· 7 years ago · Apr 12, 2018, 03:46 AM
1import javax.crypto.Cipher;
2import javax.crypto.Mac;
3import javax.crypto.spec.IvParameterSpec;
4import javax.crypto.spec.SecretKeySpec;
5import java.security.AlgorithmParameters;
6import java.security.spec.KeySpec;
7import javax.crypto.Cipher;
8import javax.crypto.SecretKey;
9import javax.crypto.SecretKeyFactory;
10import javax.crypto.spec.IvParameterSpec;
11import javax.crypto.spec.PBEKeySpec;
12import javax.crypto.spec.SecretKeySpec;
13import java.security.MessageDigest;
14import java.security.NoSuchAlgorithmException;
15
16public class EncryptorDecryptor {
17 public static void main(String[] args) {
18
19 String key = "11111111111111111111111111111111";
20 String iv = "0000000000000000";
21 String payload = "B2AD9F69870A383FE19CAA8182723860";
22
23 String plaintext = null;
24 try {
25 plaintext = myDecrypt(payload, iv, key);
26 } catch (Exception e) {
27 e.printStackTrace();
28 }
29
30 System.out.println("plain: " + plaintext);
31 }
32 public static String bin2hex(byte[] data) {
33 if (data == null) {
34 return null;
35 }
36 int len = data.length;
37 String str = "";
38 for (int i = 0; i < len; i++) {
39 if ((data[i] & 0xFF) < 16)
40 str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
41 else
42 str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
43 }
44 return str;
45 }
46 public static byte[] hex2bin(String str) {
47 if (str == null) {
48 return null;
49 } else if (str.length() < 2) {
50 return null;
51 } else {
52 int len = str.length() / 2;
53 byte[] buffer = new byte[len];
54 for (int i = 0; i < len; i++) {
55 buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
56 }
57 return buffer;
58 }
59 }
60
61 public static String myDecrypt(String payload, String iv, String key) throws Exception {
62 byte[] decodedKey = key.getBytes();
63 SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
64
65 IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
66
67 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
68 cipher.init(Cipher.DECRYPT_MODE, originalKey, ivspec);
69
70 byte[] payload_bytes = hex2bin(payload);
71 byte[] decrypted = cipher.doFinal(payload_bytes);
72 return new String(decrypted);
73 }
74}