# 2.3 加解密 demo(JAVA)

private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
private static final String AES = "AES";

/**
 *  加密  key 需 16位
 */
public static String encryptUtf8(String str, String key) {
    try {
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return java.util.Base64.getEncoder().encodeToString(encrypted);
    } catch (Exception e) {
        return null;
    }
}

/**
 *  解密  key 需 16位
 */
public static String decryptUtf8(String str, String key) {
    try {
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(java.util.Base64.getDecoder().decode(str));
        return new String(encrypted);
    } catch (Exception e) {
        return null;
    }
}
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
上次更新: 7 天前