Android SHA256 Hash Create getHmacSHA256(String key, String input)

Here you can find the source of getHmacSHA256(String key, String input)

Description

Generated a hmac sha256 for a string

Parameter

Parameter Description
key Key used for hash generation
input String to be hashed

Exception

Parameter Description
Exception an exception

Return

Hashed string

Declaration

public static String getHmacSHA256(String key, String input)
        throws Exception 

Method Source Code

//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();
    }
}

Related

  1. sha256Byte(byte[] in)
  2. doubleSha256(byte[] data)
  3. doubleSha256(byte[] data, int offset, int length)
  4. doubleSha256TwoBuffers(byte[] data1, byte[] data2)
  5. SHA256(String text)
  6. sha256(byte[] data)
  7. cipher(int mode, byte[] data, byte[] secret)