原代码
@Test
public void des3DecodeXml2() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -319);
Long beginTime = calendar.getTimeInMillis();
String format = DateUtil.format(new Date(beginTime), "yyyyMMdd");
System.out.println(format);
byte[] key = EncodingUtils.getBytes(format, "UTF-8");
byte[] keyIV = "IOQVBBBA".getBytes(UTF_8);
String s = "/rn5ToUKiOGDX0KFTbftjxam+IjHB9yBuFgdPS8NFUm1uBoM2PiUk3itP4eNyYqiV4D7QlhVxq0=";
//加密 (错)
byte[] data = EncodingUtils.getBytes(s, "UTF-8");
int byteLen = key.length;
if (byteLen < 24) {
byte[] tmpKey = new byte[24];
System.arraycopy(key, 0, tmpKey, 0, byteLen);
key = tmpKey;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
deskey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyIV);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
int length = data.length;
byte[] data2 = new byte[length + (8 - length % 8)];
//删掉↓
if (length % 8 != 0){
System.out.println("不是8的整数倍");
for (int i = 0; i < length; i++) {
data2[i] = data[i];
}
}
System.out.println(data2.length);
byte[] bOut = cipher.doFinal(data);
System.out.println(new String(bOut, "UTF-8"));
}
出现错误
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
成功的代码
@Test
public void des3DecodeXml3() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -319);
Long beginTime = calendar.getTimeInMillis();
String format = DateUtil.format(new Date(beginTime), "yyyyMMdd");
System.out.println(format);
byte[] key = EncodingUtils.getBytes(format, "UTF-8");
byte[] keyIV = "IOQVBBBA".getBytes(UTF_8);
String s = "/rn5ToUKiOGDX0KFTbftjxam+IjHB9yBuFgdPS8NFUm1uBoM2PiUk3itP4eNyYqiV4D7QlhVxq0=";
//sun.misc 解密
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] data = base64Decoder.decodeBuffer(s);
int byteLen = key.length;
if (byteLen < 24) {
byte[] tmpKey = new byte[24];
System.arraycopy(key, 0, tmpKey, 0, byteLen);
key = tmpKey;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
deskey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyIV);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
System.out.println(new String(bOut, "UTF-8"));
}