· 9 years ago · Dec 17, 2016, 02:32 AM
1import java.io.UnsupportedEncodingException;
2import java.security.InvalidKeyException;
3import java.security.NoSuchAlgorithmException;
4import java.security.SecureRandom;
5import java.util.Base64;
6
7import javax.crypto.Mac;
8import javax.crypto.spec.SecretKeySpec;
9
10public class EncryptionUtility {
11
12 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
13
14 public static String calculateHash(String secret, String url, String encryption) {
15
16 Mac shaHmac = null;
17
18 try {
19
20 shaHmac = Mac.getInstance(encryption);
21
22 } catch (NoSuchAlgorithmException e) {
23
24 e.printStackTrace();
25 }
26
27 SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), encryption);
28
29 try {
30
31 shaHmac.init(secretKey);
32
33 } catch (InvalidKeyException e) {
34
35 e.printStackTrace();
36 }
37
38 byte[] hash = shaHmac.doFinal(url.getBytes());
39 String check = bytesToHex(hash);
40
41 return check;
42 }
43
44 public static String generateNonce() {
45
46 SecureRandom random = null;
47
48 try {
49
50 random = SecureRandom.getInstance("SHA1PRNG");
51
52 } catch (NoSuchAlgorithmException e) {
53
54 e.printStackTrace();
55 }
56
57 random.setSeed(System.currentTimeMillis());
58
59 byte[] nonceBytes = new byte[16];
60 random.nextBytes(nonceBytes);
61
62 String nonce = null;
63
64 try {
65
66 nonce = new String(Base64.getEncoder().encode(nonceBytes), "UTF-8");
67
68 } catch (UnsupportedEncodingException e) {
69
70 e.printStackTrace();
71 }
72
73 return nonce;
74 }
75
76 private static String bytesToHex(byte[] bytes) {
77
78 char[] hexChars = new char[bytes.length * 2];
79
80 for(int j = 0; j < bytes.length; j++) {
81
82 int v = bytes[j] & 0xFF;
83
84 hexChars[j * 2] = hexArray[v >>> 4];
85 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
86 }
87
88 return new String(hexChars);
89 }
90
91
92 public static String getHmacDigest(Mac mac, String postData)throws Exception {
93 byte[] bytes = mac.doFinal(postData.getBytes("ASCII"));
94 StringBuilder hash = new StringBuilder();
95 for (int i = 0; i < bytes.length; i++) {
96 String hex = Integer.toHexString(0xFF & bytes[i]);
97 if (hex.length() == 1) {
98 hash.append('0');
99 }
100 hash.append(hex);
101 }
102 return hash.toString();
103 }
104
105}