0

I have created a ECDSA key and now need to convert this to SSH2 key.

   final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA");
    ECGenParameterSpec params = new ECGenParameterSpec("secp384r1");
    keyGen.initialize(params);
    final KeyPair keyPair = keyGen.generateKeyPair();

    //format publicKey in ssh2
    final ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
     
    writeJavaECPublicKeyToSSH2(ecPublicKey)  ??

How do we implement this ?

Vicky
  • 1
  • 2

1 Answers1

0

FYI, Java encodes the public key using a X.509 ASN.1 structure by default. This will include a bunch of OIDs and data along with the actual public key. Below an example of such public keys, parsed as ASN.1:

Certificate SEQUENCE (2 elem)
  tbsCertificate TBSCertificate SEQUENCE (2 elem)
    serialNumber CertificateSerialNumber OBJECT IDENTIFIER 1.2.840.10045.2.1 ecPublicKey (ANSI X9.62 public key type)
    signature AlgorithmIdentifier OBJECT IDENTIFIER 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)
  signatureAlgorithm AlgorithmIdentifier BIT STRING (776 bit) 0000010000111101111101100100011011000101001001010110101101001100000010…

A public key generated with the same curve using ssh-keygen will be much shorter as it follows a lighter structure:

Certificate OCTET STRING (75 byte) D66E8AADFAAB2D0E01BDF125B1C5869B723D10C054F553E6C874E901C2A81F1B3E5DDF…

Fortunately, BouncyCastle includes OpenSSH util classes: OpenSSHPrivateKeyUtil and OpenSSHPublicKeyUtil, which allow such conversions. In your case, it would boil down to this:

/** Imports:
 * import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
 * import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil;
 * import java.util.Base64;
**/

private String writeJavaECPublicKeyToSSH2(final ECPublicKey publicKey) {
  AsymmetricKeyParameter key = PublicKeyFactory.createKey(publicKey.getEncoded());
  final String sshKey = OpenSSHPublicKeyUtil.encodePublicKey(key);
  return = "ecdsa-sha2-nistp384 " + Base64.getEncoder().encodeToString(sshKey);
}

One comment: your call to KeyPairGenerator.getInstance("ECDSA") is incorrect. It should be KeyPairGenerator.getInstance("EC").

veebee
  • 391
  • 2
  • 12