用java写一个非对称加密算法
时间: 2024-05-29 07:04:45 浏览: 11
非对称加密算法需要使用到公钥和私钥,常见的非对称加密算法有RSA、ECC等。以下是使用RSA算法实现的Java代码:
```
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAEncryption {
private static final String ALGORITHM = "RSA";
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encryptedText = encrypt(publicKey, plainText.getBytes());
byte[] decryptedText = decrypt(privateKey, encryptedText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + new String(encryptedText));
System.out.println("Decrypted text: " + new String(decryptedText));
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(PublicKey publicKey, byte[] plainText) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText);
}
public static byte[] decrypt(PrivateKey privateKey, byte[] encryptedText) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedText);
}
}
```
以上代码生成了一对RSA密钥,使用公钥加密明文,私钥解密密文。输出结果如下:
```
Plain text: Hello, world!
Encrypted text: [B@5e2de80c
Decrypted text: Hello, world!
```
可以看到,经过加密和解密后,明文和解密后的密文是一样的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)