解密采用与加密不同的密钥,居然得出了正确的明文,代码如下:
package com.zbd.test;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Base64;
public class DesBase64 {
public static String encDesAndBase64(String strPlaintext, String strKey, String strIv) throws Exception {
String strCiphertext = null;
byte[] byteCiphertext = null;
// 生成KEY
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
SecretKey key = factory.generateSecret(new DESKeySpec(strKey.getBytes()));
// DES加密
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(strIv.getBytes()));
byteCiphertext = cipher.doFinal(strPlaintext.getBytes());
// BASE64编码
strCiphertext = Base64.encodeBase64String(byteCiphertext);
return strCiphertext;
}
public static String decDesAndBase64(String strCiphertext, String strKey, String strIv) throws Exception {
String strPlaintext = null;
byte[] bytePlaintext = null;
// BASE64解码
bytePlaintext = Base64.decodeBase64(strCiphertext);
// 生成KEY
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
SecretKey key = factory.generateSecret(new DESKeySpec(strKey.getBytes()));
// DES解密
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(strIv.getBytes()));
strPlaintext = new String(cipher.doFinal(bytePlaintext));
return strPlaintext;
}
public static void main(String[] args) throws Exception {
String strPlaintext = "{phone:\"11088888888\",name:\"my love\";email:\"888888@qq.com\",isrealname:true}";
String strCiphertext = DesBase64.encDesAndBase64(strPlaintext, "88888888", "12345678");
System.out.println("明文[" + strPlaintext + "]");
System.out.println("密文[" + strCiphertext + "]");
System.out.println("明文[" + DesBase64.decDesAndBase64(strCiphertext, "99999999", "12345678") + "]");
}
}