rsa算法实现java
时间: 2024-01-03 18:04:35 浏览: 28
RSA算法是常用的非对称加密算法,以下是Java实现RSA算法的示例代码:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
KeyPair keyPair = generateKeyPair();
// 加密
byte[] cipherText = encrypt(plainText, keyPair.getPublic());
System.out.println("Cipher text: " + new String(cipherText));
// 解密
String decryptedText = decrypt(cipherText, keyPair.getPrivate());
System.out.println("Decrypted text: " + decryptedText);
}
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
}
```
以上代码中,`generateKeyPair`方法用于生成密钥对,`encrypt`方法用于加密,`decrypt`方法用于解密。其中,加密和解密都使用了`Cipher`类来完成。在实际使用中,需要注意安全性和效率问题。