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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