【AES】
一種對稱加密算法,DES的取代者。
加密相關文章見:Java加密技術
【代碼】
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
/**
* 功能:AES加密解密工具類
* @date : 2016-01-27
*/
public class AesUtil {
/**
* 對密碼進行解密操作
* @param strPlain 密文
* @param key 解密密鑰
* @return
*/
public static String decrypt(String strPlain,String key){
BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());
CipherParameters param = new KeyParameter(Hex.decode(key));
cipher.init(false, param);
byte[] output = Hex.decode(strPlain);
byte[] out = new byte[output.length];
int len2 = cipher.processBytes(output, 0, output.length, out, 0);
try {
cipher.doFinal(out, len2);
return new String(out);
} catch (DataLengthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidCipherTextException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 對密碼進行加密操作
* @param password
* @param key
* @return
*/
public static String encrypt(String password,String key){
BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());
CipherParameters param = new KeyParameter(Hex.decode(key));//key
byte[] input =password.getBytes();
byte[] out = new byte[input.length];
cipher.init(true, param);
int len1 = cipher.processBytes(input, 0, input.length, out, 0);
try {
cipher.doFinal(out, len1);
String str = new String(Hex.encode(out));
return str;
} catch (DataLengthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidCipherTextException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 對密碼進行加0操作
* @param password
* @return
*/
public static String addzero(String password){
int length = password.length();
if(length<30){
for(int i=length;i<30;i++){
password=password+"0";
}
}
if(length>9){
password = password + String.valueOf(length);
}else{
password = password + "0" + String.valueOf(length);
}
//System.out.println(password);
return password;
}
/**
* 對密碼進行還原操作,去除之前添加的0
* @param password
* @return
*/
public static String removezero(String password){
if(!Validators.isNull(password)&&password.length()==32){
String length = password.substring(30, 32);
char c = length.charAt(0);
if(c == '0'){
length = length.substring(1, 2);
}
return password.substring(0, Integer.parseInt(length));
}
return "";
}
}
String password = AesUtil.encrypt(AesUtil.addzero(pwd),HashHelper.MD5Encode(hashKey));//加密
String password = AesUtil.removezero(AesUtil.decrypt(pwd,HashHelper.MD5Encode(key)));// 解密