SHA256withRSA签名与验签代码示例
时间: 2023-07-02 20:07:41 浏览: 226
rsa256 签名验签
5星 · 资源好评率100%
以下是SHA256withRSA签名与验签的Java代码示例:
**签名代码:**
```
import java.security.*;
import java.util.Base64;
public class RSASignatureExample {
public static void main(String[] args) throws Exception {
String message = "This is a message to be signed.";
// Generate key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
// Create a signature object
Signature signature = Signature.getInstance("SHA256withRSA");
// Initialize the signature object with the private key
PrivateKey privateKey = keyPair.getPrivate();
signature.initSign(privateKey);
// Update the signature object with the message
signature.update(message.getBytes());
// Sign the message
byte[] signatureBytes = signature.sign();
// Print the signature in Base64 encoding
System.out.println("Signature: " + Base64.getEncoder().encodeToString(signatureBytes));
}
}
```
**验签代码:**
```
import java.security.*;
import java.util.Base64;
public class RSASignatureExample {
public static void main(String[] args) throws Exception {
String message = "This is a message to be signed.";
String signatureString = "PLl6yBb6IhOv0Jd3k1y/YlR9a3UOx0WJQy6RbbS/3W8mQ2ztcL5x+JShHl6O8gTlJn4wtNQ7Ggz0ZiPwq9SInQf/9d4eG4qSkZCzVgP9U9bQY7jwFVhWXfzqU6l5K8SxyA2pBw+PQs0N2dJQ2Xk9V3tXZP5h+UcMXwLQe/3K7uh2M=";
// Generate key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
// Create a signature object
Signature signature = Signature.getInstance("SHA256withRSA");
// Initialize the signature object with the public key
PublicKey publicKey = keyPair.getPublic();
signature.initVerify(publicKey);
// Update the signature object with the message
signature.update(message.getBytes());
// Verify the signature
boolean verified = signature.verify(Base64.getDecoder().decode(signatureString));
// Print the verification result
System.out.println("Signature verified: " + verified);
}
}
```
以上代码示例中,我们使用SHA256withRSA算法对一个字符串进行签名和验签。在签名时,我们首先生成了一个RSA密钥对,然后使用私钥对消息进行签名,并打印出Base64编码的签名结果。在验签时,我们使用同样的RSA密钥对和签名算法,使用公钥初始化签名对象,并使用该对象对消息进行验证,最终打印验证结果。需要注意的是,验签时需要将签名结果从Base64编码中解码。
阅读全文