如何在 Android 中计算字符串的 SHA-256 哈希值? [英] How can I calculate the SHA-256 hash of a string in Android?

查看:36
本文介绍了如何在 Android 中计算字符串的 SHA-256 哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Android 中获取字符串的 SHA256.

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

这是我要匹配的 PHP 代码:

Here is the PHP code that I want to match:

echo bin2hex(mhash(MHASH_SHA256,"asdf"));
//outputs "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"

现在,在 Java 中,我正在尝试执行以下操作:

Now, in Java, I'm trying to do the following:

            String password="asdf"
            MessageDigest digest=null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
       digest.reset();
       try {
        Log.i("Eamorr",digest.digest(password.getBytes("UTF-8")).toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但这会打印出:a42yzk3axdv3k4yh98g8"

But this prints out: "a42yzk3axdv3k4yh98g8"

我在这里做错了什么?

感谢 erickson 的解决方案:

Solution thanks to erickson:

 Log.i("Eamorr",bin2hex(getHash("asdf")));

 public byte[] getHash(String password) {
       MessageDigest digest=null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
       digest.reset();
       return digest.digest(password.getBytes());
 }
static String bin2hex(byte[] data) {
    return String.format("%0" + (data.length*2) + "X", new BigInteger(1, data));
}

推荐答案

PHP 函数 bin2hex 的意思是它接受一串字节并将其编码为十六进制数.

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

在 Java 代码中,您试图获取一堆随机字节并使用平台的默认字符编码将它们解码为字符串.那是行不通的,即使行得通,也不会产生相同的结果.

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.

以下是 Java 的快速二进制到十六进制转换:

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.

这篇关于如何在 Android 中计算字符串的 SHA-256 哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