我正在尝试在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) {
} }
答案 0 :(得分:14)
您的签名在变量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);
:)