packagecom.wintv.common;importjavax.crypto.Cipher;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;/*******************************************************************************
* AES加解密算法
*
*@authorarix04
**/publicclassAES {//加密publicstaticString Encrypt(String sSrc, String sKey)throwsException {if(sKey==null) {
System.out.print("Key为空null");returnnull;
}//判断Key是否为16位if(sKey.length()!=16) {
System.out.print("Key长度不是16位");returnnull;
}byte[] raw=sKey.getBytes();
SecretKeySpec skeySpec=newSecretKeySpec(raw,"AES");
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv=newIvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);byte[] encrypted=cipher.doFinal(sSrc.getBytes());returnbyte2hex(encrypted).toLowerCase();
}//解密publicstaticString Decrypt(String sSrc, String sKey)throwsException {try{//判断Key是否正确if(sKey==null) {
System.out.print("Key为空null");returnnull;
}//判断Key是否为16位if(sKey.length()!=16) {
System.out.print("Key长度不是16位");returnnull;
}byte[] raw=sKey.getBytes("ASCII");
SecretKeySpec skeySpec=newSecretKeySpec(raw,"AES");
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv=newIvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);byte[] encrypted1=hex2byte(sSrc);try{byte[] original=cipher.doFinal(encrypted1);
String originalString=newString(original);returnoriginalString;
}catch(Exception e) {
System.out.println(e.toString());returnnull;
}
}catch(Exception ex) {
System.out.println(ex.toString());returnnull;
}
}publicstaticbyte[] hex2byte(String strhex) {if(strhex==null) {returnnull;
}intl=strhex.length();if(l%2==1) {returnnull;
}byte[] b=newbyte[l/2];for(inti=0; i!=l/2; i++) {
b[i]=(byte) Integer.parseInt(strhex.substring(i*2, i*2+2),16);
}returnb;
}publicstaticString byte2hex(byte[] b) {
String hs="";
String stmp="";for(intn=0; n
stmp=(java.lang.Integer.toHexString(b[n]&0XFF));if(stmp.length()==1) {
hs=hs+"0"+stmp;
}else{
hs=hs+stmp;
}
}returnhs.toUpperCase();
}publicstaticvoidmain(String[] args)throwsException {/** 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定*/String cKey="1234567890123456";//需要加密的字串String cSrc="Email : arix04@xxx.com";
System.out.println(cSrc);//加密longlStart=System.currentTimeMillis();
String enString=AES.Encrypt(cSrc, cKey);
System.out.println("加密后的字串是:"+enString);longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗时:"+lUseTime+"毫秒");//解密lStart=System.currentTimeMillis();
String DeString=AES.Decrypt(enString, cKey);
System.out.println("解密后的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗时:"+lUseTime+"毫秒");
}
}