java实现aes加密
时间: 2023-10-10 17:15:39 浏览: 39
以下是Java实现AES加密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesEncryption {
private static final String AES_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String IV_PARAMETER = "0123456789abcdef";
private static final String SECRET_KEY = "0123456789abcdef0123456789abcdef";
public static byte[] encrypt(byte[] data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER.getBytes());
Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER.getBytes());
Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(data);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
byte[] encrypted = encrypt(plainText.getBytes());
byte[] decrypted = decrypt(encrypted);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted: " + new String(encrypted));
System.out.println("Decrypted: " + new String(decrypted));
}
}
```
该示例代码使用AES/CBC/PKCS5Padding算法进行加密和解密。SECRET_KEY和IV_PARAMETER是密钥和初始向量,可以根据实际需求修改。