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

前端 未结 4 1544
独厮守ぢ
独厮守ぢ 2020-12-12 22:05

I\'m trying to get the SHA256 of a string in Android.

Here is the PHP code that I want to match:

echo bin2hex(mhash(MHASH_SHA256,\"asdf\"));
//output         


        
4条回答
  •  -上瘾入骨i
    2020-12-12 22:21

    The PHP function bin2hex means that it takes a string of bytes and encodes it as a hexadecimal number.

    In the Java code, you are trying to take a bunch of random bytes and decode them as a string using your platform's default character encoding. That isn't going to work, and if it did, it wouldn't produce the same results.

    Here's a quick-and-dirty binary-to-hex conversion for Java:

    static String bin2hex(byte[] data) {
        StringBuilder hex = new StringBuilder(data.length * 2);
        for (byte b : data)
            hex.append(String.format("%02x", b & 0xFF));
        return hex.toString();
    }
    

    This is quick to write, not necessarily quick to execute. If you are doing a lot of these, you should rewrite the function with a faster implementation.

提交回复
热议问题