rsa的数字签名代码java输出签名后的内容
时间: 2024-02-25 16:56:28 浏览: 26
以下代码在 Java 基础上加入了输出签名后的内容:
```java
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import java.util.Base64;
public class RSASignatureExample {
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
// 要签名的原文
String message = "hello world";
// 对原文进行Hash
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(message.getBytes("UTF-8"));
// 生成签名
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(keyPair.getPrivate());
signature.update(messageDigest);
byte[] signatureBytes = signature.sign();
// 输出签名后的内容
String signatureStr = Base64.getEncoder().encodeToString(signatureBytes);
System.out.println("Signature: " + signatureStr);
// 验证签名
signature.initVerify(keyPair.getPublic());
signature.update(messageDigest);
boolean verified = signature.verify(signatureBytes);
if (verified) {
System.out.println("Signature is valid");
} else {
System.out.println("Signature is invalid");
}
}
}
```
输出签名后的内容可以用于传输或存储,以便在验证签名时使用。注意,为了方便输出,这里使用了 Base64 编码将签名转换为字符串。在实际应用中,需要根据实际情况选择合适的方式进行签名数据的传输和存储。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)