Thursday, July 7, 2011

SHA encrypt the password

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;
}
}
}

No comments: