package com.nova.sankuai.domain.api.nanjingmingtuo;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.codec.binary.Base64;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.nio.charset.StandardCharsets;
|
|
/**
|
* @author Gmw
|
*/
|
@Slf4j
|
public class AesUtil {
|
|
/**
|
* 加密
|
*
|
* @param sSrc 加密内容
|
* @param sKey 加密 key
|
*/
|
public static String encrypt(String sSrc, String sKey) throws Exception {
|
if (sKey == null) {
|
System.out.print("Key 为空 null");
|
return null;
|
}
|
// 判断 Key 是否为 16 位
|
if (sKey.length() != 16) {
|
System.out.print("Key 长度不是 16 位");
|
return null;
|
}
|
byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
|
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
|
// "算法/模式/补码方式"
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
|
byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
|
// 此处使用 BASE64 做转码功能,同时能起到 2 次加密的作用。
|
return Base64.encodeBase64String(encrypted);
|
}
|
|
/**
|
* 解密内容
|
*
|
* @param sSrc 内容
|
* @param sKey 私钥
|
*/
|
public static String decrypt(String sSrc, String sKey) throws Exception {
|
try {
|
// 判断 Key 是否正确
|
if (sKey == null) {
|
System.out.print("Key 为空 null");
|
return null;
|
}
|
// 判断 Key 是否为 16 位
|
if (sKey.length() != 16) {
|
System.out.print("Key 长度不是 16 位");
|
return null;
|
}
|
byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
|
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
|
byte[] encrypted1 = Base64.decodeBase64(sSrc);
|
try {
|
byte[] original = cipher.doFinal(encrypted1);
|
return new String(original, StandardCharsets.UTF_8);
|
} catch (Exception e) {
|
log.error("解密失败!", e);
|
return null;
|
}
|
} catch (Exception ex) {
|
log.error("解密失败!", ex);
|
return null;
|
}
|
}
|
}
|