Pages

SHA-1 In Java

SHA-1 produces a message digest based on principles similar to those used by Ronald L. Rivest of MIT in the design of the MD4 and MD5 message digest algorithms, but has a more conservative design.

The Secure Hash Algorithm takes a message of less than 264 bits in length and produces a 160-bit message digest which is designed so that it should be computationally expensive to find a text which matches a given hash. ie if you have a hash for document A, H(A), it is difficult to find a document B which has the same hash, and even more difficult to arrange that document B says what you want it to say.

You can use the SHA-1 algorithm for securing password and to check the  integrity of your file and data.

When storing user details in a repository, you should avoid storing user passwords in clear text, because that makes them vulnerable to hackers. Instead, you should always store encrypted passwords in your repository.

You can also use the  SHA-1 algorithm to check the Duplicate File. MD5 can also be used for checksum.


A checksum is a small-sized datum derived from a block of digital data for the purpose of detecting errors which may have been introduced during its transmission or storage. It is usually applied to an installation file after it is received from the download server. By themselves, checksums are often used to verify data integrity but are not relied upon to verify data authenticity.

Now I am going to show you, How to use SHA-1 in Java

Java has a class  "MessageDigest" inside java.security package, that contains the implementation of SHA-1

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value.

package com.esc.validator;

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

public class SHA1 {

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

  String testString = "I am going to kanpur";
  MessageDigest md = MessageDigest.getInstance("SHA-1");
  byte[] digest = md.digest(testString.getBytes());

  StringBuilder sb = new StringBuilder();
  for (byte b : digest) {
   sb.append(String.format("%02x", b & 0xff));
  }
  System.out.println(sb.toString());

 }

}

Output 

48ebce1dcd35bc56c5b8223711d4c98375859e44 

MD5 in Java

References
https://en.wikipedia.org/wiki/SHA-1

1 comment:

  1. That is an extremely smart written article. I will be sure to bookmark it and return to learn extra of your useful information. Thank you for the post. I will certainly return.

    ReplyDelete