【问题标题】:Converting byte array to publickey ECDSA将字节数组转换为公钥 ECDSA
【发布时间】:2015-06-19 19:16:43
【问题描述】:

我需要使用 ECDSA 算法来签署消息并在 java 中发送给接收者。然后,接收方应验证发送方的签名。

因此,为此,接收方拥有发送方的公钥,但在通过以下命令将java.security.PublicKey 转换为字节数组后采用字节数组格式:

byte[] byteArrayPublicKey = publickey.getEncoded();

ECDSA算法中公钥的格式(转换为字节数组前)如下:

公钥:

X: 8a83c389e7bb817c17bf2db4ed71055f18342b630221b2a3a1ca752502dc2e21

Y: 3eaf48c9ab1700fe0966a0cde196b85af66bb8f0bacef711c9dca2368f9d8470

但是,问题是将此字节数组转换为可用格式,以验证接收者签名为java.security.PublicKey

一般来说,有什么解决方案可以验证签名而不将其转换为字节数组?换句话说,问题是通过发送者的公钥验证签名,使用任何方法。

【问题讨论】:

标签: java key signature public-key ecdsa


【解决方案1】:

但是,问题是将此字节数组转换为可用格式,以验证接收者的签名是 java.security.PublicKey。

你可以这样解决问题:

public static ECPublicKey genEcPubKey() throws Exception {
    KeyFactory factory = KeyFactory.getInstance("ECDSA", "BC");
    java.security.PublicKey ecPublicKey = (ECPublicKey) factory
            .generatePublic(new X509EncodedKeySpec(Helper
                    .toByte(ecRemotePubKey))); // Helper.toByte(ecRemotePubKey)) is java.security.PublicKey#getEncoded()
    return (ECPublicKey) ecPublicKey;
}

请注意,您需要 BouncyCastle 提供者来执行此操作。

但问题仍然存在,如何生成私钥?

public KeyPair ecKeyPairGenerator(String curveName) throws Exception {
    KeyPair keyPair;
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            "ECDSA", "BC");
    ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(
            curveName);
    keyPairGenerator.initialize(ecGenParameterSpec, new SecureRandom());
    keyPair = keyPairGenerator.generateKeyPair();
    java.security.PublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
    System.out.println("JAVA EC PublicKey: "
            + Helper.toHex(ecPublicKey.getEncoded()));

    // write private key into a file. Just for testing purpose
    FileOutputStream fileOutputStream = new FileOutputStream(
            "ECPrivateKey.key");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(
            fileOutputStream);
    objectOutputStream.writeObject(keyPair.getPrivate());
    objectOutputStream.close();
    return keyPair;
}

我在github 中有用于 EC 签名/验证的完整运行代码。你可以看看更好的理解。

【讨论】:

  • Rakeb void,非常感谢您的有用和出色的回答。应该补充一点,我在这里的另一个问题中解释了它:stackoverflow.com/questions/30956867/… 这件事是在签名和验证方面尊重 ASN.1。
  • 如果这是您正在寻找的答案,请尝试接受它。泰。
  • 我尝试投票支持它接受这个答案,但事实上,这需要至少 15 名声望。我的声望是 7。一旦我能够投票,我就会尝试这样做。
  • 没有“BC”有没有办法使用?我想知道oracle jre是否有KeyFactory的ECDSA算法?
  • 如何在 C/C++ 中做到这一点?
猜你喜欢
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 2022-01-06
  • 1970-01-01
  • 2015-10-19
  • 2011-03-17
相关资源
最近更新 更多