Microsoft CryptoAPI encryption technology (2)

Source: Internet
Author: User

Microsoft CryptoAPI encryption technology (2)
Author: cuick

Download sample source code

Last time we talked about the composition of Microsoft CryptoAPI and the use of session keys. Next we will take a look at the use of public/private key pairs, hash algorithms, digital signatures, and other technologies.

I. public key encryption technology

Public key encryption technology uses two different keys: public key and private key. The private key must be kept securely and cannot be known by outsiders. The public key can tell anyone as long as they need it. The Public Key is usually published in the form of a digital certificate.
Data Encrypted with one key in a public-private key pair can only be decrypted with another key in the key pair. That is to say, data encrypted with user a's public key can only be decrypted with a's private key. Similarly, data encrypted with a's private key can only be decrypted with a's public key.
If you use a private key to sign a message, you must use the corresponding public key to verify the validity of the signature.
Unfortunately, the efficiency of public key encryption technology is very low or even only 1‰ of symmetric encryption, so it is not suitable for encrypting a large amount of data. In fact, the public key encryption technology is generally used to encrypt session keys, and Data Encryption can be symmetric.
Let's go back to Microsoft CryptoAPI. We know that a CSP has a keystore that has one or more key containers. What are key containers? Generally, a key container has two pairs of public-private key pairs, one for session encryption, and the other for digital signature, that is, key exchange key pair and signature key pair.

How can we get these key pairs?

