簡體   English   中英

SHA256Digest 返回一個奇怪的 hash

[英]SHA256Digest is returning a weird hash

BlackBerry應用程序中,我使用此代碼從密碼中獲取 hash:

        SHA256Digest sha256d = new SHA256Digest();
        byte[] passwordData = null;

        try {
            passwordData = password.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        DigestOutputStream outputStream = new DigestOutputStream(sha256d, null);
        try {
            outputStream.write(passwordData);
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] hashedValue = sha256d.getDigest();
        tempSHA256Password = new String(hashedValue);
        System.out.println(tempSHA256Password);

在此代碼塊的末尾, tempSHA256Password將是這樣的: ëÇ#ÎiGê8óq =ßÝ÷<rê¨_FR»ã ... 所以絕不是我所期望的。 我期待一個看起來像這樣的字符串: ebc723ce6947ea38f371a03d0cdfddf73c840f7215eaa85f031446529bbb16e3

我究竟做錯了什么?

Insted of tempSHA256Password = new String(hashedValue); 試試這個代碼:

StringBuffer buffer = new StringBuffer();
for(byte b : hashedValue)
{
    buffer.append(String.format("%02x",b<0 ? b+256 : b));
}
tempSHA256Password = buffer.toString();

這就是問題:

tempSHA256Password = new String(hashedValue);

它試圖從任意二進制數據創建一個字符串,就好像它是使用平台默認編碼的文本編碼一樣。 聽起來您正在尋找十六進制。 Java 中有許多不同的十六進制編碼實用程序庫 - 例如,您可能想查看Apache Commons Codec

您不能直接打印二進制值:

tempSHA256Password = new String(hashedValue);
System.out.println(tempSHA256Password);

所以如果你想把它轉換成十六進制你可以使用這個方法:

static final String HEXES = "0123456789ABCDEF";
public static String getHex( byte [] raw ) {
  if ( raw == null ) {
    return null;
  }
  final StringBuffer hex = new StringBuffer( 2 * raw.length );
  for ( final byte b : raw ) {
    hex.append(HEXES.charAt((b & 0xF0) >> 4))
     .append(HEXES.charAt((b & 0x0F)));
  }
  return hex.toString();
}

此方法來自此處,如果有興趣,您還有其他示例。

您看到的是 hash 的二進制形式。您必須將其轉換為十六進制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM