RSA 加密算法实现 java
时间: 2023-11-18 07:46:27 浏览: 67
RSA加密算法是一种非对称加密算法,它的加密和解密使用不同的密钥。下面是Java实现RSA加密算法的代码示例:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
public class RSAUtil {
private static final String ALGORITHM = "RSA";
private static final String PROVIDER = "BC"; // Bouncy Castle Provider
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
/**
* 生成公钥和私钥对
*/
public static KeyPair generateKeyPair(int keySize) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER);
keyPairGenerator.initialize(keySize);
return keyPairGenerator.generateKeyPair();
}
/**
* RSA加密
*/
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* RSA解密
*/
public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
}
}
```
使用示例:
```java
// 生成公钥和私钥对
KeyPair keyPair = RSAUtil.generateKeyPair(1024);
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密
String plaintext = "Hello world!";
byte[] encryptedData = RSAUtil.encrypt(plaintext.getBytes(), publicKey);
// 解密
byte[] decryptedData = RSAUtil.decrypt(encryptedData, privateKey);
String decryptedText = new String(decryptedData);
System.out.println("明文:" + plaintext);
System.out.println("加密后:" + new String(encryptedData));
System.out.println("解密后:" + decryptedText);
```
需要注意的是,这段代码中使用了Bouncy Castle Provider作为加密算法的提供者,需要先下载并导入Bouncy Castle的jar包。