Repository navigation
Expand file tree
/
Copy pathSymmEncoder.java
More file actions
66 lines (56 loc) · 1.92 KB
/
Copy pathSymmEncoder.java
File metadata and controls
66 lines (56 loc) · 1.92 KB
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
package org.tron.common.crypto;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SymmEncoder {
public static SecretKey restoreSecretKey(byte[] secretBytes, String algorithm) {
SecretKey secretKey = new SecretKeySpec(secretBytes, algorithm);
return secretKey;
}
public static byte[] AES128EcbEnc(byte[] plain, byte[] aesKey) {
if (aesKey == null || aesKey.length != 16) {
logger.error("AesKey need 16 bytes !!!");
return null;
}
if (plain == null || (plain.length & 0x0F) != 0) {
logger.error("The length of encoded must be a multiple of 16 !!!");
return null;
}
SecretKey key = restoreSecretKey(aesKey, "AES");
return AesEcbEncode(plain, key);
}
public static byte[] AES128EcbDec(byte[] encoded, byte[] aesKey) {
if (aesKey == null || aesKey.length != 16) {
logger.error("AesKey need 16 bytes !!!");
return null;
}
if (encoded == null || (encoded.length & 0x0F) != 0) {
logger.error("The length of encoded must be a multiple of 16 !!!");
return null;
}
SecretKey key = restoreSecretKey(aesKey, "AES");
return AesEcbDecode(encoded, key);
}
private static byte[] AesEcbEncode(byte[] plainText, SecretKey key) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private static byte[] AesEcbDecode(byte[] encodedText, SecretKey key) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encodedText);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}