简体   繁体   English

如何在Java中使用哈希sha256生成哈希代码?

[英]How do I generate a hash code with hash sha256 in java?

I would like to know the code to do this in java please? 我想知道在Java中执行此操作的代码吗?

This is what i have so far but it does not work? 这是我到目前为止所拥有的,但是它不起作用?

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static jdk.nashorn.tools.ShellFunctions.input;

public class Sha256hash 
{

    public static String main(String[] args) throws NoSuchAlgorithmException 
    {
        MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
    }

}

I'm still unclear whether you want SHA-1 or SHA-256, so let's abstract the problem; 我仍然不清楚您要使用SHA-1 还是 SHA-256,因此让我们抽象一下问题; firstly, an encode method to take a byte[] and return the hex (don't worry, you already wrote it; but I would prefer a StringBuilder over String concatenation. Java String is immutable , so you're creating garbage for later garbage collection with + ) - 首先,一个编码方法采用一个byte[]并返回十六进制(不用担心,您已经编写了它;但是我更喜欢StringBuilder不是String连接String不可变的 ,因此您要为以后的垃圾创建垃圾加上+ )-

private static String encodeHex(byte[] digest) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < digest.length; i++) {
        sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
}

Next, we can create a method that takes the algorithm name and the String to digest and returns that digest. 接下来,我们可以创建一个使用算法名称和String进行摘要并返回该摘要的方法。 Like 喜欢

public static String digest(String alg, String input) {
    try {
        MessageDigest md = MessageDigest.getInstance(alg);
        byte[] buffer = input.getBytes("UTF-8");
        md.update(buffer);
        byte[] digest = md.digest();
        return encodeHex(digest);
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

Then we can get a SHA-1 or a SHA-256 hash like 然后我们可以得到SHA-1 SHA-256哈希

public static void main(String[] args) {
    System.out.println(digest("SHA1", ""));
    System.out.println(digest("SHA-256", ""));
}

Which outputs (as expected) 哪些输出(预期)

da39a3ee5e6b4b0d3255bfef95601890afd80709
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

The main entry point can not return String. 主入口点不能返回String。 Furthermore, input is not declared. 此外,未声明input You maybe want to change the name of your function to generate with input as a parameter. 您可能想要更改要使用input作为参数generate的函数的名称。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static jdk.nashorn.tools.ShellFunctions.input;

public class Sha256hash 
{

    public static String generate(String input) throws NoSuchAlgorithmException 
    {
        MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
    }

}

This example works for me returning c3499c2729730a7f807efb8676a92dcb6f8a3f8f as result of processing the string example : 此示例对我c3499c2729730a7f807efb8676a92dcb6f8a3f8f ,因为处理字符串example后返回了c3499c2729730a7f807efb8676a92dcb6f8a3f8f

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256hash 
{

    public static String generate(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException 
    {
        MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
    }

}

Main: 主要:

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public class Tester {
    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String someText = "example";
        System.out.println(Sha256hash.generate(someText));
    }
}

Finally, as Elliott has pointed out If you want to use SHA-256 you should change MessageDigest.getInstance("SHA1"); 最后,正如Elliott所指出的,如果要使用SHA-256,则应更改MessageDigest.getInstance("SHA1"); to MessageDigest.getInstance("SHA256") ; MessageDigest.getInstance("SHA256") ; Right now you are using SHA-1. 现在,您正在使用SHA-1。 Also pointed by Elliot you should use StringBuilder in the loop for improved efficiency. Elliot还指出,您应该在循环中使用StringBuilder以提高效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM