Java HMAC hmacSha256(String keyHex, String stringData)

Here you can find the source of hmacSha256(String keyHex, String stringData)

Description

hmac Sha

License

Apache License

Declaration

private static byte[] hmacSha256(String keyHex, String stringData)
            throws NoSuchAlgorithmException, InvalidKeyException 

Method Source Code


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

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

public class Main {
    private static byte[] hmacSha256(String keyHex, String stringData)
            throws NoSuchAlgorithmException, InvalidKeyException {
        byte[] keyBytes = hex_to_bytes(keyHex);
        byte[] data = string_to_bytes(stringData);

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(keyBytes, "HmacSHA256");
        sha256_HMAC.init(secret_key);/*w w  w  . j  av a 2  s . com*/

        return sha256_HMAC.doFinal(data);
    }

    private static byte[] hex_to_bytes(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    static byte[] string_to_bytes(String str) {
        return str.getBytes();
    }
}

Related

  1. hmacSha1(SecretKeySpec signingKey, byte[]... data)
  2. hmacSha1(String data, String key)
  3. hmacSha1(String input, byte[] keyBytes)
  4. hmacSha1(String input, byte[] keyBytes)
  5. hmacSHA256(byte[] secret, byte[] data)
  6. hmacsha256Representation(String data, String pusherApplicationSecret)
  7. hmacSha512(byte[] key, byte[] message)
  8. hmacSign(String aValue, String aKey)
  9. hmacSign(String skey, String data)