• October 5, 2024

How to implement SHA-256 Encryption in Java

Encryption is the process of converting plain text into an unreadable form of data called cipher text, to protect it from unauthorized access or modification. SHA-256 is a cryptographic hash function that takes an input and produces a fixed-size, unique output.

Here’s an example code in Java using SHA-256:

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Example {

   public static void main(String[] args) {
      String text = "Hello, world!"; // The text to be encrypted
      String hash = sha256(text); // The encrypted hash value
      System.out.println("Plain text: " + text);
      System.out.println("SHA-256 hash: " + hash);
   }

   public static String sha256(String text) {
      try {
         MessageDigest digest = MessageDigest.getInstance("SHA-256");
         byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
         StringBuilder hexString = new StringBuilder();
         for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
         }
         return hexString.toString();
      } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException(e);
      }
   }
}

This code uses the MessageDigest class from the java.security package to get an instance of the SHA-256 algorithm. It then passes the plain text to be encrypted to the digest() method, which returns the encrypted hash value as an array of bytes. The code then converts the byte array into a hexadecimal string using a StringBuilder and returns it as the final encrypted hash value.

Leave a Reply

Your email address will not be published. Required fields are marked *