You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
2.3 KiB
65 lines
2.3 KiB
2 years ago
|
package com.ynxbd.common.helper.common;
|
||
|
|
||
|
|
||
|
import lombok.extern.slf4j.Slf4j;
|
||
|
import org.apache.commons.codec.binary.Hex;
|
||
|
|
||
|
import javax.crypto.Cipher;
|
||
|
import javax.crypto.spec.IvParameterSpec;
|
||
|
import javax.crypto.spec.SecretKeySpec;
|
||
|
import java.nio.charset.StandardCharsets;
|
||
|
|
||
|
/**
|
||
|
* AES加密算法
|
||
|
*/
|
||
|
@Slf4j
|
||
|
public class AesHelper {
|
||
|
|
||
|
public static String decryptHex(String data, String key, String iv) {
|
||
|
try {
|
||
|
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||
|
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
|
||
|
|
||
|
return new String(cipher.doFinal(Hex.decodeHex(data.toCharArray())));
|
||
|
} catch (Exception e) {
|
||
|
log.warn(e.getMessage());
|
||
|
return null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Aes加密算法( Hex)
|
||
|
*
|
||
|
* @param data 加密数据
|
||
|
* @param key 密钥(16位)
|
||
|
* @param iv 密钥偏移量
|
||
|
* @return 加密后的数据
|
||
|
*/
|
||
|
public static String encryptHex(String data, String key, String iv) {
|
||
|
try {
|
||
|
if (key == null || key.length() != 16) {
|
||
|
throw new Exception("Key长度不是16位");
|
||
|
}
|
||
|
|
||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //"算法/模式/补码方式"
|
||
|
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"), new IvParameterSpec(iv.getBytes()));
|
||
|
byte[] encrypted = cipher.doFinal(data.getBytes());
|
||
|
return Hex.encodeHexString(encrypted).toUpperCase();
|
||
|
} catch (Exception e) {
|
||
|
log.warn(e.getMessage());
|
||
|
return null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static void main(String[] args) throws Exception {
|
||
|
long beg = System.currentTimeMillis();
|
||
|
String encrypt = encryptHex("文字123", "wsqysqsdssjtwmyd", "xbzynydykkxxkkll");
|
||
|
System.out.println(encrypt);
|
||
|
long end = System.currentTimeMillis();
|
||
|
|
||
|
System.out.println(end - beg);
|
||
|
String a = decryptHex("111123", "wsqysqsdssjtwmyd", "xbzynydykkxxkkll");
|
||
|
System.out.println(a);
|
||
|
}
|
||
|
}
|