aGang513 2014-12-18 01:20 采纳率: 0%
浏览 1533

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 2014-12-18 06:30
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao