Java函数实现AES加解密算法的示例代码
AES(Advanced Encryption Standard)是一种对称加密算法,也是目前被广泛使用的加密算法之一。在Java中,可以使用javax.crypto包下的Cipher类来实现AES加解密算法。
下面是一个示例代码,用于实现AES加解密算法,其中包括加密函数和解密函数。
### AES加密函数实现
public static String encrypt(String plaintext, String key) throws Exception {
// 将密钥转换为字节数组
byte[] byteKey = key.getBytes("UTF-8");
// 创建AES加密算法实例
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 根据密钥初始化加密算法
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 加密明文数据
byte[] bytePlaintext = plaintext.getBytes("UTF-8");
byte[] byteCiphertext = cipher.doFinal(bytePlaintext);
// 将加密后的数据转换为Base64编码格式的字符串
String ciphertext = Base64.getEncoder().encodeToString(byteCiphertext);
return ciphertext;
}
在以上代码中,encrypt()函数接受两个参数:明文数据和密钥。首先,将密钥转换为字节数组(byteKey)。
然后,创建AES加密算法实例,并使用密钥初始化加密算法(cipher)。这里采用了ECB模式和PKCS5填充方式。
接下来,将明文数据转换为字节数组(bytePlaintext),然后使用加密算法(cipher)加密该数据,得到加密后的字节数组(byteCiphertext)。
最后,将加密后的字节数组转换为Base64编码格式的字符串(ciphertext),并返回该字符串。
### AES解密函数实现
public static String decrypt(String ciphertext, String key) throws Exception {
// 将密钥转换为字节数组
byte[] byteKey = key.getBytes("UTF-8");
// 创建AES解密算法实例
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 根据密钥初始化解密算法
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 将Base64编码格式的密文数据转换为字节数组
byte[] byteCiphertext = Base64.getDecoder().decode(ciphertext);
// 解密密文数据
byte[] bytePlaintext = cipher.doFinal(byteCiphertext);
// 将解密后的数据转换为字符串
String plaintext = new String(bytePlaintext, "UTF-8");
return plaintext;
}
在以上代码中,decrypt()函数接受两个参数:密文数据和密钥。与加密函数类似,首先将密钥转换为字节数组(byteKey)。
然后,创建AES解密算法实例,并使用密钥初始化解密算法(cipher)。同样采用了ECB模式和PKCS5填充方式。
接下来,将Base64编码格式的密文数据转换为字节数组(byteCiphertext),并使用解密算法(cipher)解密该数据,得到解密后的字节数组(bytePlaintext)。
最后,将解密后的字节数组转换为字符串(plaintext),并返回该字符串。
### 示例代码使用方法
使用以上示例代码实现AES加解密算法非常简单。下面是一个测试代码示例,用于展示如何使用该算法。
public static void main(String[] args) {
try {
String plaintext = "Hello, World!";
String key = "MySecretKey12345";
// 加密明文数据
String ciphertext = AESUtil.encrypt(plaintext, key);
System.out.println("Ciphertext: " + ciphertext);
// 解密密文数据
String decrypted = AESUtil.decrypt(ciphertext, key);
System.out.println("Decrypted: " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
在以上测试代码中,首先定义了一个明文数据(plaintext)和一个密钥(key)。
然后,使用AESUtil.encrypt()函数对明文数据进行加密,得到密文数据(ciphertext),并输出到控制台。
接下来,使用AESUtil.decrypt()函数对密文数据进行解密,得到原始的明文数据(decrypted),并同样输出到控制台。
输出结果如下:
Ciphertext: FJ2DJUKl6pdC79Lgt6Yqfw== Decrypted: Hello, World!
可以看到,经过加密和解密后,原始的明文数据与解密后的数据完全一致。这说明该示例代码所实现的AES加解密算法是正确的。
