Search code examples
c#copenssltripledes

Converting C openssl TripleDes encryption to .NET


I have been trying to replicate an encryption process for a 3rd party integration. The 3rd party uses openssl, and have given me there C code they use to perform the process. I have been trying to port this process across to C# for weeks, but I appear to be missing something I can not work out. Most likely I am missing something in transposing the C code and OpenSSL libraries, but I can not figure it out for the life of me The main port os OpenSSL to .NET (https://github.com/openssl-net/openssl-net) unfortunatly does not have support for TripleDes, so can not be used

Here is the example C code

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <openssl/dh.h>
#include <openssl/pem.h>
#include <openssl/engine.h>
#include <openssl/bn.h>
#include <openssl/des.h>
#include <openssl/rand.h>

static void encrypt_ean(int argc, char **argv)
{
    size_t i;

    if (argc != 3)
        usage();
    char *mwkstr = argv[1];
    char *ean = argv[2];

    unsigned char mwk[24];
    hex2bin(mwkstr, 48, mwk);

    DES_key_schedule keysched[3];
    set_key_checked(mwk, keysched);

    unsigned char idata[16];
    unsigned char odata[16];
    DES_cblock zero_iv;
    memset(&zero_iv, 0, sizeof(zero_iv));
    if (RAND_bytes(idata+0, 8) != 1) {
        fprintf(stderr, "RAND_bytes failed.\n");
        exit(1);
    }

    for (i=0; i<8; i++)
        idata[8+i] = (i >= eanlen) ? ' ' : ean[i];
    idata[7] = chksum((char *)idata+8, 8);
    if (g_verbose) {
        printf("ean = %s\n", mean);
        printf("idata = ");
        for (i=0; i<sizeof(idata); i++)
            printf("%d %02X\n", (int)i, idata[i]);
        printf("\n");
    }
    DES_ede3_cbc_encrypt(idata, odata, sizeof(odata),
        &keysched[0], &keysched[1], &keysched[2], &zero_iv, DES_ENCRYPT);
    for (i=0; i<sizeof(odata); i++)
        printf("%02X", odata[i]);
    printf("\n");
}

static unsigned char chksum(char *data, size_t datalen)
{
    size_t i;
    unsigned char sum=0;

    for (i=0; i<datalen; i++)
        sum += data[i];
    return sum;
}

static void hex2bin(const char *str, int len, unsigned char *bin)
{
    int i, j, x;

    for (i=0, j=0; i<len; i+=2) {
        char tmpstr[3];
        tmpstr[0] = str[i+0];
        tmpstr[1] = str[i+1];
        tmpstr[2] = '\0';
        sscanf(tmpstr, "%02X", &x);
        bin[j++] = x;
    }
}

static int set_key_checked(unsigned char *key, DES_key_schedule *keysched)
{
    if (DES_set_key_checked((const_DES_cblock *)(key+0), &keysched[0]) < 0) {
set_key_err:
        fprintf(stderr, "DES_set_key_checked failed.\n");
        exit(1);
    }
    if (DES_set_key_checked((const_DES_cblock *)(key+8), &keysched[1]) < 0)
        goto set_key_err;
    if (DES_set_key_checked((const_DES_cblock *)(key+16), &keysched[2]) < 0)
        goto set_key_err;
    return 0;
}

And here is my C# Code (Consider ean = pin for easier transposing)

internal static class PINEncoding
{
    internal static string EncodePIN(string unencodedPIN, string decryptedWorkingKey)
    {
        var bytes = GenerateRandomBytes();
        var asciiPin = ConvertPINToASCIIBytes(unencodedPIN);

        var checksum = new byte[1];
        checksum[0] = ComputeChecksum(asciiPin);

        var pinBlock = ObtainPinBlock(bytes, checksum, asciiPin);

        return EncryptPIN(pinBlock, decryptedWorkingKey);
    }

