Search code examples
encryptioncryptographydes

DES encrypt file less than 64 bytes


I want to create an encryption program for studies using the DES algorithm. If my data is more than 64 bytes I can use CBC or EBC mode to encrypt it. But what if my data file is less than 64 bytes? Should I add white spaces at the end of the file to fill it and get 64 bytes? What is a good approach?


Solution

  • The DES block size is 64 bits, or 8 bytes. If your message is less than 8 bytes, you need to pad it. A common scheme is to fill out the block by repeatedly appending the length of the padding. For example, if your message is 3 bytes, and you need to fill an 8-byte block, you need 5 bytes of padding. Append the value 5, 5 times, to the message:

    // Message ABC + 5 bytes of padding
    0x41 0x42 0x43 + 0x05 0x05 0x05 0x05 0x05
    

    This implies you need at least one byte of padding, so if your message is a complete block, you need to add a whole extra block just for padding. To remove the padding, look at the value of the last byte, N, and verify that the last N bytes of the plain text have that same value.