gpt4 book ai didi

java - java中的RSA签名和验证

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:02 26 4
gpt4 key购买 nike

我正在尝试用 java 对消息进行签名,但它似乎不起作用。验证步骤给了我错误。

谁能告诉我我的错误在哪里。我不明白我做错了什么。谢谢

String messageString = "text";
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey RSAPublicKey = keyPair.getPublic();
PrivateKey RSAPrivateKey = keyPair.getPrivate();

System.out.println("public key = " + RSAPublicKey);
System.out.println("private key = " + RSAPrivateKey);

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Signature signature = Signature.getInstance("SHA1withRSA", "BC");
signature.initSign(RSAPrivateKey, new SecureRandom());
byte[] message = messageString.getBytes();
signature.update(message);
byte[] sigBytes = signature.sign();

Signature signature1 = Signature.getInstance("SHA1withRSA", "BC");
signature1.initVerify(RSAPublicKey);
signature1.update(sigBytes);

boolean result = signature1.verify(sigBytes);
System.out.println("result = "+result);
} catch (NoSuchAlgorithmException | NoSuchProviderException | SignatureException | InvalidKeyException ex) {

} }

最佳答案

您的签名在变量 sigBytes 中,您的消息在变量 message 中。要验证消息,请先执行 signature1.update(message),然后执行 signature1.verify(sigBytes)

以下代码示例验证签名:

Signature signature1 = Signature.getInstance("SHA1withRSA", "BC");
signature1.initVerify(RSAPublicKey);
signature1.update(message);
boolean result = signature1.verify(sigBytes);

:)

关于java - java中的RSA签名和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179959/

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