新增方法

This commit is contained in:
wenc000 2020-10-29 18:42:46 +08:00
parent f1b6258dc3
commit b48dbd5e27

View File

@ -14,6 +14,14 @@ import java.security.SecureRandom;
public class AesUtil {
private static final String IV_STRING = "16-Bytes--String";
/**
* PKCS#7
*/
public static final String PKCS_7 = "PKCS7Padding";
/**
* PKCS#5
*/
public static final String PKCS_5 = "PKCS5Padding";
/**
* AES加密
@ -84,15 +92,27 @@ public class AesUtil {
* @throws Exception
*/
public static String aesCommonEncoder(String key, String content) throws Exception {
byte[] encryptedBytes = aesCommonEncodeDetail(key, content, IV_STRING.getBytes(), PKCS_5);
return new String(Base64.encodeBase64(encryptedBytes), "UTF-8");
}
/**
* 通用aes加密兼容IOS
*
* @param key
* @param content
* @param paddingType
* @return
* @throws Exception
*/
public static byte[] aesCommonEncodeDetail(String key, String content, byte[] ivBytes, String paddingType) throws Exception {
byte[] byteContent = content.getBytes("UTF-8");
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/" + paddingType);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
return new String(Base64.encodeBase64(encryptedBytes), "UTF-8");
return cipher.doFinal(byteContent);
}
/**
@ -105,13 +125,26 @@ public class AesUtil {
*/
public static String aesCommonDecoder(String key, String content) throws Exception {
byte[] encryptedBytes = Base64.decodeBase64(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
byte[] keyBytes = key.getBytes();
byte[] result = aesCommonDecoderDetail(keyBytes, encryptedBytes, IV_STRING.getBytes(), PKCS_5);
return new String(result, "UTF-8");
}
/**
* aes cbc 通用解密
*
* @param keyBytes 秘钥字节数组
* @param encryptedBytes 密文字节数组
* @param ivBytes 向量字节数组
* @param paddingType 填充类型
* @return
* @throws Exception
*/
public static byte[] aesCommonDecoderDetail(byte[] keyBytes, byte[] encryptedBytes, byte[] ivBytes, String paddingType) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/" + paddingType);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
return cipher.doFinal(encryptedBytes);
}
}