Search code examples
c++des

C++ Des encryption with 16 bytes key


I'm trying to encrypt in DES a text with dynamic length with a 16 bytes key, but there is a problem with the block size of the key and text, i'm using openssl library for DES encryption. How can I use keys with 16 bytes of length.

Here my example:

char * Encrypt( char Key, char *Msg, int size) { 
      static char*    Res;
      DES_cblock      Key2;
      DES_key_schedule schedule;

      Res = ( char * ) malloc( size );

      memcpy(Key2, Key, 8);
      DES_set_odd_parity( &Key2 );
      DES_set_key_checked( &Key2, &schedule );

      unsigned char buf[9];    
      buf[8] = 0;

      DES_ecb_encrypt(( DES_cblock  ) &Msg, ( DES_cblock  ) &buf, &schedule, DES_ENCRYPT );    
      memcpy(Res, buf, sizeof(buf));    
      return (Res);
}

int main(int argc, char const *argv[]) {
      char key[] = "password";
      char clear[] = "This is a secret message";
      char *encrypted;

      encrypted = (char *) malloc(sizeof(clear));

      printf("Clear text\t : %s \n",clear); 

      memcpy(encrypted, Encrypt(key, clear, sizeof(clear)), sizeof(clear));

      printf("Encrypted text\t : %s \n",encrypted);
      return 0;
}

Solution

    1. DES has a 8-byte 56-bit key (the LSB is not used as part of the key, it is for parity) so you can't use a 16-byte key (parity is generally ignored).

    2. Don't use DES, it is not secure and has been replaced with AES.

    3. Don't use ECB mode, it is insecure, see ECB mode, scroll down to the Penguin.

    AES allows 128, 192 and 256 bit keys.