如何在 Android 中使用密钥计算字符串的 SHA-256 哈希?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12050700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:35:49  来源:igfitidea点击:

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

androidhashsha256

提问by Gabrielle

I need to calculate a SHA-256 hash of a string with a secret key. I found this code :

我需要使用密钥计算字符串的 SHA-256 哈希值。我找到了这个代码:

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 ?

用于在没有密钥的情况下计算散列。如何使用密钥进行计算?我搜索但我没有在Android中找到任何解决方案。任何的想法 ?

回答by Chirag

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:

其中 HASH_ALGORITHM 定义为:

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

回答by Jacob Abraham

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.

要使用 DatatypeConverter,请从以下链接下载 jar 文件。

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

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