Click here to Skip to main content
15,895,606 members
Articles / Desktop Programming / MFC
Article

Encryption using the Win32 Crypto API

Rate me:
Please Sign up or sign in to vote.
4.24/5 (19 votes)
8 Sep 20054 min read 405.2K   18.8K   85   60
How to encrypt using the Win32 Crypto API.

Introduction

Using information technology today gets more and more sophisticated. The information that is being transferred and stored are often classified material of some kind and it is often necessary to prevent it from being read by third parties. The keyword for this particular problem is (both logical and physical) security. A part of the security aspect is encryption. Often people think that security is “just” something you plug in afterwards – it is definitely not!

A few rules of thumb when encryption is going to be included in the final product can be summarised into the following basics:

  1. Do not base the encryption on the algorithm itself.
  2. Make the algorithm public and the key private.

RSA Encryption

One of the most well known encryptions today is the RSA encryption. This form for encryption uses asymmetric keys. This means that you cannot evaluate the second key if you have the first one and vice versa.

The RSA encryption is a public-key crypto system, which uses two algorithms (E, D), one for encryption and one for decryption. You have a key pair containing: a secret key (sk) and a public key (pk).

m = D sk (E pk (m))
m = cd mod n AND c = me mod n <=>
m = (me mod n)d mod n

CBC Mode

The RSA encryption is typically using CBC mode (Cipher Block Chaining mode) when encrypting. This means the text that is being encrypted is divided into blocks. Each block is chained together, using the XOR operator, and then encrypted.

Sample screenshot

When using the CBC mode of operation it is required that all blocks have the same size. If the last block has a size less than the others then it will be necessary to use padding. The padding will then fill the block until it has the same size as the others. Formally the CBC mode operates in the following way, where we start with y0, which is a 64-bit initialisation vector:

y i = e k (y i-1 XOR x i), i >= 1

Doing the decryption, the entire operation is just reversed. This means that the cipher blocks are decrypted and then XORed. In this way we will end up with the clear text again.

x i = y i-1 XOR (d k (y i)) , i >= 1

Using the code

The Win32 Crypto API does provide some functionality, which can be used to perform an encryption. The advantage using the Crypto API is that you don’t need to use/find any third party cryptographic provider and figure out how it is installed and used. Simply use the one that sticks to the operating system. The disadvantage is clear – it is not simple to change to another operation system.

Sample screenshot

Before any functionality can be used it is necessary to create a context. This context is used several times when doing the encryption, so it is important that the handle is kept open until the encryption is done.

if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0))
{
    dwResult = GetLastError();
    if (dwResult == NTE_BAD_KEYSET)
    {
        if (!CryptAcquireContext(&hProv, 
            NULL, MS_DEF_PROV, PROV_RSA_FULL, 
            CRYPT_NEWKEYSET))
        {
            dwResult = GetLastError();
            MessageBox("Error [0x%x]: CryptAcquireContext() failed.", 
                       "Information", MB_OK);
            return;
        }
    }
    else {
        dwResult = GetLastError();
        return;
    }
}

When we get the context, we need to get a (session) key, which we are going to use when doing the encryption. The key can be created from scratch or it can be imported from a file. In the following code snip, the pbBlob is (if not NULL) a binary that contains the key, which is fetched from a file.

if (pbBlob) {
    if (!CryptImportKey(hProv, pbBlob, cbBlob, 0, 0, &hSessionKey))
    {
        dwResult = GetLastError();
        MessageBox("Error [0x%x]: CryptImportKey() failed.", 
                                      "Information", MB_OK);
        return;
    }
}
else { 
    if (!CryptImportKey(hProv, PrivateKeyWithExponentOfOne, 
        sizeof(PrivateKeyWithExponentOfOne), 0, 0, &hKey))
    {
        dwResult = GetLastError();
        MessageBox("Error CryptImportKey() failed.", 
                              "Information", MB_OK);
        return;
    }
    if (!CryptGenKey(hProv, CALG_RC4, CRYPT_EXPORTABLE, &hSessionKey))
    {
        dwResult = GetLastError();
        MessageBox("Error CryptGenKey() failed.", 
                           "Information", MB_OK);
        return;
    }
}

It is always a good idea to use the PKCS#7 standard, when storing the key. Please note that the project enclosed with this article does not use it.

After the key is imported or generated, it is now time to perform the encryption or decryption. The encryption and decryption depends on a session key, which is based on the key we just imported or generated previously.

void Encrypt()
{
    unsigned long length = m_clear.GetLength() +1;
    unsigned char * cipherBlock = (unsigned char*)malloc(length);
    memset(cipherBlock, 0, length);
    memcpy(cipherBlock, m_clear, length -1); 

    if (!CryptEncrypt(hSessionKey, 0, TRUE, 0, cipherBlock, &length, length))
    {
        dwResult = GetLastError();
        MessageBox("Error CryptEncrypt() failed.", "Information", MB_OK);
        return;
    }

    m_cipher = cipherBlock;
    m_clear = "";
    free(cipherBlock);
}

The decryption does not vary much from the encryption. Like with the encryption it is done with just one invocation and the cipher text is then decrypted.

void Decrypt()
{
    unsigned long length = m_cipher.GetLength() +1;
    unsigned char * cipherBlock = (unsigned char*)malloc(length);
    memset(cipherBlock, 0, length);
    memcpy(cipherBlock, m_cipher, length -1); 

    if (!CryptDecrypt(hSessionKey, 0, TRUE, 0, cipherBlock, &length))
    {
        dwResult = GetLastError();
        MessageBox("Error CryptDecrypt() failed.", 
                            "Information", MB_OK);
        return;
    }

    m_clear = cipherBlock;
    m_cipher = "";

    free(cipherBlock);
}

