當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java SHA-256 Hash用法及代碼示例


定義:
在密碼學中,SHA是加密哈希函數,它以20字節作為輸入,並以十六進製數(約40位長)呈現哈希值。

消息摘要類:
要在Java中計算加密哈希值,將使用MessageDigest Class(位於包java.security下)。

MessagDigest類提供以下加密哈希函數來查找文本的哈希值,它們是:


  1. MD5
  2. SHA-1
  3. SHA-256

該算法以稱為getInstance()的靜態方法初始化。選擇算法後,它將計算摘要值並以字節數組形式返回結果。

使用BigInteger類,該類將結果字節數組轉換為其sign-magnitude表示形式。該表示形式轉換為十六進製格式,以獲取MessageDigest

例子:

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);  
        }  
    }  
} 
輸出:
HashCode Generated by SHA-256 for:

GeeksForGeeks:112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade

hello world:b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

應用:

  1. 密碼學
  2. 數據的完整性


相關用法


注:本文由純淨天空篩選整理自bilal-hungund大神的英文原創作品 SHA-256 Hash in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。