import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAExample {
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // 密钥长度为2048位
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// 要加密的明文
String originalText = "Hello, RSA!";
System.out.println("Original Text: " + originalText);
// 使用公钥加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(originalText.getBytes());
System.out.println("Encrypted Text: " + new String(encryptedBytes));
// 使用私钥解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println("Decrypted Text: " + decryptedText);
}
}
KeyPairGenerator 类生成一个 RSA 密钥对(包括公钥和私钥),密钥长度为 2048 位。Cipher 类,并指定了加密模式为 ENCRYPT_MODE。Cipher 类,并指定了解密模式为 DECRYPT_MODE。这段代码展示了如何使用 Java 的 javax.crypto 和 java.security 包来实现 RSA 加密和解密的基本操作。
上一篇:java网络编程技术
下一篇:java快排
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站