Generate SHA-1 Hash in Java With Example

SHA-1 Example Java

We just saw the SHA-256 Hashing example in the below example.

In this example, we take a look at SHA-1 Hashing.

The SHA-1 stands for "Secure Hash Algorithm 1". It is an old cryptographic hash function that generates a fixed-size 160-bit (20-byte) hash value.

Note that SHA-1 is considered less secure than SHA-256 due to vulnerabilities, but is still used in various legacy systems.

Example:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaSHA1HashExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        String algorithmSha1 = "SHA-1";
        String inputMessage = "Code2care";
        MessageDigest sha1MessageDigest = MessageDigest.getInstance(algorithmSha1);
        byte[] hashBytes = sha1MessageDigest.digest(inputMessage.getBytes());

        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            hexString.append(String.format("%02x", b));
        }

        System.out.println("Message:" + inputMessage);
        System.out.println("SHA-1 Hash: " + hexString.toString());
    }
}

Output:

Message:Code2care
SHA-1 Hash: 60b581839836083f4f62467bc61424b675f5cb0d

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!