Generate RSA key pair and encode private as string

后端 未结 1 1858
忘了有多久
忘了有多久 2020-12-08 04:38

I want to generate 512 bit RSA keypair and then encode my public key as a string. How can I achieve this?

相关标签:
1条回答
  • 2020-12-08 05:17

    For output as Hex-String

    import java.security.*;
    public class Test {
        public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(512);
            byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
            StringBuffer retString = new StringBuffer();
            for (int i = 0; i < publicKey.length; ++i) {
                retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1));
            }
            System.out.println(retString);
        }
    }
    

    For output as byte values

    import java.security.*;
    public class Test {
        public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(512);
            byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
            StringBuffer retString = new StringBuffer();
            retString.append("[");
            for (int i = 0; i < publicKey.length; ++i) {
                retString.append(publicKey[i]);
                retString.append(", ");
            }
            retString = retString.delete(retString.length()-2,retString.length());
            retString.append("]");
            System.out.println(retString); //e.g. [48, 92, 48, .... , 0, 1]
        }
    }
    
    0 讨论(0)
提交回复
热议问题