0

I only have a private key and I need to calculate the public key from it in java. Following this answer Get public key from private in Java I came up with the following code:

String pemString = "full private key string here";
pemString = pemString.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
pemString = pemString.replace("-----END RSA PRIVATE KEY-----", "");
pemString = pemString.replace("\n", ""); //without this exception: Illegal base64 character a
logger.info(pemString);

byte[] decoded = Base64.getDecoder().decode(pemString);
KeyFactory kf = KeyFactory.getInstance("RSA");

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
PrivateKey privatekey = kf.generatePrivate(keySpec);
RSAPrivateCrtKey privk = (RSAPrivateCrtKey)privatekey;

RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent());
PublicKey pubKey = kf.generatePublic(publicKeySpec);
String pubString = Base64.getEncoder().encodeToString(pubKey.getEncoded());

logger.info(pubString);

But if I compare the output of the code with the public key that EC2 stores in .ssh/authorized keys it is not the same. What am I doing wrong?

I want to achieve ssh-keygen -y

Community
  • 1
  • 1
cen
  • 2,873
  • 3
  • 31
  • 56

1 Answers1

2

The key you are generating is in X.509 format. While the key in .ssh/authorized_keys2 is in SSH format. You can use ssh-keygen utility to do the conversion:

ssh-keygen -i -m PEM -f key.pem > ssh.pub
Community
  • 1
  • 1
divanov
  • 6,173
  • 3
  • 32
  • 51
  • Accepting your answer because it pointed out the actual problem. Managed to do it directly in java with format conversion http://stackoverflow.com/questions/3706177/how-to-generate-ssh-compatible-id-rsa-pub-from-java – cen Feb 08 '16 at 00:09