使用hutool对称价目AES

编程

public class AESHelper {

/**

* AES加密

*

* @param content 待加密的内容

* @param encryptKey 密钥

* @param length 密钥长度

* @return 加密后code

*/

public static String encryptAes(String content, String encryptKey, KeyLength length) {

//设置密钥长度

String aesKey = getAesKey(encryptKey, length.value);

//构建 随机生成密钥

//AES aes = SecureUtil.aes(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());

//构建

AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, aesKey.getBytes());

//加密

String encryptBase64 = aes.encryptBase64(content);

return encryptBase64;

}

/**

* AES解密

*

* @param content 待解密的内容

* @param encryptKey 密钥

* @param length 密钥长度

* @return 解密后code

*/

public static String decryptAes(String content, String encryptKey, KeyLength length) {

//设置密钥长度

String aesKey = getAesKey(encryptKey, length.value);

//构建

AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, aesKey.getBytes());

//解密

byte[] decrypt = aes.decrypt(content);

//解密字符串

String res = new String(decrypt);

return res;

}

/*

*

* 获取指定长度密钥

* @param key 密钥

* @param length 密钥长度

* */

private static String getAesKey(String key,int length)

{

if (key.isEmpty())

{

throw new NullPointerException("Aes密钥不能为空");

}

if (key.length() < length)

{

key = padRight(key, length, "0");

}

if (key.length() > length)

{

key = key.substring(0, length);

}

return key;

}

/*

*

* 补位

*

* */

private static String padRight(String src, int len, char ch) {

int diff = len - src.length();

if (diff <= 0) {

return src;

}

char[] charr = new char[len];

System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());

for (int i = 0; i < diff; i++) {

charr[i] = ch;

}

return new String(charr);

}

/*

* 密钥长度

*

* */

public enum KeyLength{

Lentth16(16),

Lentth24(24),

Lentth32(32);

private final int value;

private KeyLength(int value) {

this.value = value;

}

public KeyLength valueOf(int value) {

switch (value) {

case 16:

return KeyLength.Lentth16;

case 24:

return KeyLength.Lentth24;

case 32:

return KeyLength.Lentth32;

default:

return null;

}

}

}

}

可以使用提供的随机密钥,也可以使用指定的密钥

以上是 使用hutool对称价目AES 的全部内容, 来源链接: utcz.com/z/518822.html

回到顶部