12,628,454 members (35,120 online)
alternative version

271.8K views
79 bookmarked
Posted

# Encryption using the Win32 Crypto API

, 8 Sep 2005
 Rate this:
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.

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.

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 (!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.

A list of licenses authors might use can be found here

## Share

 Architect Denmark
I'm an independent researcher and software architect, who holds a master's degree from Aarhus University, Denmark. I have more than 10 yrs of commercial experience. I am specialized in the C++ programming language, software architectures and crypto systems.

Support & help

## You may also be interested in...

 Pro Pro

 First PrevNext
 Encryption of Japanese characters uzayim3-Dec-12 11:09 uzayim 3-Dec-12 11:09
 Re: Encryption of Japanese characters Jessn5-Dec-12 9:17 Jessn 5-Dec-12 9:17
 Re: Encryption of Japanese characters uzayim5-Dec-12 10:03 uzayim 5-Dec-12 10:03
 Digital Certificate Daniel Ramnath23-Sep-12 8:49 Daniel Ramnath 23-Sep-12 8:49
 Hi, I am looking some good article, website or book which I can purchase for programming using windows digital certificate api. The MSDN doesn't seems to be of much help. Please advice me. Thank you. Regards, Daniel Ramnath. Jesus saves
 error in running the code Member 91308804-Jul-12 18:06 Member 9130880 4-Jul-12 18:06
 Re: error in running the code Jessn30-Jul-12 1:10 Jessn 30-Jul-12 1:10
 problem using the crypto api stylix0074-May-09 23:35 stylix007 4-May-09 23:35
 Have bugs been fixed int his sample code? Gonzalo Parra17-Jun-08 4:55 Gonzalo Parra 17-Jun-08 4:55
 Re: Have bugs been fixed int his sample code? Jessn17-Jun-08 5:56 Jessn 17-Jun-08 5:56
 Re: Have bugs been fixed int his sample code? Gonzalo Parra17-Jun-08 7:28 Gonzalo Parra 17-Jun-08 7:28
 Re: Have bugs been fixed int his sample code? Jessn17-Jun-08 9:44 Jessn 17-Jun-08 9:44
 Re: Have bugs been fixed int his sample code? Gonzalo Parra17-Jun-08 9:53 Gonzalo Parra 17-Jun-08 9:53
 Is it possible to restrict the output characters? Angus Comber15-Jun-08 12:16 Angus Comber 15-Jun-08 12:16
 Re: Is it possible to restrict the output characters? Jessn16-Jun-08 5:15 Jessn 16-Jun-08 5:15
 Re: problem nomicism22-Oct-07 1:15 nomicism 22-Oct-07 1:15
 Re: problem Jessn9-Dec-08 22:26 Jessn 9-Dec-08 22:26
 Origin of key data... achainard13-Oct-07 6:09 achainard 13-Oct-07 6:09
 the key in key.h Ray Cheng17-Apr-06 22:07 Ray Cheng 17-Apr-06 22:07
 Re: the key in key.h Jessn18-Apr-06 1:56 Jessn 18-Apr-06 1:56
 Re: the key in key.h Ray Cheng18-Apr-06 18:23 Ray Cheng 18-Apr-06 18:23
 Re: the key in key.h Jessn31-May-06 2:22 Jessn 31-May-06 2:22
 Re: the key in key.h Ray Cheng8-Jun-06 5:08 Ray Cheng 8-Jun-06 5:08
 Re: the key in key.h Jessn9-Jun-06 1:04 Jessn 9-Jun-06 1:04
 Building Secure Applications Jessn23-Jan-06 4:30 Jessn 23-Jan-06 4:30
 How is the code related to RSA? semmel7124-Nov-05 5:12 semmel71 24-Nov-05 5:12
 Re: How is the code related to RSA? Jessn24-Nov-05 5:35 Jessn 24-Nov-05 5:35
 some problems with the program bbrehm0417-Nov-05 22:58 bbrehm04 17-Nov-05 22:58
 Re: some problems with the program Jessn23-Nov-05 5:46 Jessn 23-Nov-05 5:46
 Re: some problems with the program bbrehm0423-Nov-05 21:34 bbrehm04 23-Nov-05 21:34
 Re: some problems with the program Jessn23-Nov-05 23:57 Jessn 23-Nov-05 23:57
 Re: some problems with the program bbrehm0424-Nov-05 16:44 bbrehm04 24-Nov-05 16:44
 Re: some problems with the program bbrehm0424-Nov-05 19:04 bbrehm04 24-Nov-05 19:04
 Re: some problems with the program Jessn25-Nov-05 0:30 Jessn 25-Nov-05 0:30
 safe? T1TAN9-Sep-05 1:08 T1TAN 9-Sep-05 1:08
 Re: safe? Jessn9-Sep-05 1:54 Jessn 9-Sep-05 1:54
 Re: safe? T1TAN9-Sep-05 6:33 T1TAN 9-Sep-05 6:33
 Re: safe? Jessn10-Sep-05 3:23 Jessn 10-Sep-05 3:23
 Re: safe? T1TAN12-Sep-05 0:14 T1TAN 12-Sep-05 0:14
 Re: safe? Jessn13-Sep-05 11:42 Jessn 13-Sep-05 11:42
 Re: safe? T1TAN14-Sep-05 0:54 T1TAN 14-Sep-05 0:54
 Re: safe? Jessn30-Sep-05 8:11 Jessn 30-Sep-05 8:11
 Re: safe? T1TAN2-Oct-05 23:11 T1TAN 2-Oct-05 23:11
 Re: safe? Jessn15-Oct-05 7:18 Jessn 15-Oct-05 7:18
 Re: safe? T1TAN15-Oct-05 15:43 T1TAN 15-Oct-05 15:43
 Re: safe? Jessn17-Oct-05 19:28 Jessn 17-Oct-05 19:28
 Re: safe? [modified] Jessn28-Oct-07 22:57 Jessn 28-Oct-07 22:57
 Re: safe? T1TAN28-Oct-07 23:59 T1TAN 28-Oct-07 23:59
 It traps Alexander D. Alexeev9-Sep-05 0:19 Alexander D. Alexeev 9-Sep-05 0:19
 Re: It traps Jessn9-Sep-05 0:42 Jessn 9-Sep-05 0:42
 A picky comment fwsouthern8-Sep-05 18:13 fwsouthern 8-Sep-05 18:13
 Last Visit: 31-Dec-99 19:00     Last Update: 6-Dec-16 18:45 Refresh 12 Next »