简体   繁体   中英

What is SHA-256 for? And how to create it in Java?

I read SHA-256 from a book, but the book doesn't explain what it is for? The book explained how to create it in Java. However, I failed to understand what Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)) is for. Can someone explain it to me in detail?

在此处输入图片说明

SHA-256 is called a hash algorithm, and its purpose is simple: it takes any data and generates a unique series of bytes to represent it. There is no way to reverse this process, and there are no known instances of a SHA-256 hash being not unique.

The purpose of the line of code in question is to generate one character of the final SHA-256 output. Java gives you the has in raw data (a byte array) and we typically convert it to hexadecimal to represent it as a string. That line of code is pretty complex, so I'll go over what each part of it does separately.

sb.append(); is taking the imput and adding it to the result stored in a StringBuilder.

Integer.toString(); Takes a number and represents it as a literal string

byteData[i] & 0xff Selects the current byte of hash data and uses the bitwise and operation using 0xff (so for each bit in the byte, if the corresponding bit in 0xff is the same, the output is a 1, if not the output is a 0.

string.substring(1); Outputs the string starting after the first character.

Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1))

is one way of converting a byte value to a string that's exacly two character wide, showing the byte's hexadecimal value. Having a look at String's Javadoc page will help.

The combination of 0x100 and substring(1) ensures that byte values < than 16 decimal (that is, 0 to F in hex) are also represented as two characters.

By the way:

String.format("%02x",byteData[i])

does exactly the same, and might be considered more readable, especially by people who are used to C printf style format strings.

Lastly, why (byteData[i] & 0xff) ? See here for a detailed explanation:

It works because Java will perform a widening conversion to int, using sign extension, so instead of a negative byte you will have a negative int. Masking with 0xff will leave only the lower 8 bits, thus making the number positive again (and what you initially intended).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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