Java HMAC hmac(String hash, String data, String key)

Here you can find the source of hmac(String hash, String data, String key)

Description

hmac

License

Apache License

Declaration

public static String hmac(String hash, String data, String key) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

public class Main {

    public static String hmac(String hash, String data, String key) {
        byte[] byteHMAC = null;
        try {//  w w  w.j a  v a2  s  . c  o  m
            Mac mac = Mac.getInstance("Hmac" + hash);
            SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "Hmac" + hash);
            mac.init(spec);
            byteHMAC = mac.doFinal(data.getBytes("UTF-8"));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException ignore) {
            ignore.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (byteHMAC != null) {
            try {
                String hexMac = bytes2hex(byteHMAC);
                return hexMac;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }

    public static String bytes2hex(byte[] bts) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        int j = bts.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = bts[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }
}

Related

  1. hmac(byte key[], byte text[])
  2. hmac(String msg, String keyString)
  3. HMAC(String username, BigInteger nonce, String hashedPassword)
  4. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  5. hmac_sha(String crypto, byte[] keyBytes, byte[] text)