如何在 Java 中使用 SHA-256 对某个字符串进行哈希处理?

发布于 2024-10-29 13:06:06 字数 72 浏览 6 评论 0原文

如何在 Java 中使用 SHA-256 对某些 String 进行哈希处理?

How can I hash some String with SHA-256 in Java?

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

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

发布评论

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

评论(17

¢蛋碎的人ぎ生 2024-11-05 13:06:06

SHA-256 不是一种“编码”——它是一种单向哈希。

您基本上将字符串转换为字节(例如使用text.getBytes(StandardCharsets.UTF_8)),然后对字节进行哈希处理。请注意,哈希的结果是任意二进制数据,如果您想在字符串中表示它,您应该使用 base64 或十六进制...不要尝试使用 < code>String(byte[], String) 构造函数。

例如

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));

SHA-256 isn't an "encoding" - it's a one-way hash.

You'd basically convert the string into bytes (e.g. using text.getBytes(StandardCharsets.UTF_8)) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex... don't try to use the String(byte[], String) constructor.

e.g.

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
不必你懂 2024-11-05 13:06:06

我认为最简单的解决方案是使用 Apache Common Codec

String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);   

I think that the easiest solution is to use Apache Common Codec:

String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);   
再可℃爱ぅ一点好了 2024-11-05 13:06:06

完整示例哈希到字符串作为另一个字符串。

public static String sha256(final String base) {
    try{
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        final byte[] hash = digest.digest(base.getBytes("UTF-8"));
        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            final String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) 
              hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Full example hash to string as another string.

public static String sha256(final String base) {
    try{
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        final byte[] hash = digest.digest(base.getBytes("UTF-8"));
        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            final String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) 
              hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}
银河中√捞星星 2024-11-05 13:06:06

另一种选择是 Guava,它具有易于使用的哈希实用程序。例如,要使用 SHA256 作为十六进制字符串对字符串进行哈希处理,您只需执行以下操作:

final String hashed = Hashing.sha256()
        .hashString("your input", StandardCharsets.UTF_8)
        .toString();

Another alternative is Guava which has an easy-to-use suite of Hashing utilities. For example, to hash a string using SHA256 as a hex-string you would simply do:

final String hashed = Hashing.sha256()
        .hashString("your input", StandardCharsets.UTF_8)
        .toString();
谢绝鈎搭 2024-11-05 13:06:06

如果您使用的是 Java 8,您可以通过以下方式对 byte[] 进行编码

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);

If you are using Java 8 you can encode the byte[] by doing

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);
梦里兽 2024-11-05 13:06:06
import java.security.MessageDigest;

public class CodeSnippets {

 public static String getSha256(String value) {
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(value.getBytes());
        return bytesToHex(md.digest());
    } catch(Exception ex){
        throw new RuntimeException(ex);
    }
 }
 private static String bytesToHex(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    return result.toString();
 }
}
import java.security.MessageDigest;

public class CodeSnippets {

 public static String getSha256(String value) {
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(value.getBytes());
        return bytesToHex(md.digest());
    } catch(Exception ex){
        throw new RuntimeException(ex);
    }
 }
 private static String bytesToHex(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    return result.toString();
 }
}
雨轻弹 2024-11-05 13:06:06
String hashWith256(String textToHash) {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
    byte[] hashedByetArray = digest.digest(byteOfTextToHash);
    String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
    return encoded;
}
String hashWith256(String textToHash) {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
    byte[] hashedByetArray = digest.digest(byteOfTextToHash);
    String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
    return encoded;
}
瞳孔里扚悲伤 2024-11-05 13:06:06

我通过 DigestUtils 跟踪 Apache 代码,sha256 似乎默认返回到 java.security.MessageDigest 进行计算。 Apache 没有实现独立的 sha256 解决方案。我一直在寻找一个独立的实现来与 java.security 库进行比较。仅供参考。

I traced the Apache code through DigestUtils and sha256 seems to default back to java.security.MessageDigest for calculation. Apache does not implement an independent sha256 solution. I was looking for an independent implementation to compare against the java.security library. FYI only.

盗心人 2024-11-05 13:06:06

此方法返回左填充的 String,其中包含零:

Java 10 及其后:

