Java工具类(27)—AES加密工具类
package com.awifi.cloudnative.container.common.utils;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.awifi.cloudnative.container.common.content.ErrorConstants;
import com.awifi.cloudnative.container.common.exception.BaseException;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AESUtil {
private static final Logger LOG = LoggerFactory.getLogger(AESUtil.class);
public static final String CODE_TYPE = "UTF-8";
public static final String AES_TYPE = "AES/ECB/NoPadding";
private static final String ENCRYPTION = "AES";
private static final String IV = "0000000000000000";
public static String getKey() {
Random random = new SecureRandom();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(3);
long result = 0;
switch (number) {
case 0:
result = Math.round(new SecureRandom().nextInt(25) + 65);
sb.append((char) result);
break;
case 1:
result = Math.round(new SecureRandom().nextInt(25) + 97);
sb.append(String.valueOf((char) result));
break;
case 2:
sb.append(String.valueOf(new SecureRandom().nextInt(10)));
break;
}
}
return sb.toString();
}
public AESUtil() {
}
public static String encrypt(String cleartext, String password) {
try {
password = appendZero2Password(password);
byte[] str = cleartext.getBytes(CODE_TYPE);
str = completionCodeFor16Bytes(str);
Cipher cipher = Cipher.getInstance(AES_TYPE);
SecretKeySpec key = new SecretKeySpec(password.getBytes(), ENCRYPTION);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(str);
String sign = Base64.encodeBase64String(encryptedData);
LOG.debug("加密后的字符串:{}", sign);
return sign;
} catch (Exception e) {
LOG.error("AES加密失败", e);
throw new BaseException(ErrorConstants.ERR_EXCEPTION_000, "AES加密失败");
}
}
public static String decrypt(String encrypted, String password) {
try {
password = appendZero2Password(password);
byte[] byteMi = Base64.decodeBase64(encrypted);
byteMi = completionCodeFor16Bytes(byteMi);
SecretKeySpec key = new SecretKeySpec(password.getBytes(), ENCRYPTION);
Cipher cipher = Cipher.getInstance(AES_TYPE);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, "utf-8").trim();
} catch (Exception e) {
LOG.error("AES解密失败" + e.getMessage());
throw new BaseException(ErrorConstants.ERR_EXCEPTION_000, "AES解密失败");
}
}
public static byte[] completionCodeFor16Bytes(byte[] str) throws UnsupportedEncodingException {
int num = str.length;
int index = 16 - num % 16;
if (index == 16) {
return str;
}
byte[] newStr = new byte[str.length + index];
System.arraycopy(str, 0, newStr, 0, str.length);
return newStr;
}
public static byte[] completionCodeFor4Bytes(byte[] str) throws UnsupportedEncodingException {
int num = str.length;
int index = 4 - num % 4;
if (index == 4) {
return str;
}
byte[] newStr = new byte[str.length + index];
System.arraycopy(str, 0, newStr, 0, str.length);
return newStr;
}
private static String appendZero2Password(String password) {
if (null == password) {
LOG.error("AES密钥长度错误");
throw new BaseException(ErrorConstants.INNER_EXCEPTION_010, "AES密钥长度错误");
}
if (password.length() == 16) {
return password;
}
StringBuilder sbBuilder = new StringBuilder(password);
sbBuilder.append("\0");
return sbBuilder.toString();
}
public static String AccountdesEncrypt(String data, String key, String iv) {
try {
byte[] encrypted1 = new Base64().decode(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString.trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}