您的位置:首页 > 其它

DES3加密解密类

2015-07-31 16:44 225 查看
public class DES3 {
private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish
private static final byte[] keyBytes = {0x12, 0x22, 0x4F, 0x58, (byte)0x88, 0x10, 0x40, 0x38
, 0x28, 0x25, 0x79, 0x51, (byte)0xCB, (byte)0xDD, 0x55, 0x66
, 0x77, 0x29, 0x74, (byte)0x98, 0x30, 0x40, 0x36, (byte)0xE2l};//24字节的密钥
//keybyte为加密密钥,长度为24字节
//src为被加密的数据缓冲区(源)
private static byte[] encryptMode(byte[] keybyte, byte[] src) {
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}

//keybyte为加密密钥,长度为24字节
//src为加密后的缓冲区
private static byte[] decryptMode(byte[] keybyte, byte[] src) {
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
// Cipher c1 = Cipher.getInstance(Algorithm);
Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}

//转换成十六进制字符串
private static String byte2hex(byte[] b) {
String hs="";
String stmp="";
for (int n=0;n<b.length;n++) {
stmp=(java.lang.Integer.toHexString(b
& 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1)  hs=hs+":";
}
return hs.toUpperCase();
}

/******
* ***
* @author     :QZC
* @createDate :2014年9月10日 下午10:08:02
* 函数功能描述:加密字符串
* @param input
* @return
****
*/
public static String encodeString(String  input){
try{
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
byte[] encoded = encryptMode(keyBytes, input.getBytes());
BASE64Encoder base64en = new BASE64Encoder();
return base64en.encode(encoded);
}catch(Exception e){
e.printStackTrace();
}
return null;
}

/******
* @author     :QZC
* @createDate :2014年9月10日 下午10:14:03
* 函数功能描述:解密加密后的字符串
* @param input
* @return
****
*/
public static String decodeString(String input){
try{
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
byte[] srcBytes = decryptMode(keyBytes, Base64.decode(input));
return new String(srcBytes);
}catch(Exception e){
e.printStackTrace();
}
return null;
}

public static void main(String[] args){
try{
String beforeEncode="123456";
String afterEncode=encodeString(beforeEncode);
System.out.println("afterEncode:"+afterEncode);
String afterDecode=decodeString(afterEncode);
System.out.println("afterDecode:"+afterDecode);
}catch(Exception e){
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: