1、AES-128加密算法:
package com.arithmetic.encryption;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
//使用Java的javax.crypto包提供的AES算法实现加密和解密功能。
//AES_ALGORITHM表示使用CBC模式和PKCS5Padding填充,AES_KEY和AES_IV分别为密钥和初始向量,需要使用16字节长度的byte数组。
//在encrypt方法中,首先使用Cipher.getInstance方法获取实现指定算法的Cipher对象,并使用密钥和初始向量进行初始化。
//调用cipher.doFinal方法对明文进行加密,并使用Base64进行编码,返回加密后的密文。
//在decrypt方法中,同样使用Cipher.getInstance方法获取Cipher对象,并使用相同的密钥和初始向量初始化。
//调用cipher.doFinal方法对Base64解码后的密文进行解密,并将解密后的字节数组转换为字符串返回。
//在main方法中,测试加密和解密的功能
//定义一个明文字符串,然后调用encrypt方法对明文进行加密,将得到的密文打印输出。
//调用decrypt方法对密文进行解密,并将解密后的明文打印输出。
//示例代码中的密钥和初始向量是硬编码的,实际应用中,应该根据安全要求生成随机的密钥和初始向量,并妥善保管。
public class AES128EncryptionDemo {
private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String AES_KEY = "0123456789abcdef"; // 16字节的密钥
private static final String AES_IV = "0123456789abcdef"; // 16字节的初始向量
public static String encrypt(String plaintext) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String ciphertext) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) {
try {
String plaintext = "Hello, world!";
String ciphertext = encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext);
System.out.println("Decrypted text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、AES-256加密算法: