java中的RSA签名和验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21179959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RSA Signing and verifying in java
提问by Carmen Cojocaru
I'm trying to sign a message in java and it doesn't seem to work. The verifying step gives me false.
我正在尝试用 Java 签署一条消息,但它似乎不起作用。验证步骤给我错误。
Can anyone tell me where is my mistake. I can't understand what I'm doing wrong. Thanks
谁能告诉我我的错误在哪里。我无法理解我做错了什么。谢谢
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) {
} }
回答by Developer Marius ?il?nas
You have your signature in variable sigBytes
and your message is in variable message
.
To verify a message first do signature1.update(message)
and then do signature1.verify(sigBytes)
.
你的签名是可变的sigBytes
,你的信息是可变的message
。要验证消息,请先执行signature1.update(message)
然后执行 signature1.verify(sigBytes)
。
The following code example verifies signature:
以下代码示例验证签名:
Signature signature1 = Signature.getInstance("SHA1withRSA", "BC");
signature1.initVerify(RSAPublicKey);
signature1.update(message);
boolean result = signature1.verify(sigBytes);
:)
:)