    private static byte[] GenerateRandomBytes()
    {
        Random rnd = new Random();
        byte[] b = new byte[7];

        rnd.NextBytes(b);
        return b;
    }

    private static byte[] ConvertPINToASCIIBytes(string pin)
    {
        return ASCIIEncoding.ASCII.GetBytes(pin);
    }

    private static byte ComputeChecksum(byte[] data)
    {
        long longSum = data.Sum(x => (long)x);
        return unchecked((byte)longSum);
    }

    private static byte[] ObtainPinBlock(byte[] random, byte[] checksum, byte[] asciiPin)
    {
        var result = new byte[random.Length + checksum.Length + asciiPin.Length];
        Buffer.BlockCopy(random, 0, result, 0, random.Length);
        Buffer.BlockCopy(checksum, 0, result, random.Length, checksum.Length);
        Buffer.BlockCopy(asciiPin, 0, result, random.Length + checksum.Length, asciiPin.Length);

        return result;
    }

    private static string EncryptPIN(byte[] eanBlock, string decryptedWorkingKey)
    {
        var keyAsBytes = HexStringBytesConverter.ConvertHexStringToByteArray(decryptedWorkingKey);

        var byteResult = TripleDESEncryption.Encrypt(eanBlock, keyAsBytes);

        return BitConverter.ToString(byteResult).Replace("-", "");
    }
}
public static class TripleDESEncryption
{
    public static byte[] Encrypt(byte[] toEncrypt, byte[] key)
    {
        using (var tdes = new TripleDESCryptoServiceProvider
        {
            Key = key,
            IV = new byte[8] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
            Mode = CipherMode.CBC,
            Padding = PaddingMode.None
        })
        {
            var cTransform = tdes.CreateEncryptor();

            return cTransform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
        }
    }
}

One of my example inputs and expected outs are

  • Unencoded Pin: 71548715
  • Decrypted Working Key: A7E5A86DB6F41FBA0DE99DE5BC3246ABA7E5A86DB6F41FBA
  • Expected Encryption Result: C097280EC13B486AE5DA57DB8F779184
  • Result Obtained by Above : C909165718FCE9A432AD432E7A104DCD

Solution

  • The C/C++ code performs an encryption with TripleDES in CBC mode without padding. The input parameters are the hex encoded key (argv[1]) and the EAN/PIN (argv[2]). The EAN/PIN is preceded by an 8 bytes value before encryption, whose first 7 bytes were randomly generated with RAND_bytes() and whose 8th byte is a checksum byte generated with chksum(). A zero IV is applied as IV.

    The C# code does the same! Of course, because of the first random 7 bytes, this cannot be verified by just comparing the ciphertexts as you did, but by comparing the ciphertexts using the identical leading 7 bytes in both codes.

    The leading 7 bytes for this test can be determined beforehand by decrypting the posted expected ciphertext using the posted key and a zero IV with a tool or other code. This decryption returns hex encoded the value 51174b043d6274a63731353438373135 (performed e.g. with http://tripledes.online-domain-tools.com/), of which the last 8 bytes are ASCII decoded 71548715, thus corresponding to the posted EAN/PIN. The first 7 bytes are hex encoded 51174b043d6274.

    If for the test of the C# code in EncodePIN() the line

    var bytes = GenerateRandomBytes();
    

    is replaced by

    var bytes = HexStringBytesConverter.ConvertHexStringToByteArray("51174b043d6274");
    

    the call

    Console.WriteLine(PINEncoding.EncodePIN("71548715", "A7E5A86DB6F41FBA0DE99DE5BC3246ABA7E5A86DB6F41FBA"));
    

    returns

    C097280EC13B486AE5DA57DB8F779184
    

    in accordance with the expected ciphertext, proving that the C/C++ and C# code are functionally identical.

    Note that the C/C++ code actually has a bit more functionality under the hood, e.g. checking the key (s. DES_set_key_checked), which however has no effect on the result if the key is valid (odd parity, not weak or semi weak).