Java 中的 SHA-256 哈希

原文:https://www.geeksforgeeks.org/sha-256-hash-in-java/

定义: 在密码学中,SHA 是一种密码散列函数,它将输入作为 20 个字节,并以十六进制数表示散列值,长约 40 位。

消息摘要类: 为了计算 Java 中的加密散列值,使用了包 java.security 下的消息摘要类。

MessagDigest 类提供以下加密散列函数来查找文本的散列值,它们是:

  1. 讯息摘要 5
  2. SHA-1
  3. SHA-256

该算法在名为 getInstance() 的静态方法中初始化。选择算法后,它计算摘要值,并以字节数组的形式返回结果。

使用 BigInteger 类,它将结果字节数组转换为它的符号幅度表示。该表示被转换成十六进制格式以获得消息摘要

示例:

Input : hello world
Output : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

Input : GeeksForGeeks
Output : 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade
import java.math.BigInteger; 
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

// Java program to calculate SHA hash value 

class GFG { 
    public static byte[] getSHA(String input) throws NoSuchAlgorithmException
    { 
        // Static getInstance method is called with hashing SHA 
        MessageDigest md = MessageDigest.getInstance("SHA-256"); 

        // digest() method called 
        // to calculate message digest of an input 
        // and return array of byte
        return md.digest(input.getBytes(StandardCharsets.UTF_8)); 
    }

    public static String toHexString(byte[] hash)
    {
        // Convert byte array into signum representation 
        BigInteger number = new BigInteger(1, hash); 

        // Convert message digest into hex value 
        StringBuilder hexString = new StringBuilder(number.toString(16)); 

        // Pad with leading zeros
        while (hexString.length() < 32) 
        { 
            hexString.insert(0, '0'); 
        } 

        return hexString.toString(); 
    }

    // Driver code 
    public static void main(String args[])
    { 
        try 
        {
            System.out.println("HashCode Generated by SHA-256 for:"); 

            String s1 = "GeeksForGeeks"; 
            System.out.println("\n" + s1 + " : " + toHexString(getSHA(s1))); 

            String s2 = "hello world"; 
            System.out.println("\n" + s2 + " : " + toHexString(getSHA(s2))); 
        }
        // For specifying wrong message digest algorithms 
        catch (NoSuchAlgorithmException e) { 
            System.out.println("Exception thrown for incorrect algorithm: " + e); 
        } 
    } 
} 

Output:

HashCode Generated by SHA-256 for:

GeeksForGeeks : 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade

hello world : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

应用:

  1. 密码系统
  2. 数据完整性