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

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

    评论

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误