2 agang513 aGang513 于 2014.12.18 09:20 提问

Java中Des算法的问题,请大神帮忙看看,谢谢!

解密采用与加密不同的密钥,居然得出了正确的明文,代码如下:

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") + "]");
}

}

1个回答

aGang513
aGang513   2014.12.18 14:30

没人回答吗,自己顶一下。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!