Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm currently doing an assignment for a college course using Java's JCA. The application takes in a file and encrypts it (or decrypts it) using DES-ECB. I am fully aware that it's not a secure encryption algorithm.

It encrypts fine, I believe, however when decrypting it blows up with a "Input length must be multiple of 8" even though the original message is being padded with PKCS5.

For the encryption I'm using:
Java
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    
    cipher.init(Cipher.ENCRYPT_MODE, symmetricKey);

    
    File file = new File(filePath);
    
    FileOutputStream outputStream = new FileOutputStream("encrypted_"+file.getName());

    
    CipherInputStream cipherStream = new CipherInputStream( new FileInputStream(file), cipher);


    byte[] buffer = new byte[MAX_BUFFER]; //buffer para leitura
    int bytes; //bytes a ler

    //Encoder base64 - Apache Commons Codec
    Base64 encoder = new Base64();

    
    while ( (bytes = cipherStream.read(buffer)) != -1 ) {
        
        byte[] encodedBuffer = encoder.encode(buffer);
        
        outputStream.write(encodedBuffer, 0, bytes);
    }

    
    cipherStream.close();
    outputStream.flush();

    return outputStream;


For decryption:

Java
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    
    cipher.init(Cipher.DECRYPT_MODE, symmetricKey);

    
    File file = new File(filePath);
    FileInputStream cipheredStream = new FileInputStream(file);

    
    FileOutputStream outputStream = new FileOutputStream("decrypted_"+file.getName());

    
    CipherOutputStream cipherOutStream = new CipherOutputStream(outputStream, cipher);

    byte[] buffer = new byte[MAX_BUFFER];
    int bytes;

    //Decoder base 64 - Apache Commons Codec
    Base64 decoder = new Base64();

    cipheredStream.read(buffer);
    byte[] decodedBuffer = decoder.decode(buffer);
    byte[] output = cipher.doFinal(decodedBuffer);
    cipherOutStream.write(output);

    //TODO bug here -> use this for big files
    /*while ( (bytes = cipheredStream.read(buffer)) != -1 ) {
        byte[] decodedBuffer = decoder.decode(buffer);
        cipherOutStream.write(decodedBuffer, 0, bytes);
    }*/

    cipherOutStream.close();
    cipheredStream.close();

    return outputStream;


I'm just lost and would appreciate knowing what I'm doing wrong.

What I have tried:

I've tried using AES to no avail; I've tried no padding, obviously it didn't work.
I've tried using various variations of DES - nothing.
Also tried to change encrypting key algorithm...
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900