Search code examples
javacryptographyprivate-keypublic-keyssh-keygen

Public key from private key in java is incorrect


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


Solution

  • 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