使用crypto api的签名和验证签名源代码
#include "stdafx.h"
//--------------------------------------------------------------------
// 数字签名以及认证
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);
void main(void)
{
//-------------------------------------------------------------
// Declare and initialize variables.
HCRYPTPROV hProv;
BYTE *pbBuffer= (BYTE *)"The data that is to be hashed and signed.";//被签名的数据
DWORD dwBufferLen = strlen((char *)pbBuffer)+1;
HCRYPTHASH hHash;
HCRYPTKEY hKey;
BYTE *pbKeyBlob; //签名者得公钥数据
BYTE *pbSignature; //数字签名
DWORD dwSigLen;
DWORD dwBlobLen;
LPTSTR szDescription = L"Test Data Description";
//--------------------------------------------------------------------
// 获得CSP句柄,密钥容器名为登陆用户名
if(CryptAcquireContext(
&hProv,
NULL,
NULL,
PROV_RSA_FULL,
0))
{
printf("CSP context acquired.\n");
}
else //密钥容器不存在创建之
{
if(CryptAcquireContext(
&hProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET))
{
printf("A new key container has been created.\n");
}
else
{
MyHandleError("Error during CryptAcquireContext.");
}
}
//--------------------------------------------------------------------
// 从密钥容器中取数字签名用的密钥
if(CryptGetUserKey(
hProv,
AT_SIGNATURE,
&hKey))
{
printf("The signature key has been acquired. \n");
}
else
{
if(GetLastError() == NTE_NO_KEY) //密钥容器里不存在signature key pair创建之
{
if(CryptGenKey(
hProv, //CSP句柄
AT_SIGNATURE, //创建的密钥对类型为signature key pair
0, //key类型,这里用默认值
&hKey)) //创建成功返回新创建的密钥对的句柄
{
printf("Created a signature key pair.\n");
}
else
{
MyHandleError("Error occurred creating a signature key.\n");
}
}
else
{
MyHandleError("Error during CryptGetUserKey for signkey.");
}
}
//--------------------------------------------------------------------
// 因为接收消息者要验证数字签名,所以要导出公钥给接收者。
if(CryptExportKey(
hKey,
NULL,
PUBLICKEYBLOB,
0,
NULL,
&dwBlobLen)) //得到公钥的大小
{
printf("Size of the BLOB for the public key determined. \n");
}
else
{
MyHandleError("Error computing BLOB length.");
}
//--------------------------------------------------------------------
// 为存储公钥的缓冲区分配内存。
if(pbKeyBlob = (BYTE*)malloc(dwBlobLen))
{
printf("Memory has been allocated for the BLOB. \n");
}
else
{
MyHandleError("Out of memory. \n");
}
//--------------------------------------------------------------------
// 真正导出公钥数据
if(CryptExportKey(
hKey,
NULL,
PUBLICKEYBLOB,
0,
pbKeyBlob, //这个数据可以存入文件,发送给接收者。一般被存入数字证书
&dwBlobLen))
{
printf("Contents have been written to the BLOB. \n");
}
else
{
MyHandleError("Error during CryptExportKey.");
}
//--------------------------------------------------------------------
// 创建hash对象
if(CryptCreateHash(
hProv,
CALG_MD5,
0,
0,
&hHash))
{
printf("Hash object created. \n");
}
else
{
MyHandleError("Error during CryptCreateHash.");
}
//--------------------------------------------------------------------
// 对数据进行hash运算
if(CryptHashData(
hHash,
pbBuffer,
dwBufferLen,
0))
{
printf("The data buffer has been hashed.\n");
}
else
{
MyHandleError("Error during CryptHashData.");
}
//--------------------------------------------------------------------
// 使用signature key pair的私钥对hash数据签名
dwSigLen= 0;
if(CryptSignHash(
hHash,
AT_SIGNATURE,
szDescription,
0,
NULL,
&dwSigLen)) //得到数字签名大小
{
printf("Signature length %d found.\n",dwSigLen);
}
else
{
MyHandleError("Error during CryptSignHash.");
}
//--------------------------------------------------------------------
// 为数字签名缓冲区分配内存
if(pbSignature = (BYTE *)malloc(dwSigLen))
{
printf("Memory allocated for the signature.\n");
}
else
{
MyHandleError("Out of memory.");
}
//--------------------------------------------------------------------
// 得到数字签名
if(CryptSignHash(
hHash,
AT_SIGNATURE,
szDescription,
0,
pbSignature, //这里将返回数字签名,同被签名的数据一起发送给接收方
&dwSigLen))
{
printf("pbSignature is the hash signature.\n");
}
else
{
MyHandleError("Error during CryptSignHash.");
}
//--------------------------------------------------------------------
// Destroy the hash object.
if(hHash)
CryptDestroyHash(hHash);
printf("The hash object has been destroyed.\n");
printf("The signing phase of this program is completed.\n\n");
//--------------------------------------------------------------------
// 下面的代码应该是接收者使用的,这里为了说明方便就把它放在一个文件里了。
// pbBuffer, pbSignature, szDescription, pbKeyBlob, 还有他们的长度
// 在这里直接使用了,应该是接收者从文件或其他地方读取的。
// pbBuffer 里保存的是被签名的数据,所以认证时的内容必须跟签名时的一样
// 这里使用的CSP句柄也没有重新创建
// Point szDescription at the text describing the data being
// signed. This is the same description text that was originally
// passed to CryptSignHash.
//--------------------------------------------------------------------
// 把签名者的公钥数据导入生成公钥句柄
HCRYPTKEY hPubKey;
if(CryptImportKey(
hProv,
pbKeyBlob,
dwBlobLen,
0,
0,
&hPubKey))
{
printf("The key has been imported.\n");
}
else
{
MyHandleError("Public key import failed.");
}
//--------------------------------------------------------------------
// 创建哈希对象
if(CryptCreateHash(
hProv,
CALG_MD5,
0,
0,
&hHash))
{
printf("The hash object has been recreated. \n");
}
else
{
MyHandleError("Error during CryptCreateHash.");
}
//--------------------------------------------------------------------
// 跟生成时一样对数据进行hash运算
if(CryptHashData(
hHash,
pbBuffer,
dwBufferLen,
0))
{
printf("The new has been created.\n");
}
else
{
MyHandleError("Error during CryptHashData.");
}
//--------------------------------------------------------------------
// 验证数字签名
if(CryptVerifySignature(
hHash,
pbSignature, //数字签名数据
dwSigLen,
hPubKey, //签名者的公钥
szDescription,
0))
{
printf("The signature has been verified.\n");
}
else
{
printf("Signature not validated!\n");
}
//--------------------------------------------------------------------
// Free memory to be used to store signature.
if(pbSignature)
free(pbSignature);
if(pbKeyBlob)
free(pbKeyBlob);
//--------------------------------------------------------------------
// Destroy the hash object.
if(hHash)
CryptDestroyHash(hHash);
//--------------------------------------------------------------------
// Release the provider handle.
if(hProv)
CryptReleaseContext(hProv, 0);
} // End of main
//--------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function, to print an error message to the standard error
// (stderr) file and exit the program.
// For most applications, replace this function with one
// that does more extensive error reporting.
void MyHandleError(char *s)
{
fprintf(stderr,"An error occurred in running the program. \n");
fprintf(stderr,"%s\n",s);
fprintf(stderr, "Error number %x.\n", GetLastError());
fprintf(stderr, "Program terminating. \n");
exit(1);
} // End of MyHandleError
// #include < stdio.h >
// #include < windows.h >
// #include < wincrypt.h >
// #define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
// #define KEYLENGTH 0x00800000
// void HandleError(char *s);
//
// //--------------------------------------------------------------------
// // These additional #define statements are required.
// #define ENCRYPT_ALGORITHM CALG_RC4
// #define ENCRYPT_BLOCK_SIZE 8
//
// // Declare the function EncryptFile. The function definition
// // follows main.
//
// BOOL EncryptFile(
// PCHAR szSource,
// PCHAR szDestination,
// PCHAR szPassword);
// BOOL DecryptFile(
// PCHAR szSource,
// PCHAR szDestination,
// PCHAR szPassword);
//
// //--------------------------------------------------------------------
// // Begin main.
//
// void main(void)
// {
// CHAR szSource[100];
// CHAR szDestination[100];
// CHAR szPassword[100];
// int way[1];
// printf("please choose encryption of 1 or decryption of 2\n\n");
// scanf("%d",way);
//
// if (way[0] == 1)
// {
// printf("Encrypt a file. \n\n");
// printf("Enter the name of the file to be encrypted: ");
// scanf("%s",szSource);
// printf("Enter the name of the output file: ");
// scanf("%s",szDestination);
// printf("Enter the password:");
// scanf("%s",szPassword);
// if(EncryptFile(szSource, szDestination, szPassword))
// {
// printf("Encryption of the file %s was a success. \n", szSource);
// printf("The encrypted data is in file %s.\n",szDestination);
// }
// else
// {
// HandleError("Error encrypting file!");
// }
// }else{
// printf("Decrypt a file. \n\n");
// printf("Enter the name of the file to be decrypted: ");
// scanf("%s",szSource);
// printf("Enter the name of the output file: ");
// scanf("%s",szDestination);
// printf("Enter the password:");
// scanf("%s",szPassword);
// if(DecryptFile(szSource, szDestination, szPassword))
// {
// printf("Decryption of the file %s was a success. \n", szSource);
// printf("The decrypted data is in file %s.\n",szDestination);
// }
// else
// {
// HandleError("Error decrypting file!");
// }
// }
//
//
// } // End of main
//
//
// //--------------------------------------------------------------------
// // Code for the function EncryptFile called by main.
//
// static BOOL EncryptFile(
// PCHAR szSource,
// PCHAR szDestination,
// PCHAR szPassword)
// //--------------------------------------------------------------------
// // Parameters passed are:
// // szSource, the name of the input, a plaintext file.
// // szDestination, the name of the output, an encrypted file to be
// // created.
// // szPassword, the password.
// {
// //--------------------------------------------------------------------
// // Declare and initialize local variables.
//
// FILE *hSource;
// FILE *hDestination;
//
// HCRYPTPROV hCryptProv;
// HCRYPTKEY hKey;
// HCRYPTHASH hHash;
//
// PBYTE pbBuffer;
// DWORD dwBlockLen;
// DWORD dwBufferLen;
// DWORD dwCount;
//
// //--------------------------------------------------------------------
// // Open source file.
// if(hSource = fopen(szSource,"rb"))
// {
// printf("The source plaintext file, %s, is open. \n", szSource);
// }
// else
// {
// HandleError("Error opening source plaintext file!");
// }
//
// //--------------------------------------------------------------------
// // Open destination file.
// if(hDestination = fopen(szDestination,"wb"))
// {
// printf("Destination file %s is open. \n", szDestination);
// }
// else
// {
// HandleError("Error opening destination ciphertext file!");
// }
//
// //以下获得一个CSP句柄
// if(CryptAcquireContext(
// &hCryptProv,
// NULL, //NULL表示使用默认密钥容器,默认密钥容器名
// //为用户登陆名
// NULL,
// PROV_RSA_FULL,
// 0))
// {
// printf("A cryptographic provider has been acquired. \n");
// }
// else
// {
// if(CryptAcquireContext(
// &hCryptProv,
// NULL,
// NULL,
// PROV_RSA_FULL,
// CRYPT_NEWKEYSET))//创建密钥容器
// {
// //创建密钥容器成功,并得到CSP句柄
// printf("A new key container has been created.\n");
// }
// else
// {
// HandleError("Could not create a new key container.\n");
// }
//
// }
//
// //--------------------------------------------------------------------
// // 创建一个会话密钥(session key)
// // 会话密钥也叫对称密钥,用于对称加密算法。
// // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
// // CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
//
// //--------------------------------------------------------------------
// // Create a hash object.
// if(CryptCreateHash(
// hCryptProv,
// CALG_MD5,
// 0,
// 0,
// &hHash))
// {
// printf("A hash object has been created. \n");
// }
// else
// {
// HandleError("Error during CryptCreateHash!\n");
// }
//
// //--------------------------------------------------------------------
// // 用输入的密码产生一个散列
// if(CryptHashData(
// hHash,
// (BYTE *)szPassword,
// strlen(szPassword),
// 0))
// {
// printf("The password has been added to the hash. \n");
// }
// else
// {
// HandleError("Error during CryptHashData. \n");
// }
//
// //--------------------------------------------------------------------
// // 通过散列生成会话密钥
// if(CryptDeriveKey(
// hCryptProv,
// ENCRYPT_ALGORITHM,
// hHash,
// KEYLENGTH,
// &hKey))
// {
// printf("An encryption key is derived from the password hash. \n");
// }
// else
// {
// HandleError("Error during CryptDeriveKey!\n");
// }
// //--------------------------------------------------------------------
// // Destroy the hash object.
//
// CryptDestroyHash(hHash);
// hHash = NULL;
//
// //--------------------------------------------------------------------
// // The session key is now ready.
//
// //--------------------------------------------------------------------
// // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
// // 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
// // 数据长度。
//
// dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
//
// //--------------------------------------------------------------------
// // Determine the block size. If a block cipher is used,
// // it must have room for an extra block.
//
// if(ENCRYPT_BLOCK_SIZE > 1)
// dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
// else
// dwBufferLen = dwBlockLen;
//
// //--------------------------------------------------------------------
// // Allocate memory.
// if(pbBuffer = (BYTE *)malloc(dwBufferLen))
// {
// printf("Memory has been allocated for the buffer. \n");
// }
// else
// {
// HandleError("Out of memory. \n");
// }
// //--------------------------------------------------------------------
// // In a do loop, encrypt the source file and write to the source file.
//
// do
// {
//
// //--------------------------------------------------------------------
// // Read up to dwBlockLen bytes from the source file.
// dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
// if(ferror(hSource))
// {
// HandleError("Error reading plaintext!\n");
// }
//
// //--------------------------------------------------------------------
// // 加密数据
// if(!CryptEncrypt(
// hKey, //密钥
// 0, //如果数据同时进行散列和加密,这里传入一个
// //散列对象
// feof(hSource), //如果是最后一个被加密的块,输入TRUE.如果不是输.
// //入FALSE这里通过判断是否到文件尾来决定是否为
// //最后一块。
// 0, //保留
// pbBuffer, //输入被加密数据,输出加密后的数据
// &dwCount, //输入被加密数据实际长度,输出加密后数据长度
// dwBufferLen
// )) //pbBuffer的大小。
// {
// HandleError("Error during CryptEncrypt. \n");
// }
//
// //--------------------------------------------------------------------
// // Write data to the destination file.
//
// fwrite(pbBuffer, 1, dwCount, hDestination);
// if(ferror(hDestination))
// {
// HandleError("Error writing ciphertext.");
// }
//
// }
// while(!feof(hSource));
// //--------------------------------------------------------------------
// // End the do loop when the last block of the source file has been
// // read, encrypted, and written to the destination file.
//
// //--------------------------------------------------------------------
// // Close files.
//
// if(hSource)
// fclose(hSource);
// if(hDestination)
// fclose(hDestination);
//
// //--------------------------------------------------------------------
// // Free memory.
//
// if(pbBuffer)
// free(pbBuffer);
//
// //--------------------------------------------------------------------
// // Destroy session key.
//
// if(hKey)
// CryptDestroyKey(hKey);
//
// //--------------------------------------------------------------------
// // Destroy hash object.
//
// if(hHash)
// CryptDestroyHash(hHash);
//
// //--------------------------------------------------------------------
// // Release provider handle.
//
// if(hCryptProv)
// CryptReleaseContext(hCryptProv, 0);
// return(TRUE);
// } // End of Encryptfile
//
// //--------------------------------------------------------------------
// // This example uses the function HandleError, a simple error
// // handling function, to print an error message to the standard error
// // (stderr) file and exit the program.
// // For most applications, replace this function with one
// // that does more extensive error reporting.
//
// void HandleError(char *s)
// {
// fprintf(stderr,"An error occurred in running the program. \n");
// fprintf(stderr,"%s\n",s);
// fprintf(stderr, "Error number %x.\n", GetLastError());
// fprintf(stderr, "Program terminating. \n");
// exit(1);
// } // End of HandleError
//
//
// static BOOL DecryptFile(
// PCHAR szSource,
// PCHAR szDestination,
// PCHAR szPassword)
// //--------------------------------------------------------------------
// // Parameters passed are:
// // szSource, the name of the input, a plaintext file.
// // szDestination, the name of the output, an encrypted file to be
// // created.
// // szPassword, the password.
// {
// //--------------------------------------------------------------------
// // Declare and initialize local variables.
//
// FILE *hSource;
// FILE *hDestination;
//
// HCRYPTPROV hCryptProv;
// HCRYPTKEY hKey;
// HCRYPTHASH hHash;
//
// PBYTE pbBuffer;
// DWORD dwBlockLen;
// DWORD dwBufferLen;
// DWORD dwCount;
//
// //--------------------------------------------------------------------
// // Open source file.
// if(hSource = fopen(szSource,"rb"))
// {
// printf("The source plaintext file, %s, is open. \n", szSource);
// }
// else
// {
// HandleError("Error opening source plaintext file!");
// }
//
// //--------------------------------------------------------------------
// // Open destination file.
// if(hDestination = fopen(szDestination,"wb"))
// {
// printf("Destination file %s is open. \n", szDestination);
// }
// else
// {
// HandleError("Error opening destination ciphertext file!");
// }
//
// //以下获得一个CSP句柄
// if(CryptAcquireContext(
// &hCryptProv,
// NULL, //NULL表示使用默认密钥容器,默认密钥容器名
// //为用户登陆名
// NULL,
// PROV_RSA_FULL,
// 0))
// {
// printf("A cryptographic provider has been acquired. \n");
// }
// else
// {
// if(CryptAcquireContext(
// &hCryptProv,
// NULL,
// NULL,
// PROV_RSA_FULL,
// CRYPT_NEWKEYSET))//创建密钥容器
// {
// //创建密钥容器成功,并得到CSP句柄
// printf("A new key container has been created.\n");
// }
// else
// {
// HandleError("Could not create a new key container.\n");
// }
//
// }
//
// //--------------------------------------------------------------------
// // 创建一个会话密钥(session key)
// // 会话密钥也叫对称密钥,用于对称加密算法。
// // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
// // CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
//
// //--------------------------------------------------------------------
// // Create a hash object.
// if(CryptCreateHash(
// hCryptProv,
// CALG_MD5,
// 0,
// 0,
// &hHash))
// {
// printf("A hash object has been created. \n");
// }
// else
// {
// HandleError("Error during CryptCreateHash!\n");
// }
//
// //--------------------------------------------------------------------
// // 用输入的密码产生一个散列
// if(CryptHashData(
// hHash,
// (BYTE *)szPassword,
// strlen(szPassword),
// 0))
// {
// printf("The password has been added to the hash. \n");
// }
// else
// {
// HandleError("Error during CryptHashData. \n");
// }
//
// //--------------------------------------------------------------------
// // 通过散列生成会话密钥
// if(CryptDeriveKey(
// hCryptProv,
// ENCRYPT_ALGORITHM,
// hHash,
// KEYLENGTH,
// &hKey))
// {
// printf("An encryption key is derived from the password hash. \n");
// }
// else
// {
// HandleError("Error during CryptDeriveKey!\n");
// }
// //--------------------------------------------------------------------
// // Destroy the hash object.
//
// CryptDestroyHash(hHash);
// hHash = NULL;
//
// //--------------------------------------------------------------------
// // The session key is now ready.
//
// //--------------------------------------------------------------------
// // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
// // 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
// // 数据长度。
//
// dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
//
// //--------------------------------------------------------------------
// // Determine the block size. If a block cipher is used,
// // it must have room for an extra block.
//
// if(ENCRYPT_BLOCK_SIZE > 1)
// dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
// else
// dwBufferLen = dwBlockLen;
//
// //--------------------------------------------------------------------
// // Allocate memory.
// if(pbBuffer = (BYTE *)malloc(dwBufferLen))
// {
// printf("Memory has been allocated for the buffer. \n");
// }
// else
// {
// HandleError("Out of memory. \n");
// }
// //--------------------------------------------------------------------
// // In a do loop, encrypt the source file and write to the source file.
//
// do
// {
//
// //--------------------------------------------------------------------
// // Read up to dwBlockLen bytes from the source file.
// dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
// if(ferror(hSource))
// {
// HandleError("Error reading plaintext!\n");
// }
//
// //--------------------------------------------------------------------
// // 加密数据
// if(!CryptDecrypt(
// hKey, //密钥
// 0, //如果数据同时进行散列和加密,这里传入一个
// //散列对象
// feof(hSource), //如果是最后一个被加密的块,输入TRUE.如果不是输.
// //入FALSE这里通过判断是否到文件尾来决定是否为
// //最后一块。
// 0, //保留
// pbBuffer, //输入被加密数据,输出加密后的数据
// &dwCount //输入被加密数据实际长度,输出加密后数据长度
// //dwBufferLen
// )) //pbBuffer的大小。
// {
// HandleError("Error during CryptEncrypt. \n");
// }
//
// //--------------------------------------------------------------------
// // Write data to the destination file.
//
// fwrite(pbBuffer, 1, dwCount, hDestination);
// if(ferror(hDestination))
// {
// HandleError("Error writing ciphertext.");
// }
//
// }
// while(!feof(hSource));
// //--------------------------------------------------------------------
// // End the do loop when the last block of the source file has been
// // read, encrypted, and written to the destination file.
//
// //--------------------------------------------------------------------
// // Close files.
//
// if(hSource)
// fclose(hSource);
// if(hDestination)
// fclose(hDestination);
//
// //--------------------------------------------------------------------
// // Free memory.
//
// if(pbBuffer)
// free(pbBuffer);
//
// //--------------------------------------------------------------------
// // Destroy session key.
//
// if(hKey)
// CryptDestroyKey(hKey);
//
// //--------------------------------------------------------------------
// // Destroy hash object.
//
// if(hHash)
// CryptDestroyHash(hHash);
//
// //--------------------------------------------------------------------
// // Release provider handle.
//
// if(hCryptProv)
// CryptReleaseContext(hCryptProv, 0);
// return(TRUE);
// }