public static String sha256(String text) {
    try {
        var messageDigest = MessageDigest.getInstance("SHA-256");
        var hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

Java 8

public static String sha256(String text) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

顺便说一句,您可以使用 "%064X " 表示大写结果。

例子:

System.out.println(sha256("hello world 1"));

063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4

与 Linux cmd 的比较:

$ echo -n '你好世界 1' | sha256sum
063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4-

This method return a left padded String with zero:

Java 10 and after:

public static String sha256(String text) {
    try {
        var messageDigest = MessageDigest.getInstance("SHA-256");
        var hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

Java 8:

public static String sha256(String text) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

BTW, you can use "%064X" for an uppercase result.

Example:

System.out.println(sha256("hello world 1"));

063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4

Comparison to Linux cmd:

$ echo -n 'hello world 1' | sha256sum
063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4 -

紫南 2024-11-05 13:06:06

这是将摘要转换为十六进制字符串的稍微更高效的方法:

private static final char[] hexArray = "0123456789abcdef".toCharArray();

public static String getSHA256(String data) {
    StringBuilder sb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte[] byteData = md.digest();
        sb.append(bytesToHex(byteData);
    } catch(Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return String.valueOf(hexChars);
}

有谁知道 Java 中更快的方法吗?

Here is a slightly more performant way to turn the digest into a hex string:

private static final char[] hexArray = "0123456789abcdef".toCharArray();

public static String getSHA256(String data) {
    StringBuilder sb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte[] byteData = md.digest();
        sb.append(bytesToHex(byteData);
    } catch(Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return String.valueOf(hexChars);
}

Does anyone know of a faster way in Java?

少女七分熟 2024-11-05 13:06:06

在Java 8中

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;


Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
scanner.close();

MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        
System.out.println(encoded.toLowerCase());

In Java 8

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;


Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
scanner.close();

MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        
System.out.println(encoded.toLowerCase());
夏末染殇 2024-11-05 13:06:06

这是我使用 Kotlin 的方法:

private fun getHashFromEmailString(email : String) : String{
    val charset = Charsets.UTF_8
    val byteArray = email.toByteArray(charset)
    val digest = MessageDigest.getInstance("SHA-256")
    val hash = digest.digest(byteArray)

    return hash.fold("", { str, it -> str + "%02x".format(it)})
}

This was my approach using Kotlin:

private fun getHashFromEmailString(email : String) : String{
    val charset = Charsets.UTF_8
    val byteArray = email.toByteArray(charset)
    val digest = MessageDigest.getInstance("SHA-256")
    val hash = digest.digest(byteArray)

    return hash.fold("", { str, it -> str + "%02x".format(it)})
}
给妤﹃绝世温柔 2024-11-05 13:06:06

这就是我用于散列的内容:

String pass = "password";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);

输出:5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

This is what i have been used for hashing:

String pass = "password";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);

Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

少年亿悲伤 2024-11-05 13:06:06

您可以通过以下方式使用 MessageDigest:

public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}

You can use MessageDigest in the following way:

public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}
森林很绿却致人迷途 2024-11-05 13:06:06
public static String sha256(String s) {
    try {
        return DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))).toLowerCase();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
public static String sha256(String s) {
    try {
        return DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))).toLowerCase();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
鹊巢 2024-11-05 13:06:06

在Java中,MessageDigest类用于计算加密哈希值。此类提供加密哈希函数(MD5SHA-1SHA-256)来查找文本的哈希值。

使用 SHA-256 算法的代码示例。

public void printHash(String str) throws NoSuchAlgorithmException {

MessageDigest md=MessageDigest.getInstance("SHA-256");

byte[] sha256=md.digest(str.getBytes(StandardCharsets.UTF_8));

   for(byte b : sha256){

      System.out.printf("%02x",b);

  }
}

In Java, MessageDigest class is used to calculate cryptographic hashing value. This class provides cryptographic hash function ( MD5, SHA-1 and SHA-256) to find hash value of text.

Code example for using SHA-256 algorithm.

public void printHash(String str) throws NoSuchAlgorithmException {

MessageDigest md=MessageDigest.getInstance("SHA-256");

byte[] sha256=md.digest(str.getBytes(StandardCharsets.UTF_8));

   for(byte b : sha256){

      System.out.printf("%02x",b);

  }
}
韵柒 2024-11-05 13:06:06

以下方法展示了如何使用 sha-256String 进行哈希处理
算法并将结果编码为hex格式。这是在数据库中散列和存储密码的常用格式:

public static String sha256(final String data) {
    try {
        final byte[] hash = MessageDigest.getInstance("SHA-256").digest(data.getBytes(StandardCharsets.UTF_8));
        final StringBuilder hashStr = new StringBuilder(hash.length);

        for (byte hashByte : hash)
            hashStr.append(Integer.toHexString(255 & hashByte));

        return hashStr.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

Here's a method that shows how to hash a String with the sha-256
algorithm and encode the result in hex format. This is an often used format to hash and store passwords in a database:

public static String sha256(final String data) {
    try {
        final byte[] hash = MessageDigest.getInstance("SHA-256").digest(data.getBytes(StandardCharsets.UTF_8));
        final StringBuilder hashStr = new StringBuilder(hash.length);

        for (byte hashByte : hash)
            hashStr.append(Integer.toHexString(255 & hashByte));

        return hashStr.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文