Here you can find the source of getHmacSHA256(String key, String input)
Parameter | Description |
---|---|
key | Key used for hash generation |
input | String to be hashed |
Parameter | Description |
---|---|
Exception | an exception |
public static String getHmacSHA256(String key, String input) throws Exception
//package com.java2s; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Main { public static final String HMAC_SHA_2561 = "HmacSHA256"; /**//from www.ja v a 2s .c o m * Generated a hmac sha256 for a string * * @param key Key used for hash generation * @param input String to be hashed * @return Hashed string * @throws Exception */ public static String getHmacSHA256(String key, String input) throws Exception { Mac mac = Mac.getInstance(HMAC_SHA_2561); mac.init(new SecretKeySpec(key.getBytes(), HMAC_SHA_2561)); byte[] bs = mac.doFinal(input.getBytes()); return byteArrayToHexString(bs); } /** * Converts a byte[] to a hex string * * @param byteArray Array to be converted * @return Array as a hex string */ public static String byteArrayToHexString(byte[] byteArray) { final StringBuilder builder = new StringBuilder(); for (byte b : byteArray) { builder.append(String.format("%02x", b)); } return builder.toString(); } }