android - 如何在 Android 中使用 key 计算字符串的 SHA-256 哈希值?

标签 android hash sha256

我需要使用 key 计算字符串的 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();
}

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

最佳答案

看这个例子。

/**
 * 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);
 }
}

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

关于android - 如何在 Android 中使用 key 计算字符串的 SHA-256 哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12050700/

相关文章:

android - 同时在android上流式传输和录制视频

安卓 : show keyboard in edittext

java - AES 256 文本加密返回不同的值

endianness - 小字节序数据和sha 256

Java 整数/ double 到无符号字节

java - 错误:SSL peer shut down incorrectly

android - Twitter API postman : Code 32: Could not authenticate you

javascript - web3使用什么哈希加密算法? ethereumjs-util Sha3 返回不同的结果

c - 在这种情况下是否可以制作一个最小的完美哈希函数?

java - 适用于 Android 的 MD5 哈希