如何在 Android 中计算字符串的 SHA-256 哈希值?

发布于 2024-12-01 10:24:15 字数 1377 浏览 0 评论 0原文

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

这是我想要匹配的 PHP 代码:

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

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

            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”

我在这里做错了什么?


感谢埃里克森的解决方案:

 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));
}

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"));
//outputs "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"

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();
    }

But this prints out: "a42yzk3axdv3k4yh98g8"

What did I do wrong here?


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));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

后eg是否自 2024-12-08 10:24:16

我知道这个问题已经得到解答,但我在 android arsenal 找到了一个哈希库,它非常简单,简单,只有一个行代码。可以散列 MD5、SHA-1、SHA-256、SHA-384 或 SHA-512。

  1. 首先将其添加到您的 gradle 并同步

    实现 'com.github.1AboveAll:Hasher:1.2'

  2. 开始拥有

    Hasher.Companion.hash("Hello",HashType.SHA_1);

i know this has been answered but i found a Hashing Library at android arsenal and its very easy,simple and just one line of code. can hash MD5, SHA-1, SHA-256, SHA-384, or SHA-512.

  1. first add this to your gradle and sync

    implementation 'com.github.1AboveAll:Hasher:1.2'

  2. start hasing

    Hasher.Companion.hash("Hello",HashType.SHA_1);

笑咖 2024-12-08 10:24:16
private fun stringToSha256(input: String): String {
    val bytes = input.toByteArray()
    val md = MessageDigest.getInstance("SHA-256")
    val digest = md.digest(bytes)

    // Convert the byte array to a hexadecimal string
    val result = StringBuilder()
    for (byte in digest) {
        result.append(String.format("%02x", byte))
    }

    return result.toString()
}
private fun stringToSha256(input: String): String {
    val bytes = input.toByteArray()
    val md = MessageDigest.getInstance("SHA-256")
    val digest = md.digest(bytes)

    // Convert the byte array to a hexadecimal string
    val result = StringBuilder()
    for (byte in digest) {
        result.append(String.format("%02x", byte))
    }

    return result.toString()
}
鼻尖触碰 2024-12-08 10:24:15

PHP 函数 bin2hex 意味着它接受一个字节字符串并将其编码为十六进制数。

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

这是 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();
}

编写很快,但执行起来不一定很快。如果你做了很多这样的事情,你应该用更快的实现来重写函数。

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.

一桥轻雨一伞开 2024-12-08 10:24:15

您的思路是正确的,但转换字节有点复杂。这适用于我的设备:

// 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();
    }

来源:bytesToHexString 函数来自 IOSched 项目。

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.

晚雾 2024-12-08 10:24:15

通过使用示例完成答案,感谢埃里克森。

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();
}

使用示例:

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

Complete answer with use example, thanks to erickson.

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文