使用java代码写RSA+AES请假加密
时间: 2023-10-24 18:09:09 浏览: 133
以下是Java代码实现RSA AES加密:
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 RSAEncryption {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// 生成RSA密钥对
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密数据
String plainText = "请假申请";
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
// 解密数据
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(cipherText);
System.out.println("原始数据:" + plainText);
System.out.println("加密后数据:" + new String(cipherText));
System.out.println("解密后数据:" + new String(decryptedText));
}
}
```
AES加密:
```java
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class AESEncryption {
private static final int AES_KEY_SIZE = 128;
public static void main(String[] args) throws Exception {
// 生成AES密钥
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(AES_KEY_SIZE, new SecureRandom());
Key aesKey = keyGen.generateKey();
// 加密数据
String plainText = "请假申请";
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
// 解密数据
cipher.init(Cipher.DECRYPT_MODE, aesKey);
byte[] decryptedText = cipher.doFinal(cipherText);
System.out.println("原始数据:" + plainText);
System.out.println("加密后数据:" + new String(cipherText));
System.out.println("解密后数据:" + new String(decryptedText));
}
}
```
将RSA和AES结合使用,可以先用RSA加密AES密钥,然后使用AES加密数据,最后将加密后的AES密钥和加密后的数据一起发送。解密时,先使用RSA解密AES密钥,然后使用解密后的AES密钥解密数据。
阅读全文