AES加密解密

java

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
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

public static String encrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
return Base64.encodeBase64String(encryptedByte);
}

public static String decrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.DECRYPT_MODE);
byte[] decryptedByte = cipher.doFinal(Base64.decodeBase64(data));
return new String(decryptedByte);
}

private static Cipher initCipher(String key, int encryptMode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(encryptMode, new SecretKeySpec(key.getBytes(), "AES"));
return cipher;
}

public static void main(String[] args) throws Exception {
// 16字节秘钥即128比特
String key = "1234567890123456";
String value = "HelloWorld";

// 16进制的加密参数key
System.out.println("key hex: " + Hex.encodeHexString(key.getBytes()));

// 加密
String encrypt = encrypt(key, value);
System.out.println("encrypt: " + encrypt);
// 解密
String decrypt = decrypt(key, encrypt);
System.out.println("decrypt: " + decrypt);
}

}

angular

1
npm i crypto-js
1
2
3
4
5
6
7
8
9
import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse('1234567890123456');
const value = CryptoJS.enc.Utf8.parse('HelloWorld');
const encrypted = CryptoJS.AES.encrypt(value, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(encrypted.toString());
>