很多时候用户密码保存在数据库中会对他进行加密,这时候一般用MD5加密,因为MD5加了密很难戒,但有时候用户注册或找回密码时,会发邮箱验证,而邮箱验证需要有一个激活链接,链接中到会带user的用户名或者邮箱,这时候的用户名和邮箱号,通常也是会选择给他加密的,但用用户操作完后,要对这个用户名或邮箱进行解密,这样才能识别到底是哪个用户或邮箱在操作,这时候我们就可以用以下的工具类进行加密和解密,只需直接调用静态方法,传一个你想加密的字符串进来即可。
直接复制以下类即可:
package com.tx.cs.util;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* 密碼加密和解密
* Created:
* Update:
* @author Administrator
*
*/
public class PassCrypt {
private static final String
PASSWORD_CRYPT_KEY = "Spring brother is a true man!";
private final static String DES = "DES";
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
private static byte[] hex2byte(byte[] b) {
byte[] b2 = new byte[b.length/2];
for (int n = 0; n < b.length; n+=2) {
String item = new String(b,n,2);
b2[n/2] = (byte)Integer.parseInt(item,16);
}
return b2;
}
/**
* 加密
* @param src 數據源
* @param key 加密密匙
* @return 返回加密后的數據
* @throws Exception
*/
private static byte[] encrypt(byte[] src, byte[] key)throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(src);
}
/**
* 解密
* @param src 數據源
* @param key 加密密匙
* @return 返回解密后的數據
* @throws Exception
*/
private static byte[] decrypt(byte[] src, byte[] key)throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(src);
}
/**
* 獲取加密后的數據
* @param src 數據源
* @return 加密后的字符串
*/
public static String getEncrypt(String password)
{
try{
return byte2hex(
encrypt(password.getBytes(),PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 獲取解密后的數據
* @param src 數據源
* @return 解密后的字符串
*/
public static String getDecrypt(String password)
{
try{
return new String(decrypt(hex2byte(password.getBytes()),
PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 進行密碼的校驗
* @param password 加密后的密碼
* @param inputString 輸入的文本
* @return
*/
public static boolean validatePassword(String password , String inputString)
{
if(password.equals(getEncrypt(inputString))){
return true;
}
return false;
}
}