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

前端 未结 4 1567
独厮守ぢ
独厮守ぢ 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:41

    You are along the right lines, but converting the bytes is a little more complicated. This works on my device:

    // utility function
        private static String bytesToHexString(byte[] bytes) {
            // http://stackoverflow.com/questions/332079
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(0xFF & bytes[i]);
                if (hex.length() == 1) {
                    sb.append('0');
                }
                sb.append(hex);
            }
            return sb.toString();
        }
    
    // generate a hash
    
        String password="asdf";
        MessageDigest digest=null;
        String hash;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            digest.update(password.getBytes());
    
            hash = bytesToHexString(digest.digest());
    
            Log.i("Eamorr", "result is " + hash);
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    

    Source: bytesToHexString function is from the IOSched project.

提交回复
热议问题