CNS Lab Exercise-10


 EXERCISE-10


Calculate the message digest of a text using the SHA-1 algorithm in JAVA.



import java.security.MessageDigest;
import java.util.Scanner;

public class SHA1UserInput {

    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);

            // User input
            System.out.print("Enter text: ");
            String text = sc.nextLine();

            // SHA-1 MessageDigest object
            MessageDigest md = MessageDigest.getInstance("SHA-1");

            // Generate hash
            byte[] hashBytes = md.digest(text.getBytes());

            // Convert bytes to hex
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }

            // Output
            System.out.println("Original Text: " + text);
            System.out.println("SHA-1 Message Digest: " + sb.toString());

        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}


Sample Output:


Enter text: hello

Original Text: hello
SHA-1 Message Digest: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d