Skip to content Skip to sidebar Skip to footer

How Can I Calculate The Sha-256 Hash Of A String With A Secret Key In Android?

I need to calculate a SHA-256 hash of a string with a secret key. I found this code : public String computeHash(String input) throws NoSuchAlgorithmException, UnsupportedEncodi

Solution 1:

Look at this example.

/**
 * Encryption of a given text using the provided secretKey
 * 
 * @param text
 * @param secretKey
 * @return the encoded string
 * @throws SignatureException
 */publicstatic String hashMac(String text, String secretKey)throws SignatureException {

 try {
  Keysk=newSecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
  Macmac= Mac.getInstance(sk.getAlgorithm());
  mac.init(sk);
  finalbyte[] hmac = mac.doFinal(text.getBytes());
  return toHexString(hmac);
 } catch (NoSuchAlgorithmException e1) {
  // throw an exception or pick a different encryption methodthrownewSignatureException(
    "error building signature, no such algorithm in device "
      + HASH_ALGORITHM);
 } catch (InvalidKeyException e) {
  thrownewSignatureException(
    "error building signature, invalid key " + HASH_ALGORITHM);
 }
}

Where HASH_ALGORITHM is defined as:

privatestaticfinalStringHASH_ALGORITHM="HmacSHA256";

publicstatic String toHexString(byte[] bytes) {  
    StringBuildersb=newStringBuilder(bytes.length * 2);  

    Formatterformatter=newFormatter(sb);  
    for (byte b : bytes) {  
        formatter.format("%02x", b);  
    }  

    return sb.toString();  
}  

Solution 2:

Use the below code,

/**
 * Returns a hexadecimal encoded SHA-256 hash for the input String.
 * @paramdata
 * @return
 */privatestaticStringgetSHA256Hash(String data) {
    String result = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(data.getBytes("UTF-8"));
        returnbytesToHex(hash); // make it printable
    }catch(Exception ex) {
        ex.printStackTrace();
    }
    return result;
}

/**
 * Use javax.xml.bind.DatatypeConverter class in JDK
 * to convert byte array to a hexadecimal string. Note that this generates hexadecimal in upper case.
 * @paramhash
 * @return
 */privatestaticStringbytesToHex(byte[] hash) {
    returnDatatypeConverter.printHexBinary(hash);
}

To use DatatypeConverter, download the jar file from the below link.

http://www.java2s.com/Code/Jar/j/Downloadjavaxxmlbindjar.htm

Post a Comment for "How Can I Calculate The Sha-256 Hash Of A String With A Secret Key In Android?"