Enterprise Architecture & Integration, SOA, ESB, Web Services & Cloud Integration

Enterprise Architecture & Integration, SOA, ESB, Web Services & Cloud Integration

Wednesday 27 April 2016

Using SHA-256 for secure passwords, data integrity protection and digital signatures

Even more seasoned developers mix Encryption with Digest and do not know the difference between them. Both are different and having different purposes. Yes, Digest is not Encryption. Digest is a One-way method and Encryption is two-way method - which essentially means that you can not reconstruct the original message from the message digest whereas you will be able to decrypt the encrypted message to reconstruct the original message.

Digest is used for hashing, checksum, data integrity, digital signature, password etc

Digest is otherwise known as hash, message digest also.

There are many digest algorithms available. Let us see here about SHA-256. Wikipedia says "SHA-2 (Secure Hash Algorithm 2) is a set of cryptographic hash functions designed by the National Security Agency (NSA). SHA stands for Secure Hash Algorithm". You can read more about it here https://en.wikipedia.org/wiki/SHA-2

When you create a digest for a given message using SHA256, it will generate a 32 byte string which is usually represented as 64 digit hexadecimal number. It is not encryption algorithm, so you can not decrypt the digest to reveal the original message.

Here is a Java program to generate digest:

import java.security.MessageDigest;

public class HashingUtil {


public String hash(String message) throws Exception{
System.out.format("Original message is %s\n", message);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(message.getBytes("UTF-8"));

StringBuffer digest = new StringBuffer(64);
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1)
digest.append('0');
digest.append(hex);
}
System.out.format("Digest is %s\n", digest.toString());
return digest.toString();
}

public static void main(String[] args) throws Exception{
String hash = new HashingUtil().hash("iKnowWhatYouDidLastSummer");
System.out.println(hash);
}
}

For Java doc, you can refer here https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html 

Hop you like this post. Let me know your comments if any.