|
Microsoft CryptoAPI加密技术(一) 下载本文示例源代码 一、 加密方法: 二、 CryptoAPI CryptoAPI的编程模型同Windows系统的图形设备接口 GDI比较类似,其中加密服务提供者CSP等同于图形设备驱动程序 ,加密硬件(可选)等同于图形硬件,其上层的应用程序也类似,都不需要同设备驱动程序和硬件直接打交道。 CryptoAPI共有五部分组成:简单消息函数(Simplified Message Functions)、低层消息函数(Low-level Message Functions)、基本加密函数(Base Cryptographic Functions)、证书编解码函数(Certificate Encode/Decode Functions)和证书库管理函数(Certificate Store Functions)。其中前三者可用于对敏感信息进行加密或签名处理,可保证网络传输信心的私有性;后两者通过对证书的使用,可保证网络信息交流中的认证性。 三、 CSP 每个CSP都有一个名字和一个类型。每个CSP的名字是唯一的,这样便于CryptoAPI找到对应的CSP。目前已经有9种CSP类型,并且还在增长。下表列出出它们支持的密钥交换算法、签名算法、对称加密算法和Hash算法。
从图一可以看到,每个CSP有一个密钥库,密钥库用于存储密钥。而每个密钥库包括一个或多个密钥容器(Key Containers)。每个密钥容器中含属于一个特定用户的所有密钥对。每个密钥容器被赋予一个唯一的名字。在销毁密钥容器前CSP将永久保存每一个密钥容器,包括保存每个密钥容器中的公/私钥对(见图二)。
我们已经提过,每一个CSP都有一个名字和一个类型,并且名字保证唯一。所以可以通过名字和类型得到一个CSP。然而,要想加密肯定需要密钥,那么密钥放哪里呢?对了,就放在密钥容器。(有人会问,密码库有什么用?其实密钥库是在安装CSP的时候已经存在了,他与CSP是相对应的。)但是密钥容器并不是一开始就存在的,需要用户去创建。下面的代码实现以上功能(得到CSP即密码容器)。 if(CryptAcquireContext(&hCryptProv, // 返回CSP句柄UserName, // 密码容器名NULL, // NULL时使用默认CSP名(微软RSA Base Provider)PROV_RSA_FULL, // CSP类型0)) // Flag values{//以UserName为名的密钥容器存在,那么我们已经得到了CSP的句柄 printf("A crypto context with the %s key container \n", UserName); printf("has been acquired.\n\n");}else //如果密钥容器不存在,我们需要创建这个密钥容器{ if(CryptAcquireContext( &hCryptProv, UserName, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) //创建以UserName为名的密钥容器 {//创建密钥容器成功,并得到CSP句柄 printf("A new key container has been created.\n"); } else { HandleError("Could not create a new key container.\n"); }} // End of else
好了,我们已经创建了密钥容器,并得到了CSP的句柄。也可以这样理解,我们得到了一个CSP的句柄,并且它被绑定到以UserName为名的密钥容器上。嘿嘿……那么,以后的加解密等操作,都将在这个CSP上进行。 可以如下删除密钥容器。 CryptAcquireContext(&hCryptProv, userName, NULL, PROV_RSA_FULL, CRYPT_DELETEKEYSET); 五、 一个文件加密的例子 言归正传,我们来看一段文件加密的代码。 #include <stdio.h>#include <windows.h>#include <wincrypt.h>#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)#define KEYLENGTH 0x00800000void 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); //--------------------------------------------------------------------// Begin main.void main(void) { CHAR szSource[100]; CHAR szDestination[100]; CHAR szPassword[100]; 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);//--------------------------------------------------------------------// Call EncryptFile to do the actual encryption.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!"); } } // 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
上面的代码来自MSDN,并作了修改。注释已经很详细了,这里就不赘述了,解密与加密大同小异,大家可以自己看代码。 这次先写这么多,也许很多人觉得我写这些大家都知道,并且也太简单了。不要急慢慢来,嘿嘿:)接下来会有一些比较深入和实用的技术。 参考: |