· 4 years ago · Apr 09, 2021, 09:32 AM
1import javax.crypto.Cipher;
2import javax.crypto.spec.IvParameterSpec;
3import javax.crypto.spec.SecretKeySpec;
4import java.nio.charset.StandardCharsets;
5
6public class AES256 {
7
8 public static String encrypt(String strToEncrypt) {
9 try {
10 byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
11 IvParameterSpec ivspec = new IvParameterSpec(iv);
12 String key = "3FC4F0D2AB50057BCE0D90D9187A22B1";
13 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
14
15 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
16 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
17// return toHexString(Base64.getEncoder()
18// .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))).getBytes());
19 return toHexString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
20 } catch (Exception e) {
21 System.out.println("Error while encrypting: " + e.toString());
22 }
23 return null;
24 }
25
26 public static String decrypt(String strToDecrypt) {
27 try {
28 byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
29 IvParameterSpec ivspec = new IvParameterSpec(iv);
30 String key = "3FC4F0D2AB50057BCE0D90D9187A22B1";
31 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
32
33 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
34 cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
35 return new String(cipher.doFinal(fromHexString(strToDecrypt)), StandardCharsets.UTF_8);
36 } catch (Exception e) {
37 System.out.println("Error while decrypting: " + e.toString());
38 }
39 return null;
40 }
41
42 public static String toHexString(byte[] ba) {
43 StringBuilder str = new StringBuilder();
44 for (int i = 0; i < ba.length; i++) {
45 str.append(String.format("%02x", ba[i]));
46 }
47 return str.toString().toUpperCase();
48 }
49
50 public static byte[] fromHexString(String hex) {
51 StringBuilder str = new StringBuilder();
52 for (int i = 0; i < hex.length(); i += 2) {
53 str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
54 }
55 byte[] res = new byte[str.length()];
56 for (int i = 0; i < str.length(); i++) {
57 res[i] = (byte) str.charAt(i);
58 }
59 return res;
60 }
61}
62