java encrypt example

a very simple example of encrypt

config.properties file:

#密码加密算法
encrypt=MD5

encrypt class:

/**
*
*/
package casco.com.tse.util.sys.co;

import java.security.MessageDigest;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;

import casco.com.tse.hibernate.dao.tools.ReadProperty;

/**
* password encryption
*
* @author Joshua
*
*/
public class Crypt {

private static Logger logger = Logger.getLogger(Crypt.class);
private static String encalg = ReadProperty.getKey(“encrypt”);

/***********
* encrypt password without salt
*
* @param passwd
* @return
*/
public static String encpass(String passwd) {
return encpass(passwd, “”);
}

/***********
* encrypt password with salt
*
* @param passwd
* @param salt
* @return
*/
public static String encpass(String passwd, String salt) {
if (passwd == null) {
throw new NullPointerException(“password can not be null!”);
}
if (salt == null) {
salt = “”;
}
passwd = passwd + salt;
if (encalg == null || encalg.isEmpty() || encalg.equalsIgnoreCase(“NONE”)) {
return passwd;
}
String encryptpass = “”;
try {
byte[] source = passwd.getBytes();
MessageDigest digest = null;
byte[] di1 = null;
digest = MessageDigest.getInstance(encalg);
// System.out.println(ReadProperty.getKey(“encrypt”));
digest.update(source);
di1 = digest.digest();
encryptpass = new String(Hex.encodeHex(di1));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
logger.error(e.toString());
}
return encryptpass;
}

/***********
* validate password which had encrypted without salt
*
* @param encryptedPasswd
* @param passwd
* @return
*/
public static boolean validate(String encryptedPasswd, String passwd) {
return validate(encryptedPasswd, passwd, “”);
}

/************
* validate password which had encrypted with salt
*
* @param encryptedPasswd
* @param passwd
* @param salt
* @return
*/
public static boolean validate(String encryptedPasswd, String passwd,
String salt) {
String encrypt = encpass(passwd, salt);
if (encrypt.equals(encryptedPasswd)) {
return true;
}
return false;
}
}

This entry was posted in Computer, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s