@Slf4j
public class AesUtils {
/**
* 编码格式
*/
public static final String ENCODING = "utf-8";
/**
* 密钥算法
*/
private static final String KEY_ALGORITHM = "AES";
//padding模式
//NoPadding
//PKCS5Padding
//ISO10126Padding
//PaddingMode.Zeros
//PaddingMode.PKCS7
public static String encryptCFB(String content, String key) {
try {
Cipher aesCFB = Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), KEY_ALGORITHM);
final Random random = new SecureRandom();
byte[] iv = new byte[16];
random.nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
aesCFB.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] contentBytes = content.getBytes();
//补0
int remainder = contentBytes.length % 16;
byte[] finalBytes = new byte[contentBytes.length + 16 - remainder];
if (remainder != 0){
System.arraycopy(contentBytes,0, finalBytes,0, contentBytes.length);
}else {
finalBytes = contentBytes;
}
byte[] encryptBytes = aesCFB.doFinal(finalBytes);
//结果数组加上iv
byte[] bytes1 = new byte[contentBytes.length + 16];
System.arraycopy(iv, 0,bytes1,0,16);
System.arraycopy(encryptBytes,0,bytes1,16,contentBytes.length);
return Base64.getEncoder().encodeToString(bytes1);
} catch (Exception ex) {
log.error("encryptCFB error:", ex);
}
return null;
}
/***
* @paramcontent 待解密内容,字符串形式
* @paramkey 解密用的密钥
* @return 使用字符串形式返回解密内容
* @throws Exception
**/
public static String decryptCFB(String content, String key) {
try {
Cipher aesCFB = Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
byte[] decodeBytes = Base64.getMimeDecoder().decode(content);
byte[] iv = new byte[16];
byte[] realBytes = new byte[decodeBytes.length - 16];
System.arraycopy(decodeBytes,0, iv,0,16);
System.arraycopy(decodeBytes,16,realBytes,0,decodeBytes.length - 16);
int remainder = realBytes.length % 16;
byte[] finalBytes = new byte[realBytes.length + 16 - remainder];
if (remainder != 0){
System.arraycopy(realBytes,0, finalBytes,0, realBytes.length);
}else {
finalBytes = realBytes;
}
IvParameterSpec ivSpec = new IvParameterSpec(iv);
aesCFB.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] result = aesCFB.doFinal(finalBytes);
byte[] bytes1 = new byte[realBytes.length];
System.arraycopy(result,0, bytes1,0, realBytes.length);
String AES_decode = new String(bytes1, ENCODING);
return AES_decode;
} catch (Exception ex) {
log.error("decryptCFB error:", ex);
}
return null;
}
}
注意:Base64解密的方式由getDecoder()替换成getMimeDecoder()