gpt4 book ai didi

带有 SHAwithECDSA 的 Java Signature.sign() 在多次运行时产生不同的结果

转载 作者:行者123 更新时间:2023-12-05 04:10:04 24 4
gpt4 key购买 nike

我正在尝试使用 SHAwithECDSA 对一个不会改变的字节流进行签名,私钥也不会改变。无论您运行代码的频率如何,这都应该产生相同的结果。然而,我遇到了一些我无法解释的随机性,因为每次运行时结果输出都会发生变化。

这是我所做的(最小示例):

public byte[] sign() {
Signature ecdsa = Signature.getInstance("SHA256withECDSA", "SunEC");

// This is a hexadecimal byte sequence I need to sign
String dataToBeSigned = "808112B43A3A381D1797BBBBBB973B99" +
"9737B93397AA2917B1B0B737B734B1B0" +
"B616B2BC3497A1AB43A3A381D1797BBB" +
"BBB973B999737B933979918181897981" +
"A17BC36B63239B4B396B6B7B93291B2B" +
"1B239B096B9B430991A9B22062349443" +
"1025687474703A2F2F7777772E77332E" +
"6F72672F54522F63616E6F6E6963616C" +
"2D6578692F4852D0E8E8E0745E5EEEEE" +
"EE5CEE665CDEE4CE5E646060625E6068" +
"5EF0DAD8CADCC646E6D0C2646A6C841A" +
"36BC07A00CB7DCAD662F3088A60A3D6A" +
"99431F81C122C2E9F1678EF531E95523" +
"70";

String hexPrivKey = "B9134963F51C4414738435057F97BBF1" +
"010CABCB8DBDE9C5D48138396AA94B9D";
byte[] privKey = DatatypeConverter.parseHexBinary(hexPrivKey);

ecdsa.initSign(getPrivateKey(privKey));
ecdsa.update(dataToBeSigned);
byte[] signature = ecdsa.sign();

System.out.println("Signature: " + DatatypeConverter.printHexBinary(signature));
}

public ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
try {
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256r1"));

ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);

ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);

return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
System.out.println(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
return null;
}
}

您是否有任何提示,为什么我每次运行此代码时都不会产生相同的签名输出?提出了类似的问题here ,但还没有找到真正的答案。

另一个与此相关的问题:我看到 Signature 类提供了另一个 initSign 方法:initSign(私钥私钥,SecureRandom 随机)为什么我要在创建签名时插入随机源/种子?如果随机种子未知,接收方应该如何验证该签名?

感谢您的宝贵意见!马克

最佳答案

specification of the algorithm解释一下:

One characteristic of DSA and ECDSA is that they need to produce, for each signature generation, a fresh random value (hereafter designated as k). For effective security, k must be chosen randomly and uniformly from a set of modular integers, using a cryptographically secure process. Even slight biases in that process may be turned into attacks on the signature schemes.

所以您所看到的是完全正常的。当然,算法的设计者让接收者可以验证签名,否则就没有意义了。这就是您的测试应该验证的内容。

关于带有 SHAwithECDSA 的 Java Signature.sign() 在多次运行时产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44969868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com