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

前端 未结 4 1570
独厮守ぢ
独厮守ぢ 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 22:44

    Complete answer with use example, thanks to erickson.

    Put this into your "Utils" class.

    public static String getSha256Hash(String password) {
        try {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            }
            digest.reset();
            return bin2hex(digest.digest(password.getBytes()));
        } catch (Exception ignored) {
            return null;
        }
    }
    
    private 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();
    }
    

    Example of use:

    Toast.makeText(this, Utils.getSha256Hash("123456_MY_PASSWORD"), Toast.LENGTH_SHORT).show();
    

提交回复
热议问题