当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。