If (cryptgetuserkey (
Hcryptprov, // The CSP handle we have obtained
At_signature, // here you want to get the signature key pair
& Hkey) // return the key handle.
{
Printf ("A signature key is available./N ");
}
Else // An error occurred while retrieving the signature key pair.
{
Printf ("no signature key is available./N ");
If (getlasterror () = nte_no_key) // the signature key pair does not exist in the key container.
{
// Create signature key pair.
Printf ("the signature key does not exist./N ");
Printf ("create a signature key pair./N ");
If (cryptgenkey (
Hcryptprov, // CSP handle
At_signature, // The type of the created key pair is signature key pair
0, // key type. The default value is used here.
& Hkey) // returns the handle of the newly created key pair after the key pair is successfully created.
{
Printf ("created a signature key pair./N ");
}
Else
{
Printf ("error occurred creating a signature key./N ");
}
}
Else
{
Printf ("an error other than nte_no_key getting signature/key./N ");
}
} // End if

Replace at_signature with at_keyexchange to get the key exchange key pair.
Now we only get a handle. We need to store the key value in the disk or file so that it can be passed to the other party for decryption. Next let's look at an API for exporting keys.

BOOL WINAPI CryptExportKey(
HCRYPTKEY hKey,
HCRYPTKEY hExpKey,
DWORD dwBlobType,
DWORD dwFlags,
BYTE* pbData,
DWORD* pdwDataLen
);

Hkey:Key handle to Be Exported

Hexpkey:As we mentioned earlier, the efficiency of public key encryption technology is very low, so public key encryption technology
It is generally used to encrypt session keys. The entered key is used to encrypt the exported key.
. That is to say, the data of the exported key hkey goes through the key hexpkey
Encrypted. If it is null, the data is exported directly without encryption.

Dwblobtype:The type of the exported key, such as the Public Key or private key.

Dwflags:Flag Space

Pbdata:Save the exported data. If it is null, pdwdatalen returns the length of the exported data.

Pdwdatalen:Size of the input pbdata buffer and length of the exported data

The following example shows how to export a key.

If (cryptexportkey (
Hkey,
Null,
Publickeyblob, // export the Public Key
0,
Null,
& Dwbloblen) // return the key data length
{
Printf ("Size of the Blob for the Public Key determined./N ");
}
Else
{
Printf ("error computing blob length./N ");
Exit (1 );
}
//--------------------------------------------------------------------
// Allocate memory for the pbkeyblob.

If (pbkeyblob = (byte *) malloc (dwbloblen ))
{
Printf ("memory has been allocated for the Blob./N ");
}
Else
{
Printf ("out of memory./N ");
Exit (1 );
}
//--------------------------------------------------------------------
// Do the actual exporting into the key blob.

If (cryptexportkey (
Hkey,
Null,
Publickeyblob,
0,
Pbkeyblob, // return key data
& Dwbloblen) // The length of the exported key data
{
Printf ("contents have been written to the Blob./N ");
}
Else
{
Printf ("error exporting key./N ");
Exit (1 );
}

If you want to export a key encrypted with the public key encryption technology, you only need to pass the second parameter of the API into a key exchange key pair handle.

Now that you have exported the data, you must import the data.

Bool winapi cryptimportkey (
Hcryptprov hprov, // CSP handle
Byte * pbdata, // key data to be imported
DWORD dwdatalen, // Data Length
Hcryptkey hpubkey, // if the data is encrypted, enter the key handle for decryption.
DWORD dwflags, // flag
Hcryptkey * phkey // key handle returned after import
);

This API is relatively simple and will not be illustrated here. It will be seen in future examples.

Ii. Hash

Hash is simply to generate a unique, fixed-length data segment of any piece of data through a certain algorithm. It is also called abstract. To protect data a from accidental or intentional (malicious) changes, data a is often used to generate a hash data and send it together, the receiver can use the same hash algorithm to generate a new hash data with the received data a and compare it with the received hash data to verify whether data a is real and complete data.

The following API is used to create a hash object

Bool winapi cryptcreatehash (
Hcryptprov hprov, // CSP handle
Alg_id algid, // select the hash algorithm, such as calg_md5
Hcryptkey hkey, // useful for HMAC and Mac Algorithms
DWORD dwflags, // reserved, pass 0
Hcrypthash * phhash // return the hash handle
);

If (cryptcreatehash (
Hcryptprov,
Calg_md5,
0,
0,
& Hhash ))
{
Printf ("an empty hash object has been created./N ");
}
Else
{
Printf ("error during cryptbeginhash! /N ");
Exit (1 );
}

// Insert code that uses the hash object here.

//--------------------------------------------------------------------
// After processing, hhash must be released.

If (hhash)
Cryptdestroyhash (hhash); // release the handle

Now that we have got the hash object, let's try some data. Let's also try it out. Of course, this is not the one from Kazakhstan, Japan, and Han. It's not the one from Hao. Let's go !!
Oh !! Sorry, I forgot to introduce an API.

Bool winapi crypthashdata (
Hcrypthash hhash, // hash object
Byte * pbdata, // The data to be hashed
DWORD dwdatalen, // Data Length
DWORD dwflags // Microsoft's CSP value will be ignored
);

The following code:

BYTE *pbBuffer= (BYTE *)"The data that is to be hashed.";
DWORD dwBufferLen = strlen((char *)pbBuffer)+1;

if(CryptHashData(
hHash,
pbBuffer,
dwBufferLen,
0))
{
printf("The data buffer has been added to the hash./n");
}
else
{
printf("Error during CryptHashData./n");
exit(1);
}

Now, the content in pbbuffer has been hashed, and we need to export the hash data.

Byte * pbhash;
Byte * pbhashsize;
DWORD dwhashlen = sizeof (DWORD );
Dword I;

If (! (Pbhashsize = (byte *) malloc (dwhashlen )))
Myhandleerror ("memory allocation failed .");

// I have not figured out the following call: (why do I think it is unnecessary !!
If (cryptgethashparam (
Hhash,
Hp_hashsize, // size of the hash data
Pbhashsize, // buffer for outputting hash data size
& Dwhashlen, // buffer size
0 ))
{
// It worked. Free pbhashsize.
Free (pbhashsize );
}
Else
{
Myhandleerror ("cryptgethashparam failed to get size .");
}

If (cryptgethashparam (
Hhash,
Hp_hashval, // obtain the hash value
Null, // set to null, and return the required output buffer size in dwhashlen
& Dwhashlen, // output buffer size
0 ))
{
// It worked. Do nothing.
}
Else
{
Myhandleerror ("cryptgethashparam failed to get length .");
}

If (pbhash = (byte *) malloc (dwhashlen ))
{
// It worked. Do nothing.
}
Else
{
Myhandleerror ("Allocation failed .");
}

If (cryptgethashparam (
Hhash,
Hp_hashval, // obtain the hash value
Pbhash, // return hash data
& Dwhashlen, // hash Data Length
0 ))
{
// Print the hash value.
Printf ("the hash is :");
For (I = 0; I <dwhashlen; I ++)
{
Printf ("% 2.2x", pbhash [I]);
}
Printf ("/N ");
}
Else
{
Myhandleerror ("error during reading hash value .");
}
Free (pbhash );

Iii. Digital Signature

When publishing a plain text message, the recipient can use a digital signature to identify and verify the message sender. The signature does not change the information, but generates a digital signature string that is sent along with the information or separately.
A digital signature is a data segment encrypted with the sender's private key, and the receiver can decrypt the data segment only with the sender's public key. The statement is as follows:

There are two steps to generate a digital signature by using the message. First, hash the message to generate hash data. Then, use the private key of sign a to encrypt the hash data. The details are as follows:

Verify the message and digital signatures to be represented by a signature. First, hash the message as it is when it is generated to generate hash data. Then, it is verified by the public key, digital signatures, and the generated hash data of the signatory. The details are as follows:

Well, have you learned digital signatures? A lot of technical terms may sound awesome. They are actually very simple !! Hey.
The routine of the document will use almost all the content we mentioned above.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.