Coders Packet

SHA-256 Encryption using MessageDirect and StringBuilder class in JAVA


SHA-256 hashing is widely used as it is being considered the most secure hashing algorithm in the cryptographic arena.

SHA - 256 Encryption

The SHA(Secure Hash Algorithm) is one of the popular cryptographic hash functions. Let's have a look at how hashing of any data gets encrypted with the help of Java libraries. The SHA-256 algorithm generates an almost unique, fixed-size 256-bit hash which is of type one-way function. The result obtained cannot be decrypted back to the original value.

Steps to generate a hash code using the SHA-256 algorithm.

1. MessageDirect Class in Java

The hash functions transform arbitrary large bit strings called messages, into small, fixed-length bit strings called message digests, such that digests identify the messages that produced them with a very high probability. With the help of these, java provides an inbuilt MessageDigest class for SHA-256 hashing by the following command: 

                                                      MessageDigest message = MessageDigest.getInstance("SHA-256")

The command above provides the message in UTF-8 Standard form which is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte code units

2. Converting it to Hexadecimal form: 

However,  here we have to use a custom byte to hex converter to get the hashed value in hexadecimal. For that, we need BigInteger and StringBuilder class to generate the hexadecimal value. In StringBuilder, toString(int radix) means that the method will return us the string representation for the object defined. For eg., if the value of radix is 16, it means that it will convert the number to hexadecimal form. 

                                                    StringBuilder hexString = new StringBuilder(number.toString(16));


We need to be aware, that the MessageDigest is not thread-safe. Consequently, we should use a new instance for every thread. The java code may not be appropriate for numbers greater than 32 bytes(256 bit = 32 bytes). So, it may throw an error by showing the "NoSuchAlgorithmException" message in the compiler. One of the most interesting part is that the following code can generate a hash for 512 bits too, provided that every bit should be multiple of 32. 

Below is the implementation of the following code:



Download Complete Code


No comments yet