【问题标题】:SHA-256 hashing yields the wrong result in AndroidSHA-256 哈希在 Android 中产生错误的结果
【发布时间】:2012-11-19 02:56:15
【问题描述】:

我正在尝试使用1111 加密12345 作为盐使用SHA-256 编码,我得到的答案是:010def5ed854d162aa19309479f3ca44dc7563232ff072d1c87bd85943d0e930this site返回的值不同。

这里是sn-p的代码:

public String getHashValue(String entity, String salt){
    byte[] hashValue = null;
    try {
        MessageDigest digest =  MessageDigest.getInstance("SHA-256");
        digest.update(entity.getBytes("UTF-8"));
        digest.update(salt.getBytes("UTF-8"));
        hashValue = digest.digest();
    } catch (NoSuchAlgorithmException e) {
        Log.i(TAG, "Exception "+e.getMessage());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return BasicUtil.byteArrayToHexString(hashValue);
}

我已经用 SO 的样本验证了我的打印方法,结果很好。谁能告诉我这里出了什么问题?

澄清一下 - 当我在 iOS 代码中加密相同的值和盐时,返回的值与转换站点给出的值相同。

【问题讨论】:

  • 我从您链接的页面获得010def5ed854d162aa19309479f3ca44dc7563232ff072d1c87bd85943d0e930。你到底输入了什么?
  • 我得到b0c3d371142251569cb39f81280baeb73d5ed6f0b177386f8436d166d4a3cd6e 怎么会?!

标签: android hash salt sha256


【解决方案1】:

如果您在该站点中填写 hmac secret 的可选部分,将使用 HmacSHA256 算法。 使用此函数可以产生相同的结果:

public static String getHmac(String entity, String salt) throws Exception{
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(salt.getBytes(), "HmacSHA1"));
    byte[] bs = mac.doFinal(entity.getBytes());
    return new HexDumpEncoder().encode(bs); // use your favorite hex converter
}

如果您想从该站点获得相同的输出,请尝试在没有 hmac 密码的情况下散列此值“123451111”。

显然,两次调用 MessageDigest.update 等同于使用连接值调用一次。

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2020-06-29
    • 2013-01-09
    • 2011-04-18
    相关资源
    最近更新 更多