Java Program to implement Password Hashing using SHA-256:

              A simple java security Program is implemented here. It uses SHA-256.

What is SHA-256?

              Secure Hash Algorithm 256-bit is the expansion of SHA-256. It is a hashing algorithm in the form of cryptography. The input data size is 32 bits. Common usage of this algorithm deals with password hashing, data integrity and digital signatures.

Logic behind the program:

  • A password is given by the user as input.
  • This password is hashed in the format of 32 bits by the use of SHA-256 function.
  • Here, MessageDigest is used to make the user password into hashed format.

Program implementation:

              Program implementation starts with including the built-in packages from java.security.

  • A Public class”PassWordHashEg” is created with main() function.
  • A string variable “pwd” is assigned with user password.
  • Using a try catch block, the process is created.
  • A MessageDigest object is created and it gets assigned the instance of SHA-256.
  • Using digest function, it gets the bytes of user password “pwd”. The value is assigned to a byte array hBytes.
  • StringBuilder object sBuilder is created.
  • Using a for loop, the process is repeated until last hBytes value.
  • Each and every byte is converted to hash value and added to string builder sBuilder.
  • Finally, original password and hashed password is printed as output.

Program:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class PassWordHashEg {

    public static void main(String[] args) {

        String pwd = "Mypassword@6";

        try {

            MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");

            byte[] hBytes = msgDigest.digest(pwd.getBytes());

 

            StringBuilder sBuilder = new StringBuilder();

            for (byte b : hBytes) {

                sBuilder.append(String.format("%02x", b));

            }

            System.out.println("The original Password is: " + pwd);

            System.out.println("The Hashed Password is: " + sBuilder.toString());

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        }

    }

}

Output:

C:\raji\blog>javac PassWordHashEg.java

C:\raji\blog>java PassWordHashEg

The original Password is: Mypassword@6

The Hashed Password is: c9dc8f3bb0ffe6a8883899a6d4c97a9572a6f16c137c167e8b24e60b324d7b79

 Applications:

Security Protocols (SSL/TLS and Digital Signatures)

Blockchain Technology.

This is the way of creating a java program to implement Password Hashing using SHA-256 is explained briefly. Keep coding!!!!

No comments:

Post a Comment