import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class AESAndRSAUtil {
public static String aesEncrypt(String plaintext, byte[] key, String mode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String rsaEncrypt(String plaintext, Key rsaPublicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String rsaDecrypt(String encryptedText, Key rsaPrivateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(original);
}
public static String aesDecrypt(String encryptedText, byte[] key, String mode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(original);
}
public static void main(String[] args) throws Exception {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(256);
SecretKey aesSecretKey = aesKeyGenerator.generateKey();
byte[] aesKey = aesSecretKey.getEncoded();
KeyPairGenerator rsaKeyPairGenerator = KeyPairGenerator.getInstance("RSA");
rsaKeyPairGenerator.initialize(2048);
KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();
PublicKey rsaPublicKey = rsaKeyPair.getPublic();
PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();
String data = "Hello World";
String aesEncryptedECB = aesEncrypt(data, aesKey, "ECB");
System.out.println("AES Encrypted (ECB): " + aesEncryptedECB);
String aesEncryptedCTR = aesEncrypt(data, aesKey, "CTR");
System.out.println("AES Encrypted (CTR): " + aesEncryptedCTR);
String aesDecryptedECB = aesDecrypt(aesEncryptedECB, aesKey, "ECB");
System.out.println("AES Decrypted (ECB): " + aesDecryptedECB);
String rsaEncrypted = rsaEncrypt(data, rsaPublicKey);
System.out.println("RSA Encrypted: " + rsaEncrypted);
String rsaDecrypted = rsaDecrypt(rsaEncrypted, rsaPrivateKey);
System.out.println("RSA Decrypted: " + rsaDecrypted);
}
}
- `aesEncrypt`和`aesDecrypt`方法接受一个模式参数,允许动态选择AES的加密模式。
- RSA的加解密使用标准的`RSA`算法名称,不涉及模式选择。
- AES的ECB和CTR模式使用`PKCS5Padding`填充方式,而GCM模式通常使用`NoPadding`。
- RSA的公钥和私钥是通过`KeyPairGenerator`生成的,可以用于加密和解密。
- 使用了`Base64`编码来处理加密后的字节数据,以便打印或存储。