How can I calculate the SHA-256 hash of a string with a secret key in Android?
Asked Answered
I

3

6

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 ?

Instinct answered 21/8, 2012 at 8:13 Comment(7)
do you understand the purpose of an hashing algorithm?Pristine
@Pristine yes, I do. what is so strange to my question? This is what I must do. I saw that in other programming languages this is possible.Instinct
can you show me how a key is related to the hashing phase? I never read about this anywhere and i don't even get your point of if this is something that can be real.Pristine
Take a look here : hash.online-convert.com/sha256-generatorInstinct
which is something about cryptography and not steganography, it's also something much more similar to a protocol rather than an hashing algorithm or an hashing phase. you are talking about 2 different things. the hashing doesn't use a key, never, if you are talking about a particular protocol or solution you have to specify it.Pristine
So it's about hmac. If so @Chirag answer is correct.Buckthorn
An explanation of HMAC.Satisfied
T
22

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();  
}  
Tieback answered 21/8, 2012 at 8:23 Comment(4)
Which is the method toHexString()?Instinct
Let me know : How can I calculate the SHA-1 hash of a String with a Secret key in android ?Lullaby
how can i reverse from Hash string to original String ? Any idea thanksLiqueur
@ShanXeeshi You're out of luck there. A hash is a one-way digest; it cannot be "reversed" to get the original text. Sorry.Wawro
L
0

In kotlin, use below function.

import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

fun String.hmacSha256(key: String): String {
    val secretKey = SecretKeySpec(key.toByteArray(Charsets.UTF_8), "HmacSHA256")
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(secretKey)
    val hash = mac.doFinal(this.toByteArray(Charsets.UTF_8))
    return hash.joinToString("") { "%02x".format(it) }
}

Here,

val key = "secret key"
val message = "message to be encrypted"
val encryptedMessage = message.hmacSha256(key) // final result
Ledoux answered 23/2, 2023 at 6:39 Comment(0)
W
-1

Use the below code,

/**
 * Returns a hexadecimal encoded SHA-256 hash for the input String.
 * @param data
 * @return
 */
private static String getSHA256Hash(String data) {
    String result = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(data.getBytes("UTF-8"));
        return bytesToHex(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.
 * @param hash
 * @return
 */
private static String  bytesToHex(byte[] hash) {
    return DatatypeConverter.printHexBinary(hash);
}

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

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

Where answered 21/6, 2018 at 8:46 Comment(1)
there is no secret keyMod

© 2022 - 2024 — McMap. All rights reserved.