简体   繁体   中英

C# 3DES encryption to C decryption

I have created a C# assembly that does 3DES encryption/encryption and tested it. I now need to decrypt the data on a remote machine for an install. .NET is not guaranteed to be present when my native process runs, so I need to decrypt it using Win32 C++ methods. This is for a commercial applicaiton, so third party libraries are going to need to flexible with their licensing. I would prefer a simple example to get me started. Most of the examples I have found so far require importing session keys. I'm not using those. I am encrypting on machineA with .NET 2.0, and passing over to machineB where I will retrive the key and decrypt with native Win32 API's. Can anyone point me in the right direction with some examples?

I know I need to start with CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT) . However, the next step appears to be import key and it looks like it requires ( http://support.microsoft.com/kb/228786 ). Is this correct, or am I making this too difficult. I have a basic understanding of encryption. Thanks in advance!

Take a look to the following code:

#define TRIPLEDES_KEYSIZE 24
#define TRIPLEDES_BLOCKSIZE 8

...

BYTE key[TRIPLEDES_KEYSIZE] = { ... };

...

HCRYPTKEY hKey;

typedef struct
{
    BLOBHEADER hdr;
    DWORD cbKeySize;
    BYTE rgbKeyData [TRIPLEDES_KEYSIZE];
} KEYBLOB;

KEYBLOB keyBlob;
memset(&keyBlob, 0, sizeof(keyBlob));
keyBlob.cbKeySize = TRIPLEDES_KEYSIZE;
keyBlob.hdr.bType = PLAINTEXTKEYBLOB;
keyBlob.hdr.bVersion = CUR_BLOB_VERSION;
keyBlob.hdr.aiKeyAlg = CALG_3DES;
memcpy(keyBlob.rgbKeyData, key, TRIPLEDES_KEYSIZE);

BOOL res = CryptImportKey(hCryptProv, (const BYTE*)&keyBlob, sizeof(keyBlob), 0, 0, &hKey);
if (res)
{
    res = CryptSetKeyParam(hKey, KP_MODE, CRYPT_MODE_ECB, 0);

Please note you can use CRYPT_MODE_ECB or CRYPT_MODE_CBC in the call to the function CryptSetKeyParam with KP_MODE option depending on what you want to do. You can set an IV by for example the following code

res = CryptSetKeyParam(hKey, KP_IV, iv, 0);

which makes only sense in a CRYPT_MODE_CBC like mode.

Please note there is also a different 3DES mode ( CALG_3DES_112 ) working with only 112 Bit key (ie with two normal DES keys). You have to modify the code if you want to use this mode.

Edit:

You should write some classes in C++ to manage all things of the CryptoApi. It will save you a lot of headache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM