2
sunshine
2024-11-05 d1f9fb55a136e589a5ad588ed9a93ce9272917da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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;
        }
    }
}