aes加密算法javacbc
时间: 2023-10-13 17:07:45 浏览: 26
下面是一个使用Java实现AES加密算法的示例代码,采用CBC模式:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String IV_PARAMETER_SPEC = "0123456789ABCDEF";
private static final String KEY_SPEC = "0123456789ABCDEF0123456789ABCDEF";
public static String encrypt(String data) throws Exception {
byte[] iv = IV_PARAMETER_SPEC.getBytes(StandardCharsets.UTF_8);
byte[] key = KEY_SPEC.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String encryptedData) throws Exception {
byte[] iv = IV_PARAMETER_SPEC.getBytes(StandardCharsets.UTF_8);
byte[] key = KEY_SPEC.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decrypted, StandardCharsets.UTF_8);
}
}
```
其中,IV_PARAMETER_SPEC和KEY_SPEC分别表示初始化向量和密钥,需要根据具体的应用场景进行设置。使用示例:
```java
public static void main(String[] args) throws Exception {
String data = "Hello, World!";
String encryptedData = AESUtil.encrypt(data);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = AESUtil.decrypt(encryptedData);
System.out.println("Decrypted data: " + decryptedData);
}
```