· 7 years ago · Nov 03, 2018, 05:04 PM
1import java.io.ByteArrayOutputStream;
2import java.io.UnsupportedEncodingException;
3import java.security.NoSuchAlgorithmException;
4import java.security.SecureRandom;
5import java.util.Base64;
6import javax.crypto.Cipher;
7import javax.crypto.NoSuchPaddingException;
8import javax.crypto.spec.IvParameterSpec;
9import javax.crypto.spec.SecretKeySpec;
10
11public class MCrypt {
12 private Cipher cipher;
13 private byte[] iv = new byte[16];
14 private IvParameterSpec ivspec;
15 private SecretKeySpec keyspec;
16
17 public MCrypt(String secretKey) {
18 SecureRandom random = new SecureRandom();
19 random.nextBytes(this.iv);
20 this.ivspec = new IvParameterSpec(this.iv);
21 try {
22 this.keyspec = buildKey(secretKey);
23 } catch (NoSuchAlgorithmException e) {
24 e.printStackTrace();
25 } catch (UnsupportedEncodingException e2) {
26 e2.printStackTrace();
27 }
28 try {
29 this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
30 } catch (NoSuchAlgorithmException e3) {
31 e3.printStackTrace();
32 } catch (NoSuchPaddingException e4) {
33 e4.printStackTrace();
34 }
35 }
36
37 private SecretKeySpec buildKey(String secretKey) throws NoSuchAlgorithmException, UnsupportedEncodingException {
38 return new SecretKeySpec(hexStringToByteArray(secretKey), "AES");
39 }
40
41 public byte[] hexStringToByteArray(String s) {
42 int len = s.length();
43 byte[] data = new byte[(len / 2)];
44 for (int i = 0; i < len; i += 2) {
45 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
46 }
47 return data;
48 }
49
50 public String encrypt(String text) throws Exception {
51 if (text == null || text.length() == 0) {
52 throw new Exception("Empty string");
53 }
54 try {
55 this.cipher.init(1, this.keyspec, this.ivspec);
56 byte[] e = this.cipher.doFinal(padString(text).getBytes());
57 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
58 outputStream.write(this.iv);
59 outputStream.write(e);
60 return new String(Base64.getEncoder().encode(outputStream.toByteArray()));
61 } catch (Exception e2) {
62 throw new Exception("[encrypt] " + e2.getMessage());
63 }
64 }
65
66 private static String padString(String source) {
67 int padLength = 16 - (source.length() % 16);
68 for (int i = 0; i < padLength; i++) {
69 source = source + '\u0000';
70 }
71 return source;
72 }
73}