· 7 years ago · Feb 28, 2018, 09:20 AM
1public class EncryptionUtility {
2
3 private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
4 private static final String algorithm = "HmacSHA512";
5
6 public static String bytesToHex(byte[] bytes) {
7 char[] hexChars = new char[bytes.length * 2];
8 for (int j = 0; j < bytes.length; j++) {
9 int v = bytes[j] & 0xFF;
10 hexChars[j * 2] = hexArray[v >>> 4];
11 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
12 }
13 return new String(hexChars);
14 }
15
16 public static String calculateHash(String secret, String url) {
17 try {
18 SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), algorithm);
19 Mac shaHmac = Mac.getInstance(algorithm);
20 shaHmac.init(secretKey);
21 byte[] hash = shaHmac.doFinal(url.getBytes());
22 return bytesToHex(hash);
23 } catch (NoSuchAlgorithmException | InvalidKeyException e) {
24 e.printStackTrace();
25 }
26 return null;
27 }
28
29 @SuppressLint("SecureRandom")
30 public static String generateNonce() {
31
32 String nonce = null;
33 try {
34 SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
35 if (random != null) {
36 random.setSeed(System.currentTimeMillis());
37 }
38
39 byte[] nonceBytes = new byte[16];
40 if (random != null) {
41 random.nextBytes(nonceBytes);
42 }
43
44 nonce = new String(Base64.encode(nonceBytes, Base64.DEFAULT), "UTF-8");
45
46
47 } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
48
49 e.printStackTrace();
50 }
51
52 return nonce;
53 }
54}