package com.example.cipher.aes;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.jupiter.api.Test;
public class AesTest {
@Test
public void aesTest3() {
String plaintext = getUuid(32);
// 如果分组模式使用CBC、CFB、OFB、CTR,则需要一个初始化向量IV
String transformation = "AES/CBC/PKCS5Padding";
// aes算法的初始化向量只能是16字节(128bit)
String initIv = getUuid(16);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initIv.getBytes(StandardCharsets.UTF_8));
encryptAndDecryptTest(plaintext, transformation, ivParameterSpec);
}
@Test
public void aesTest2() {
String plaintext = getUuid(32);
encryptAndDecryptTest(plaintext, "AES/ECB/PKCS5Padding", null);
}
@Test
public void simpleAesTest() {
String plaintext = getUuid(8);
encryptAndDecryptTest(plaintext, "AES", null);
}
private void encryptAndDecryptTest(String plaintext, String transformation, IvParameterSpec ivParameterSpec) {
try {
System.out.println("plaintext = " + plaintext);
String originKey = getUuid(32);
// aes算法支持的秘钥长度有128、192、256比特,也就是16、24、32字节
SecretKeySpec key = new SecretKeySpec(originKey.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance(transformation);
if (ivParameterSpec != null) {
cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
} else {
cipher.init(Cipher.ENCRYPT_MODE, key);
}
byte[] encryptBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
String encryptStr = Base64.getEncoder().encodeToString(encryptBytes);
System.out.println("encryptStr = " + encryptStr);
if (ivParameterSpec != null) {
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
byte[] decryptBytes = cipher.doFinal(encryptBytes);
String decryptStr = new String(decryptBytes);
System.out.println("decryptStr = " + decryptStr);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getUuid(int len) {
String uuid = UUID.randomUUID().toString().toLowerCase(Locale.US).replaceAll("-", "");
return uuid.substring(0, len);
}
}
在Java中使用AES实现加解密
最新推荐文章于 2024-08-27 12:12:26 发布
本文档展示了AES加密算法在CBC模式和ECB模式下的应用,通过`AesTest`类的测试方法,详细讲解了如何使用AES-CBC与AES-ECB进行加解密操作,并演示了密钥和初始化向量对加密效果的影响。
摘要由CSDN通过智能技术生成