#
Junjie
1 天以前 536e17a446c170a8b214aaf188b98817ee6258c1
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
package com.core.common;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
 
public class AesUtils {
 
    private static final String DEFAULT_CHARSET = "utf-8";
    private static final int DEFAULT_KEY_LENGTH = 16;
 
    public static String encrypt(String data, String key) {
        try {
            if (key == null || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) {
                return null;
            }
            byte[] raw = key.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(data.getBytes(StandardCharsets.UTF_8));
            return RadixTools.bytesToHexStr(encrypted);
        } catch (Exception ex) {
            return null;
        }
    }
 
    public static String decrypt(String data, String key) {
        try {
            if (key == null || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) {
                return null;
            }
            byte[] raw = key.getBytes(StandardCharsets.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(RadixTools.hexStringToBytes(data));
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            return null;
        }
    }
 
    public static void main(String[] args) {
        String key = "123456";
        String data = "15988786205&timestamp=" + (System.currentTimeMillis() + 5000000L);
        System.out.println(System.currentTimeMillis() + 5000000L);
        System.out.println(encrypt(data, key));
    }
}