Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, UnsupportedEncodingException
{
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.reset();

    byte[] byteData = digest.digest(input.getBytes("UTF-8"));
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
}

for calculating the hash without the secret key. How can I calculate with a secret key? I searched but I didn't find any solution in Android. Any idea ?

like image 232
Gabrielle Avatar asked Aug 21 '12 08:08

Gabrielle


People also ask

Does SHA-256 have a key?

It's part of the SHA-2 family of hash functions and uses a 256-bit key to take a piece of data and convert it into a new, unrecognizable data string of a fixed length. This string of random characters and numbers, called a hash value, is also 256 bits in size.

Can we decrypt SHA-256 password?

SHA-256 encryption is a hash, which means that it is one-way and can not be decrypted.

How many SHA-256 hashes exist?

A bit has two possible values: 0 and 1. The possible number of unique hashes can be expressed as the number of possible values raised to the number of bits. For SHA-256 there are 2256 possible combinations.


1 Answers

Look at this example.

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

 try {
  Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
  Mac mac = Mac.getInstance(sk.getAlgorithm());
  mac.init(sk);
  final byte[] hmac = mac.doFinal(text.getBytes());
  return toHexString(hmac);
 } catch (NoSuchAlgorithmException e1) {
  // throw an exception or pick a different encryption method
  throw new SignatureException(
    "error building signature, no such algorithm in device "
      + HASH_ALGORITHM);
 } catch (InvalidKeyException e) {
  throw new SignatureException(
    "error building signature, invalid key " + HASH_ALGORITHM);
 }
}

Where HASH_ALGORITHM is defined as:

private static final String HASH_ALGORITHM = "HmacSHA256";

public static String toHexString(byte[] bytes) {  
    StringBuilder sb = new StringBuilder(bytes.length * 2);  

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

    return sb.toString();  
}  
like image 81
Chirag Avatar answered Sep 18 '22 23:09

Chirag