· 8 years ago · Nov 23, 2017, 12:42 AM
1package com.cwilldev.crypt;
2
3import java.security.NoSuchAlgorithmException;
4import javax.crypto.Cipher;
5import javax.crypto.NoSuchPaddingException;
6import javax.crypto.spec.IvParameterSpec;
7import javax.crypto.spec.SecretKeySpec;
8
9public class ApiCrypter {
10
11 private String iv = "myuniqueivparam";
12 private String secretkey = "mysecretkey";
13 private IvParameterSpec ivspec;
14 private SecretKeySpec keyspec;
15 private Cipher cipher;
16
17 public ApiCrypter()
18 {
19 ivspec = new IvParameterSpec(iv.getBytes());
20 keyspec = new SecretKeySpec(secretkey.getBytes(), "AES");
21
22 try {
23 cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
24 } catch (NoSuchAlgorithmException e) {
25 e.printStackTrace();
26 } catch (NoSuchPaddingException e) {
27 e.printStackTrace();
28 }
29 }
30
31 public byte[] encrypt(String text) throws Exception
32 {
33 if(text == null || text.length() == 0) {
34 throw new Exception("Empty string");
35 }
36 byte[] encrypted = null;
37 try {
38 cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
39 encrypted = cipher.doFinal(text.getBytes("UTF-8"));
40 }
41 catch (Exception e) {
42 throw new Exception("[encrypt] " + e.getMessage());
43 }
44 return encrypted;
45 }
46
47 public byte[] decrypt(String code) throws Exception
48 {
49 if(code == null || code.length() == 0) {
50 throw new Exception("Empty string");
51 }
52 byte[] decrypted = null;
53 try {
54 cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
55 decrypted = cipher.doFinal(hexToBytes(code));
56 }
57 catch (Exception e) {
58 throw new Exception("[decrypt] " + e.getMessage());
59 }
60 return decrypted;
61 }
62
63 public static String bytesToHex(byte[] data)
64 {
65 if (data==null) {
66 return null;
67 }
68 int len = data.length;
69 String str = "";
70 for (int i=0; i<len; i++) {
71 if ((data[i]&0xFF)<16) {
72 str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
73 }
74 else {
75 str = str + java.lang.Integer.toHexString(data[i]&0xFF);
76 }
77 }
78 return str;
79 }
80
81 public static byte[] hexToBytes(String str) {
82 if (str==null) {
83 return null;
84 }
85 else if (str.length() < 2) {
86 return null;
87 }
88 else {
89 int len = str.length() / 2;
90 byte[] buffer = new byte[len];
91 for (int i=0; i<len; i++) {
92 buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
93 }
94 return buffer;
95 }
96 }
97
98}