-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAES.java
More file actions
75 lines (68 loc) · 1.75 KB
/
Copy pathAES.java
File metadata and controls
75 lines (68 loc) · 1.75 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
package rwb.java.divers;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static SecretKeySpec secretKey;
private static byte[] key;
/**
*
*/
private AES(){
//nothing to do [sonarqube]
}
/**
* Set the key
* @param myKey
*/
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
Log.warning(e.getMessage());
}
}
/**
*
* @param strToEncrypt
* @param secret
* @return
*/
public static String encrypt(String strToEncrypt, String secret) {
try{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
Log.warning("Error while encrypting: " + e.toString());
return null;
}
}
/**
*
* @param strToDecrypt
* @param secret
* @return
*/
public static String decrypt(String strToDecrypt, String secret) {
try{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
Log.warning("Error while decrypting: " + e.toString());
return null;
}
}
}