AES.java
2.46 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* Copyright (C) 2015 The Telink Bluetooth Light Project
*
*/
package com.telink.crypto;
import com.telink.util.Arrays;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public abstract class AES {
public static boolean Security = true;
static {
System.loadLibrary("TelinkCrypto");
}
private AES() {
}
public static byte[] encrypt(byte[] key, byte[] content)
throws NoSuchAlgorithmException, NoSuchPaddingException,
UnsupportedEncodingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException,
NoSuchProviderException {
if (!AES.Security)
return content;
key = Arrays.reverse(key);
content = Arrays.reverse(content);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(content);
}
public static byte[] decrypt(byte[] key, byte[] content)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, NoSuchProviderException {
if (!AES.Security)
return content;
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(content);
}
public static byte[] encrypt(byte[] key, byte[] nonce, byte[] plaintext) {
if (!AES.Security)
return plaintext;
return encryptCmd(plaintext, nonce, key);
}
public static byte[] decrypt(byte[] key, byte[] nonce, byte[] plaintext) {
if (!AES.Security)
return plaintext;
return decryptCmd(plaintext, nonce, key);
}
private static native byte[] encryptCmd(byte[] packet, byte[] iv, byte[] sk);
private static native byte[] decryptCmd(byte[] packet, byte[] iv, byte[] sk);
}