rsa加密算法java
时间: 2023-07-09 14:10:05 浏览: 60
RSA(Rivest–Shamir–Adleman)是一种非对称加密算法,常用于数据加密和数字签名。下面是一个简单的 Java 示例代码,演示了如何使用 RSA 加密和解密字符串。
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.RSAKeyGenParameterSpec;
import javax.crypto.Cipher;
public class RSAExample {
public static void main(String[] args) throws Exception {
// 生成 RSA 密钥对
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4));
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密字符串
String plainText = "Hello, RSA!";
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
System.out.println("Cipher text: " + new String(cipherText));
// 解密字符串
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(cipherText);
System.out.println("Decrypted text: " + new String(decryptedText));
}
}
```
需要注意的是,上面的代码使用了 Bouncy Castle 作为加密提供者。如果您没有安装 Bouncy Castle,可以从官网下载并安装。