简体   繁体   English

了解 SHA-256 哈希

[英]Understanding SHA-256 Hashing

I am using Sha-256 hashing in my Java program which is working as per behavior.我在我的 Java 程序中使用 Sha-256 散列,该程序按行为工作。

I am actually a bit confused in the function I have used for SHA-256.我实际上对我用于 SHA-256 的 function 有点困惑。

Following is the code of the function: function的代码如下:

// Function for generating to Hash of the file content..
    public static String generateHash( String fileContent ) 
     {
        String hashtext = EMPTY_STRING;

        try {

            // SHA - 256 Message Digest..
            MessageDigest shaDigest = MessageDigest.getInstance( "SHA-256" );

            // digest() method is called 
            // to calculate message digest of the input string 
            // returned as array of byte 
            byte[] messageDigest = shaDigest.digest( fileContent.getBytes() ); 

            // Convert byte array into signum representation 
            BigInteger no = new BigInteger( 1, messageDigest ); 

            // Convert message digest into hex value 
            hashtext = no.toString( 16 ); 

            // Add preceding 0s to make it 32 bit 
            while ( hashtext.length() < 32 ) { 
                hashtext = "0" + hashtext; 
            }

        }
        catch ( Exception hashingException ) {

            System.out.println( "Exception in Hashing of Content = " + hashingException );

        }
         // return the HashText 
         return hashtext; 
     }

Now, here I am confused in three statements;现在,在这里我对三个陈述感到困惑; as I am unaware of what is their actual purpose since I have surfed them on the internet but didnt get any explanatory stuff.因为我不知道它们的实际目的是什么,因为我在互联网上浏览过它们但没有得到任何解释性的东西。 Can some one elaborate these three steps to me?有人可以向我详细说明这三个步骤吗?

STATEMENT 1声明 1

BigInteger no = new BigInteger( 1, messageDigest ); 

STATEMENT 2声明 2

 hashtext = no.toString( 16 );

STATEMENT 3声明 3

while ( hashtext.length() < 32 ) { 
    hashtext = "0" + hashtext;
}

BigInteger no = new BigInteger( 1, messageDigest ); 

Covert the bytes to a Positive Sign-Magnitude representation.将字节转换为正符号幅度表示。 Read Javadoc for more info.阅读Javadoc了解更多信息。

hashtext = no.toString( 16 );

Convert the BigInteger number to a Base 16 (Hex Decimal) StringBigInteger数字转换为 Base 16(十六进制十进制)字符串

while ( hashtext.length() < 32 ) { 
    hashtext = "0" + hashtext;
}

Prepend 0 until the hashtext has the size of 32.在 hashtext 的大小为 32 之前添加0

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

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