Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate RSA key pair and encode public as string

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

like image 757
Angela Avatar asked Nov 10 '09 16:11

Angela


People also ask

How do you generate an RSA Keypair in Java?

Generate RSA Key Pair We can easily do it by using the KeyPairGenerator from java. security package: KeyPairGenerator generator = KeyPairGenerator. getInstance("RSA"); generator.

How can I change private key to public key?

Get the public key from the private key with ssh-keygen-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout. -f filename Specifies the filename of the key file.


1 Answers

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]
    }
}
like image 92
jitter Avatar answered Oct 17 '22 08:10

jitter