为啥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个回答

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

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问