import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* AES 加解密工具类
*/
public class AESUtils {
private static String KEY = "1234567890ABCDEF";
private static String OFFSET = "1234567890ABCDEF";
/**
* ECB 电码本模式加密
* @param content 待加密内容
* @param key 秘钥
*/
public static String aesECBEncrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
return Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
}
/**
* ECB 电码本模式解密
* @param content 待解密内容
* @param key 秘钥
*/
public static String aesECBDecrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
return new String(cipher.doFinal(Base64.decodeBase64(content)), StandardCharsets.UTF_8);
}
/**
* CBC 密码分组链接模式加密,需要一个向量iv,可增加加密算法的强度
* @param content 待加密内容
* @param key 秘钥
* @param offset 偏移量字符串
*/
public static String aesCBCEncrypt(String content, String key,String offset) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(encrypted);
}
/**
* CBC 密码分组链接模式解密
* @param content 待解密内容
* @param key 秘钥
* @param offset 偏移量字符串
*/
public static String aesCBCDecrypt(String content, String key,String offset) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
byte[] encrypted = cipher.doFinal(Base64.decodeBase64(content));
return new String(encrypted, StandardCharsets.UTF_8);
}
}
AES 加密工具类
最新推荐文章于 2024-08-08 14:59:03 发布