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

Gab*_*lle 5 hash android sha256

我需要用密钥计算字符串的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();
}
Run Code Online (Sandbox Code Playgroud)

用于计算没有密钥的散列.如何用密钥计算?我搜索但是我没有在Android中找到任何解决方案.任何的想法 ?

Chi*_*rag 17

看看这个例子.

/**
 * 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);
 }
}
Run Code Online (Sandbox Code Playgroud)

其中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();  
}  
Run Code Online (Sandbox Code Playgroud)

  • 如何从Hash字符串转换为原始字符串?不知道谢谢 (3认同)
  • @ShanXeeshi 你运气不好。哈希是一种单向摘要;无法“反转”得到原始文本。对不起。 (2认同)