天天看点

java 实现 AES 加密 解密

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>      
import org.apache.commons.codec.binary.Base64;

public class AESUtil {


    // 加密
    public static String Encrypt(String sSrc, String sKey) {
        try {
            log.info("加密前报文:{}",sSrc);
            if (checkParam(sKey)) return null;
            byte[] raw = sKey.getBytes("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("utf-8"));
            String str = new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
            log.info("加密后报文:{}",str);
            return str;
        } catch (Exception e) {
            log.error("加密失败:{}", e);
        }
        return null;
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) {
        try {
            log.info("解密前报文:{}",sSrc);
            // 判断Key是否正确
            if (checkParam(sKey)) return null;

            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] original = cipher.doFinal(new Base64().decode(sSrc));
            String originalString = new String(original, "utf-8");
            log.info("解密后报文:{}",originalString);
            return originalString;
        } catch (Exception e) {
            log.info("解密失败,error:{}", e);

        }
        return null;
    }

    public static boolean checkParam(String sKey) {
        if (sKey == null) {
            log.error("Key为空");
            return true;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            log.error("Key长度不是16位");
            return true;
        }
        return false;
    }

    public static String encrypt(JsonResult jsonResult) {
        String str = AESUtil.Encrypt(Json.toString(jsonResult), Constant.KEY);
        return str;
    }
}