Search code examples
c#cconvertersdes3des

Des and 3Des with ecb in C# (from C)


I've this C code and I have to write it in C#.

How can I write these ecb des and 3des functions in C#?

/**
* Simple Single-Des Encryption procedure.
* Does not modify the input data.
* Encrypted result is returned in a separate buffer.
*
* @param pResult    (out) Result of the encrypted byte
* @param pData      (in)  One byte of input data
* @param pKey       (in)  The DES-key
*/

void DesEncrypt(void *pResult, const void *pData, KEY_1DES *pKey)
{
    memcpy(pResult, pData, 8);
    DES_key_schedule k;
    DES_set_key_unchecked((const_DES_cblock *)&pKey, &k);
    DES_ecb_encrypt((const_DES_cblock *)pData, (const_DES_cblock *)pResult, &k, DES_ENCRYPT);
}


/**
* Encrypts a byte using double length 3DES
*
* @param pResult    (out) Result of the decryption
* @param pData      (in)  One byte of input data
* @param pKey       (in)  The 3DES-key
*/

void DesEncrypt3Des(void *pResult, const void *pData, KEY_3DES *pKey)
{
    memcpy(pResult, pData, 8);
    //DES_set_key_checked()
    DES_key_schedule left;
    DES_set_key_unchecked((const_DES_cblock *)&pKey->left, &left);
    DES_key_schedule right;
    DES_set_key_unchecked((const_DES_cblock *)&pKey->right, &right);
    DES_ecb3_encrypt((const_DES_cblock *)pData, (const_DES_cblock *)pResult, &left, &right, &left, DES_ENCRYPT);
}

I'm asking this because there are a lot of way to do this and I have to be sure to use the same encrypt parameters.


Solution

  • Why don't you just use TripleDESCryptoServiceProvider from System.Security.Cryptography?

    public static string Encrypt(string data, string pKey)
    {
        TripleDESCryptoServiceProvider cryptor = new TripleDESCryptoServiceProvider();
        byte[] array = null;
        cryptor.Key = pKey;
        cryptor.Mode = CipherMode.ECB;
        ICryptoTransform encrypt = cryptor.CreateEncryptor();
        array = ASCIIEncoding.ASCII.GetBytes(data);
        string retVal = "";
        retVal = Convert.ToBase64String(encrypt.TransformFinalBlock(array, 0, array.Length));
        return retVal;
    }
    

    And for decryption use the same logic but instead call CreateDecryptor()