Java SHA256 sha256(String string, String secret)

Here you can find the source of sha256(String string, String secret)

Description

sha

License

Open Source License

Declaration

public static String sha256(String string, String secret) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

public class Main {
    public static String sha256(String string, String secret) {
        try {/*w  ww. ja  va 2  s  .  c o  m*/
            SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");

            final Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);

            byte[] digest = mac.doFinal(string.getBytes("UTF-8"));
            digest = mac.doFinal(string.getBytes());

            BigInteger bigInteger = new BigInteger(1, digest);
            return String.format("%0" + (digest.length << 1) + "x", bigInteger);

        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException("No HMac SHA256 algorithm");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("No UTF-8");
        } catch (InvalidKeyException e) {
            throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
        }
    }
}

Related

  1. sha256(String src)
  2. sha256(String srcStr)
  3. sha256(String str)
  4. sha256(String str)
  5. sha256(String string)
  6. sha256(String strSrc)
  7. SHA256(String text)
  8. SHA256(String text)
  9. sha256(String text)