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;
if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
}
}
调用
//DES
//DES加密
byte[] en = DESUtils.enCode(hexStringToBytes("3132333435363738"), "A1A2A3A4A5A6A7A8");
//DES解密
try {
byte[] dn = DESUtils.deCode(hexStringToBytes("B1C3D2A87DBDB68FA73FBBBCD6F083AC"), "A1A2A3A4A5A6A7A8");
} catch (Exception e) {
e.printStackTrace();
}
//3DES
//3DES加密
String key = "A1A2A3A4A5A6A7A8" //K1密钥
+"B1B2B3B4B5B6B7B8" //K2密钥
+"A1A2A3A4A5A6A7A8"; //K3密钥
byte[] result = DES3Utils.encryptMode(hexStringToBytes(key), hexStringToBytes("3132333435363738"));
//3DES解密
byte[] dnresult = DES3Utils.decryptMode(hexStringToBytes(key), hexStringToBytes("B0920ED6520EAF752E22A1F49B243353"));
//***************************************************************************************
//实现String到byte的转换
public static byte[] hexStringToBytes(String string) {
String hexString = string.replaceAll(" ", "").toUpperCase();
if (hexString.length() <= 0)
return null;
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
DES的明文是3132333435363738,密钥是A1A2A3A4A5A6A7A8,加密后得到B1C3D2A87DBDB68FA73FBBBCD6F083AC,这里面前面16位是明文加密而来的,后面的A73FBBBCD6F083AC是由0808080808080808加密而来的。这8个08是算法自动填充上去的。3DES同样会填充8个08上去再加密。B0920ED6520EAF752E22A1F49B243353后面的2E22A1F49B243353是由填充的0808080808080808加密而来。