Search code examples
cencryptionopenssl3des

triple des cbc encryption in C


How I can decrypt by DES_ENCRYPT in c using openssl library. I found the following function to decrypt and it worked fine when the lengh of key is 8 byte! But when I use 16 byte key, it results wrong value!

int CBC_3Des_Decrypt(char *data, char *okey)
{
DES_key_schedule ks;
DES_cblock ivec = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

int i = 0;
int len = 0;
int nlen = 0;

unsigned char ch = '\0';
unsigned char *ptr = NULL;

unsigned char src[16] = {0};
unsigned char dst[16] = {0};

unsigned char block[8] = {0};

ptr = hex2bin(okey, strlen(okey), &nlen);
memcpy(block, ptr, 8);
free(ptr);
DES_set_key_unchecked((const_DES_cblock*)block, &ks);

len = strlen((char *)data);
ptr = hex2bin(data, len, &nlen);
len = (nlen / 8 + (nlen % 8 ? 1: 0)) * 8;
memcpy(src, ptr, len);
free(ptr);

ch = 8 - nlen % 8;
memset(src + nlen, ch, 8 - nlen % 8);

for (i = 0; i < len; i++) {
    TRACE(("%.2X", *(src + i)));
}

DES_ncbc_encrypt(src, dst, sizeof(src), &ks, &ivec, DES_DECRYPT);

for (i = 0; i < len; i++) {
    TRACE(("%.2X", *(dst + i)));
}

return 0;
}

How I can decrypt or encrypt using this library with 16 byte key?


Solution

  • The call you're making (DES_ncbc_encrypt) is the DES algorithm, not 3DES. I suspect you meant to call DES_ede3_cbc_encrypt.

    It's important not to confuse DES and 3DES ("triple DES"). They're related algorithms, but not the same. Inside of OpenSSL, 3DES is generally called EDE3. EDE3 is a specific way of implementing Triple DES (and is the one everyone uses, so in practice they're generally synonymous).