qq_41474397
欢欢19
采纳率0%
2019-05-19 22:19 浏览 721

为啥DES解密出错,求大佬解答

import java.util.Scanner;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.codec.binary.Hex;

public class DES2 {

public static void main(String[] args) {

    DESEncryption();
    DESDecryption();
}

public static void DESEncryption() {

    try {

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入需要加密内容:");
        String src = sc.nextLine();

        System.out.println("请输入密钥:");
        String str1 = sc.nextLine();
        byte[] bytesKey = str1.getBytes();

        DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = factory.generateSecret(desKeySpec);

        // DES加密
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] result = cipher.doFinal(src.getBytes());
        String hex = DatatypeConverter.printHexBinary(result);
        System.out.println("Hex:" + hex.toLowerCase());
        System.out.println("DES加密:" + Hex.encodeHexString(result));

    } catch (Exception e) {
        // TODO: handle exception
    }
}

    public static void DESDecryption() {

        try {

            Scanner sc = new Scanner(System.in);
            System.out.println("请输入需要解密内容:");
            String str1 = sc.nextLine();

            System.out.println("请输入密钥:");
            String str2 = sc.nextLine();
            byte[] bytesKey = str2.getBytes();

            DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = factory.generateSecret(desKeySpec);

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] result2 = cipher.doFinal(str1.getBytes());

            System.out.println("DES解密:" + new String(result2));
        } catch (Exception e) {
            System.out.println("解密异常");
        }
    }

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • wojiushiwo945you 毕小宝 2019-05-20 09:38

    解密过程的入参不应该是输入的,应该直接用你加密后生成的字符数组。解密字符串不是普通的字符,而需要将字节数组转码成 base64 才行。
    其次,DES 是对称加密算法,秘钥应该用相同的,
    最后一点,异常分支必须打印堆栈信息,否则不知道异常更不能查错。
    还有一点,跟 JDK 的加密套件有关系。
    参考这个 demo 重试看看。

    点赞 1 评论 复制链接分享
  • hjs218 Json-Huang 2019-05-20 12:48

    解密是加密的逆运算,需要保证算法步骤一致,比如加密后调用了Hex.encodeHexString(result),这个方法是做了编码,解密时需要先decode解码,依次类推。

    点赞 评论 复制链接分享

相关推荐