· 6 years ago · Mar 08, 2019, 08:40 PM
1public String computeHash(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException{
2 MessageDigest digest = MessageDigest.getInstance("SHA-256");
3 digest.reset();
4
5 byte[] byteData = digest.digest(input.getBytes("UTF-8"));
6 StringBuffer sb = new StringBuffer();
7
8 for (int i = 0; i < byteData.length; i++){
9 sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
10 }
11 return sb.toString();
12 }
13
14/**
15 * Encryption of a given text using the provided secretKey
16 *
17 * @param text
18 * @param secretKey
19 * @return the encoded string
20 * @throws SignatureException
21 */
22public static String hashMac(String text, String secretKey)
23 throws SignatureException {
24
25 try {
26 Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
27 Mac mac = Mac.getInstance(sk.getAlgorithm());
28 mac.init(sk);
29 final byte[] hmac = mac.doFinal(text.getBytes());
30 return toHexString(hmac);
31 } catch (NoSuchAlgorithmException e1) {
32 // throw an exception or pick a different encryption method
33 throw new SignatureException(
34 "error building signature, no such algorithm in device "
35 + HASH_ALGORITHM);
36 } catch (InvalidKeyException e) {
37 throw new SignatureException(
38 "error building signature, invalid key " + HASH_ALGORITHM);
39 }
40}
41
42where HASH_ALGORITHM is defined as
43
44private static final String HASH_ALGORITHM = "HmacSHA256";
45
46public static String toHexString(byte[] bytes) {
47 StringBuilder sb = new StringBuilder(bytes.length * 2);
48
49 Formatter formatter = new Formatter(sb);
50 for (byte b : bytes) {
51 formatter.format("%02x", b);
52 }
53
54 return sb.toString();
55}