security

SHA-1 hash function example

With this example we are going to demonstrate how to make a SHA-1 hash function example. The Secure Hash Algorithm is a family of cryptographic functions. In short, to compute the hash value of a String with the SHA-1 algorithm, you should:

  • Create a MessageDigest Object that implements the SHA-1 algorithm, using the getInstance(String algorithm) API method.
  • Reset the MessageDigest for further use, using the reset() API method.
  • Process a byte array encoded from the given string to the MessageDigest Object, using the update(byte[] input) API method.
  • Computate the hash value of the byte array, using the digest() API method,

as described in the encrypt(String x) method of the example below.

package com.javacodegeeks.snippets.core;

public class Main {

    public static void main(String arg[]) throws Exception {

  System.out.println(encrypt("JavaCodeGeeks"));
    }

    public static byte[] encrypt(String x) throws Exception {

  java.security.MessageDigest digest = null;

  digest = java.security.MessageDigest.getInstance("SHA-1");

  digest.reset();

  digest.update(x.getBytes("UTF-8"));

  return digest.digest();
    }
}

Output:

24fb3812e202e13e5f0666cc4f2e097b6422c1bf

 
This was an example of how to make an SHA-1 hash function example in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
KIRANSINH BORASIA
KIRANSINH BORASIA
5 years ago

its giving output like “[B@6d06d69c”.

Back to top button