java aes的加密解密代码模板
时间: 2023-04-03 21:04:42 浏览: 76
以下是 Java AES 加密解密的代码模板:
加密:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesEncryption {
private static final String ALGORITHM = "AES";
private static final String KEY = "mySecretKey12345"; // 密钥,必须是16位
public static String encrypt(String value) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedValue = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encryptedValue);
}
public static String decrypt(String encryptedValue) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedValue = Base64.getDecoder().decode(encryptedValue);
byte[] decryptedValue = cipher.doFinal(decodedValue);
return new String(decryptedValue);
}
public static void main(String[] args) throws Exception {
String originalValue = "Hello World";
String encryptedValue = encrypt(originalValue);
String decryptedValue = decrypt(encryptedValue);
System.out.println("Original Value: " + originalValue);
System.out.println("Encrypted Value: " + encryptedValue);
System.out.println("Decrypted Value: " + decryptedValue);
}
}
```
解密:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesDecryption {
private static final String ALGORITHM = "AES";
private static final String KEY = "mySecretKey12345"; // 密钥,必须是16位
public static String decrypt(String encryptedValue) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedValue = Base64.getDecoder().decode(encryptedValue);
byte[] decryptedValue = cipher.doFinal(decodedValue);
return new String(decryptedValue);
}
public static void main(String[] args) throws Exception {
String encryptedValue = "u1ZzC5j+J9tX9OyJvGy3qA==";
String decryptedValue = decrypt(encryptedValue);
System.out.println("Encrypted Value: " + encryptedValue);
System.out.println("Decrypted Value: " + decryptedValue);
}
}
```