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.
79 lines
2.4 KiB
79 lines
2.4 KiB
package com.ynxbd.push.helper;
|
|
|
|
|
|
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加密算法
|
|
*/
|
|
public class AesCodeHelper {
|
|
|
|
private final static String KEY = "ynxbdysdssjtwrin";
|
|
|
|
private final static String IV = "ynxbdqsdsbjtwrin";
|
|
|
|
public static String enCode(String data) {
|
|
if (data == null) {
|
|
return null;
|
|
}
|
|
return encryptHex(data, KEY, IV);
|
|
}
|
|
|
|
public static String deCode(String data) {
|
|
if (data == null) {
|
|
return null;
|
|
}
|
|
return decryptHex(data, KEY, IV);
|
|
}
|
|
|
|
|
|
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) {
|
|
e.printStackTrace();
|
|
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());
|
|
String hexPass = Hex.encodeHexString(encrypted);
|
|
return hexPass.toUpperCase();
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
return null;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// public static void main(String[] args) throws Exception {
|
|
// String a = decryptHex("", "wsqysqsdssjtwmaa", "xbzynydykkxxkkbb");
|
|
// System.out.println(a);
|
|
// }
|
|
} |