给定一个Java ECPublicKey ECDSA PublicKey,如何构建SSH2公钥?

nfeuvbwi  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(180)

我已经创建了一个ECDSA密钥,现在需要将其转换为SSH2密钥。

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)  ??

我们如何实现这一点?

fcg9iug3

fcg9iug31#

仅供参考,Java默认使用X.509 ASN.1结构对公钥进行编码。这将包括一堆OID和数据沿着实际公钥。下面是此类公钥的示例,解析为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…

使用ssh-keygen以相同的曲线生成的公钥将更短,因为它遵循更轻的结构:

Certificate OCTET STRING (75 byte) D66E8AADFAAB2D0E01BDF125B1C5869B723D10C054F553E6C874E901C2A81F1B3E5DDF…

幸运的是,BouncyCastle包含OpenSSH实用程序类:OpenSSHPrivateKeyUtil和OpenSSHPublicKeyUtil,它们允许这样的转换。在您的情况下,它可以归结为:

/** 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);
}

一条评论:您对 KeyPairGenerator.getInstance(“ECDSA”) 的调用不正确。它应该是 KeyPairGenerator.getInstance(“EC”)

相关问题