Points of interest

The clear text / data is typically a string containing any text. Before performing the encryption it is a good idea to copy the data into an unsigned char pointer to avoid future problems with casts when the encryption is performed.

Finally, when using the Win32 Crypto API, please notice that it might not necessary compile as is. This is because a pre-processor definition is missing in the project.

#define _WIN32_WINNT 0x0400

When defining the above globally to the project, it will be possible to compile code that is using the Crypto API. My suggestion is to place the definition in the StdAfx.h file.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Technical Lead
Denmark Denmark
I'm a technical lead and software architect, who holds a master's degree from Aarhus University, Denmark. I have commercial experience with IT and software engineering since mid-nineties and my professionalism has been confirmed by IEEE with my elevation to Senior Member.


Active help channel - Codementor
https://www.codementor.io/jessn/profile


Deprecated help channel - Support & help
https://groups.google.com/forum/#!forum/nielsen-tools-support

Comments and Discussions

 
Questionsafe? Pin
T1TAN9-Sep-05 0:08
T1TAN9-Sep-05 0:08 
AnswerRe: safe? Pin
Jessn9-Sep-05 0:54
Jessn9-Sep-05 0:54 
GeneralRe: safe? Pin
T1TAN9-Sep-05 5:33
T1TAN9-Sep-05 5:33 
GeneralRe: safe? Pin
Jessn10-Sep-05 2:23
Jessn10-Sep-05 2:23 
GeneralRe: safe? Pin
T1TAN11-Sep-05 23:14
T1TAN11-Sep-05 23:14 
GeneralRe: safe? Pin
Jessn13-Sep-05 10:42
Jessn13-Sep-05 10:42 
GeneralRe: safe? Pin
T1TAN13-Sep-05 23:54
T1TAN13-Sep-05 23:54 
GeneralRe: safe? Pin
Jessn30-Sep-05 7:11
Jessn30-Sep-05 7:11 
It is correct that the key can't be replaced and of course you can't decrypt the data without the key. This would be a direct contradiction of the cryptographic theories.

First of all encryption is not an out of the box operation. It uses some heavy mathematical operations, which take time. This should indeed be considered when doing the design.

If you are going to verify the data sent to you, I will suggest that you use *cryptographic* hashing instead. This means when you get the data from the computer, calculate the hash value and convert it to your serial number i.e. in a numerical format. It is important that you do not use an ordinary hashing algorithm such as the mathematical modulus operator - you must use a cryptographic hashing algorithm! Hashing is much faster than doing an encryption and it does not require a key. A rule of thumb; the hashing is exactly as secure as the crypto-system it is based on. (see one of my articles about this)

Of course the design depends on what kind of data that will be sent to you and how much. If the end-user has to enter the data each time, it is obvious that it will be annoying. Therefore be careful when you consider what data you are making the hashing on behalf of - often, if possible, use some (unique) data from the operating system or the computer itself.

Finally if you really have to use encryption, why don't you just store the key together with your system i.e. in a database? If the end-user f*** up the database, it will definately be the user's own fault. Again when you store the key in the database it is a good idea to use a PKCS#7 structure.


--
Jess Nielsen
Systems Developer
C++ Programmer

-- modified at 10:33 Sunday 2nd October, 2005
GeneralRe: safe? Pin
T1TAN2-Oct-05 22:11
T1TAN2-Oct-05 22:11 
GeneralRe: safe? Pin
Jessn15-Oct-05 6:18
Jessn15-Oct-05 6:18 
GeneralRe: safe? Pin
T1TAN15-Oct-05 14:43
T1TAN15-Oct-05 14:43 
GeneralRe: safe? Pin
Jessn17-Oct-05 18:28
Jessn17-Oct-05 18:28 
GeneralRe: safe? [modified] Pin
Jessn28-Oct-07 21:57
Jessn28-Oct-07 21:57 
GeneralRe: safe? Pin
T1TAN28-Oct-07 22:59
T1TAN28-Oct-07 22:59 
GeneralIt traps Pin
Alexander D. Alexeev8-Sep-05 23:19
Alexander D. Alexeev8-Sep-05 23:19 
GeneralRe: It traps Pin
Jessn8-Sep-05 23:42
Jessn8-Sep-05 23:42 
GeneralA picky comment Pin
fwsouthern8-Sep-05 17:13
fwsouthern8-Sep-05 17:13 
GeneralRe: A picky comment Pin
Jessn8-Sep-05 23:25
Jessn8-Sep-05 23:25 
GeneralRe: A picky comment Pin
T1TAN8-Sep-05 23:50
T1TAN8-Sep-05 23:50 
Generalkey.txt Pin
Zalosny8-Sep-05 11:54
Zalosny8-Sep-05 11:54 
GeneralRe: key.txt Pin
Jessn8-Sep-05 23:24
Jessn8-Sep-05 23:24 
GeneralRe: key.txt Pin
Jessn8-Sep-05 23:44
Jessn8-Sep-05 23:44 
GeneralRe: key.txt Pin
Zalosny9-Sep-05 0:13
Zalosny9-Sep-05 0:13 
GeneralRe: key.txt Pin
Jessn9-Sep-05 0:44
Jessn9-Sep-05 0:44 
GeneralRe: key.txt Pin
Zalosny9-Sep-05 7:20
Zalosny9-Sep-05 7:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.