Search the Site

Sponsors

bottom corner

Encrypt a string using SHA encryption

At times, we run into the need to encrypt strings. One popular situation when this is needed is when we need to store users' passwords in a database. This note provides a simple Java class that makes use of the fairly strong SHA (Secure Hash Algorithm) 160-bit encryption method.

This page is filed under keyword(s): java.

The following class provides the venue to translate the sample string "mySecr3tP4ssw0rd" into the encrypted string "Nj3lzFVrt9dx2gENZeh2H5xY6PY=", which would be tougher to crack by brute force than a plain password in case a hackers gets hold of your data store.

import java.security.MessageDigest;
import sun.misc.BASE64Encoder;

/**
 * String encryption related utilities.
 * @author C. Peter Chen of http://dev-notes.com
 * @date 20080512
 */

public class StringEncryptUtil {
	/**
	 * This main() class is used for demo only.
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("SHA encrypted mySecr3tP4ssw0rd: " + encryptSha("mySecr3tP4ssw0rd"));
	}
	
	/**
	 * Performs a SHA encryption process on the incoming string parameter.
	 * @param inputStr
	 * @return SHA-encrypted string if successful, or null if there are problems.
	 */
	public static synchronized String encryptSha(String inputStr) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA");
			md.update(inputStr.getBytes("UTF-8"));
			byte digest[] = md.digest();
			return (new BASE64Encoder()).encode(digest);
		}
		catch (Exception e) {
			return null;
		}
	}
}

As you will notice, there is no decrypt method, that is because there probably is no need for one. For instance, we have "Nj3lzFVrt9dx2gENZeh2H5xY6PY=" in the data store for the user Scott; when Scott logs in, we should SHA-encrypt the password he had just typed in, and compare the encrypted string with the encrypted string found in the data store.

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): java.
Author: C. Peter Chen
Last updated: 12 May 2008

bottom corner