mitao
2025-02-21 31573d6180d15ef65ed0df9c2732495f40b12663
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package com.panzhihua.common.model.helper;
 
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;
 
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * AES 工具类
 */
public class AESUtil {
 
    private static SecretKeySpec secretKey;
    private static byte[] key;
 
    /**
     * AES 256 加密
     *
     * @param strToEncrypt
     *            要加密的字符串
     * @param secKey
     *            秘钥
     * @param salt
     *            盐
     * @return 加密后的字符串
     */
    public static String encrypt256(String strToEncrypt, String secKey, String salt) {
        try {
            byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            IvParameterSpec ivspec = new IvParameterSpec(iv);
 
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secKey.toCharArray(), salt.getBytes(), 65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
 
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }
 
    /**
     * AES 256 解密
     *
     * @param strToDecrypt
     *            要解密的字符串
     * @param secKey
     *            秘钥
     * @param salt
     *            盐
     * @return 解密后的字符串
     */
    public static String decrypt256(String strToDecrypt, String secKey, String salt) {
        try {
            byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            IvParameterSpec ivspec = new IvParameterSpec(iv);
 
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secKey.toCharArray(), salt.getBytes(), 65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
 
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
 
    public static void setKey(String myKey) {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes(StandardCharsets.UTF_8);
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * AES 128(base64)加密
     * 
     * @param strToEncrypt
     *            要加密的字符串
     * @param secret
     *            秘钥
     * @return 加密后的字符串
     */
    public static String encrypt128(String strToEncrypt, String secret)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException,
        BadPaddingException, IllegalBlockSizeException {
        setKey(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    }
 
    /**
     * AES 128(base64) 解密
     * 
     * @param strToDecrypt
     *            要解密的字符串
     * @param secret
     *            秘钥
     * @return 解密后的字符串
     */
    public static String decrypt128(String strToDecrypt, String secret) throws NoSuchPaddingException,
        NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        setKey(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    }
 
}
 
class AES256Example {
    public static void main(String[] args) {
        String originalString = "howtodoinjava.com";
 
        String secKey = "this is my super secrt key";
        String salt = "salt for me!!!";
        String encryptedString = AESUtil.encrypt256(originalString, secKey, salt);
        String decryptedString = AESUtil.decrypt256(encryptedString, secKey, salt);
 
        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}
 
class AES128Example {
    public static void main(String[] args) {
        String[] originalString = new String[] {"51011234567892013", "13612345678", "四川省成都市高新区", "四川省成都市高新"};
 
        String key = "5165465461dsfas";
 
        Arrays.stream(originalString).forEach(os -> {
            try {
                String encryptedString = AESUtil.encrypt128(os, key);
                String decryptedString = AESUtil.decrypt128(encryptedString, key);
 
                System.out.println(os);
                System.out.println(encryptedString);
                System.out.println(decryptedString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}