Wednesday, March 20, 2013

RC2 Encryption in C

I recently had to implement a the RC2 Rivest (Block) Cipher in C. I didn't find too many examples so I figured I'd post mine here. This is a 64-bit block cipher with a variable key size.

This example uses the OpenSSL library.

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "openssl/rc2.h"

#define BITS 64

UBYTE *rc2_encrypt(const UBYTE *key,  UINT32 key_size,
       const UBYTE *data, UINT64 data_size)
{
    RC2_KEY rc2_ks;
    UBYTE *output;
    UBYTE iv[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    if (key_size % 8 != 0)
    {
        printf("RC2 key size should be a multiple of 8!\n");
        return NULL;
    }

    output = (UBYTE *) malloc(data_size);
    if (output == NULL)
    {
        printf("Out of memory!\n");
        return NULL;
    }

    RC2_set_key(&rc2_ks, key_size, key, BITS);
    RC2_cbc_encrypt(data, output, data_size, &rc2_ks, iv, RC2_ENCRYPT);

    return output;
}

UBYTE *rc2_decrypt(const UBYTE *key,  UINT32 key_size,
       const UBYTE *data, UINT64 data_size)
{
    RC2_KEY rc2_ks;
    UBYTE *output;
    UBYTE iv[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    if (key_size % 8 != 0)
    {
        printf("RC2 key size should be a multiple of 8!\n");
        return NULL;
    }

    output = (UBYTE *) malloc(data_size);
    if (output == NULL)
    {
        printf("Out of memory!\n");
        return NULL;
    }

    RC2_set_key(&rc2_ks, key_size, key, BITS);
    RC2_cbc_encrypt(data, output, data_size, &rc2_ks, iv, RC2_DECRYPT);

    return output;
}

Cheers!

No comments:

Post a Comment