Encrypt a string using SHA encryption

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");
			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.

Leave a Reply

Your email address will not be published. Required fields are marked *