开发者

Decryption bug using des ede, javax.crypto.badpaddingexception

开发者 https://www.devze.com 2023-03-23 12:55 出处:网络
I\'ve been stuck on a bug in my code, it will not let me decrypt properly! I am only passing eight bytes of data to dataBytes and I am passing

I've been stuck on a bug in my code, it will not let me decrypt properly! I am only passing eight bytes of data to dataBytes and I am passing a 24 byte key to keyBytes. I am trying t开发者_如何学编程o return the decrypted data as an array of bytes. I keep getting the bad padding exception.

Thanks!

Here is the code snippet:

private static byte[] DESEdeDecrypt(byte[] keyBytes, byte[] dataBytes){

    byte[] decryptedData = null;
    try{
        DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes, 0); 
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey key = keyFactory.generateSecret(keySpec); 
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.DECRYPT_MODE, key);
        decryptedData = cipher.doFinal(dataBytes);
    }
    catch(Exception e){System.out.println(e);}  

    return decryptedData;


You must use the same padding to decrypt as you did to encrypt. It is better to set it explicitly rather than to rely on defaults. Best also to specify the mode at both ends as well:

Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

DESede is slow and obsolescent. You shouldn't use it except for compatibility with old code. For new work it is better to use AES.

0

精彩评论

暂无评论...
验证码 换一张
取 消