Microsoft CryptoAPI加密技术(一)

来源:互联网 发布:有手机设计软件 编辑:程序博客网 时间:2024/06/05 01:18

http://www.vckbase.com/index.php/wv/716.html

在这个信息爆炸的时代,我们不得不对信息的安全提高警惕。加密作为保障数据信息安全的一种方式,越来越受到人们的关注。
下面,我将把自己对Microsoft CryptoAPI的一些肤浅的理解与大家共享,有什么不妥之处望不吝赐教。

一、 加密方法:

当初,计算机的研究就是为了破解德国人的密码,人们并没有想到计算机给今天带来的信息革命。随着计算机的发展,运算能力的增强,密码学已经取得了巨大的进展。大体来说有以下几种形式。

1、 公用密钥加密技术

加密和解密使用不同的密钥,分别叫做“公钥”和“私钥”。顾名思义,“私钥”就是不能让别人知道的,而“公钥”就是可以公开的。这两个必须配对使用,用公钥加密的数据必须用与其对应的私钥才能解开。这种技术安全性高,得到广泛运用,但是效率太低。

2、 对称密钥加密技术

要求加密和解密过程使用相同的密钥,这样,密钥必须只能被加解密双方知道,否则就不安全。这种技术安全性不高,但是效率高。

3、 结合公用和对称密钥加密技术

公钥加密技术以速度为代价换取了高安全性,而对称加密以低安全换取高性能,所以另一种常见的加密方法就是结合以上两种技术。
用对称加密算法对数据进行加密,然后使用更安全的但效率更低的公钥加密算法对对称密钥进行加密。

4、 数字签名和鉴别

就是对已经加密的数据“签名”,这样接收者可以知道加密的数据的来源,以及是否被更改。

二、 CryptoAPI

微软的CryptoAPI是PKI推荐使用的加密 API。其功能是为应用程序开发者提供在Win32环境下使用加密、验证等安全服务时的标准加密接口。CryptoAPI处于应用程序和CSP(cryptographic service provider)之间(见图一)。

 

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都有一个名字和一个类型。每个CSP的名字是唯一的,这样便于CryptoAPI找到对应的CSP。目前已经有9种CSP类型,并且还在增长。下表列出出它们支持的密钥交换算法、签名算法、对称加密算法和Hash算法。

(表一)

CSP类型交换算法签名算法对称加密算法Hash算法PROV_RSA_FULLRSARSARC2
RC4MD5
SHAPROV_RSA_SIGnoneRSAnoneMD5
SHAPROV_RSA_SCHANNELRSARSARC4
DES
Triple DESMD5
SHAPROV_DSSDSSnoneDSSMD5
SHAPROV_DSS_DHDHDSSCYLINK_MEKMD5
SHAPROV_DH_SCHANNELDHDSSDES
Triple DESMD5
SHAPROV_FORTEZZAKEADSSSkipjackSHAPROV_MS_EXCHANGERSARSACASTMD5PROV_SSLRSARSAVariesVaries

从图一可以看到,每个CSP有一个密钥库,密钥库用于存储密钥。而每个密钥库包括一个或多个密钥容器(Key Containers)。每个密钥容器中含属于一个特定用户的所有密钥对。每个密钥容器被赋予一个唯一的名字。在销毁密钥容器前CSP将永久保存每一个密钥容器,包括保存每个密钥容器中的公/私钥对(见图二)。

四、 创建密钥容器,得到CSP句柄

说了这么多只是一些理论性的东西,后面将详细介绍一下Microsoft CryptoAPI的使用方法。

我们已经提过,每一个CSP都有一个名字和一个类型,并且名字保证唯一。所以可以通过名字和类型得到一个CSP。然而,要想加密肯定需要密钥,那么密钥放哪里呢?对了,就放在密钥容器。(有人会问,密码库有什么用?其实密钥库是在安装CSP的时候已经存在了,他与CSP是相对应的。)但是密钥容器并不是一开始就存在的,需要用户去创建。下面的代码实现以上功能(得到CSP即密码容器)。

view source
print?
01.if(CryptAcquireContext(
02.&hCryptProv,              // 返回CSP句柄
03.UserName,                 // 密码容器名
04.NULL,                     // NULL时使用默认CSP名(微软RSA Base Provider)
05.PROV_RSA_FULL,            // CSP类型
06.0))                       // Flag values
07.{
08.//以UserName为名的密钥容器存在,那么我们已经得到了CSP的句柄
09.    printf("A crypto context with the %s key container \n", UserName);
10.    printf("has been acquired.\n\n");
11.}
12.else//如果密钥容器不存在,我们需要创建这个密钥容器
13.
14.   if(CryptAcquireContext(
15.      &hCryptProv, 
16.      UserName, 
17.      NULL, 
18.      PROV_RSA_FULL, 
19.      CRYPT_NEWKEYSET))//创建以UserName为名的密钥容器
20.   {
21.    //创建密钥容器成功,并得到CSP句柄
22.      printf("A new key container has been created.\n");
23.   }
24.   else
25.   {
26.      HandleError("Could not create a new key container.\n");
27.    }
28.}// End of else

好了,我们已经创建了密钥容器,并得到了CSP的句柄。也可以这样理解,我们得到了一个CSP的句柄,并且它被绑定到以UserName为名的密钥容器上。嘿嘿……

那么,以后的加解密等操作,都将在这个CSP上进行。

可以如下删除密钥容器。

CryptAcquireContext(&hCryptProv, userName, NULL, PROV_RSA_FULL, CRYPT_DELETEKEYSET);

五、 一个文件加密的例子

看到这里肯定有人开始说了,“这么多废话,还不快讲怎么加密怎么解密!”您先别急,有些原理性的东西还是先了解了比较好,对以后的使用会有很大帮助。

言归正传,我们来看一段文件加密的代码。

view source
print?
001.#include < stdio.h >
002.#include < windows.h >
003.#include < wincrypt.h >
004.#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
005.#define KEYLENGTH  0x00800000
006.voidHandleError(char *s);
007.  
008.//--------------------------------------------------------------------
009.//  These additional #define statements are required.
010.#define ENCRYPT_ALGORITHM CALG_RC4 
011.#define ENCRYPT_BLOCK_SIZE 8 
012.  
013.//   Declare the function EncryptFile. The function definition
014.//   follows main.
015.  
016.BOOLEncryptFile(
017.                 PCHARszSource, 
018.                 PCHARszDestination, 
019.                 PCHARszPassword); 
020.  
021.//--------------------------------------------------------------------
022.//   Begin main.
023.  
024.voidmain(void
025.
026.    CHARszSource[100]; 
027.    CHARszDestination[100]; 
028.    CHARszPassword[100]; 
029.      
030.      
031.    printf("Encrypt a file. \n\n");
032.    printf("Enter the name of the file to be encrypted: ");
033.    scanf("%s",szSource);
034.    printf("Enter the name of the output file: ");
035.    scanf("%s",szDestination);
036.    printf("Enter the password:");
037.    scanf("%s",szPassword);
038.      
039.    //--------------------------------------------------------------------
040.    // Call EncryptFile to do the actual encryption.
041.      
042.    if(EncryptFile(szSource, szDestination, szPassword))
043.    {
044.        printf("Encryption of the file %s was a success. \n", szSource);
045.        printf("The encrypted data is in file %s.\n",szDestination);
046.    }
047.    else
048.    {
049.        HandleError("Error encrypting file!"); 
050.    
051.}// End of main
052.  
053.//--------------------------------------------------------------------
054.//   Code for the function EncryptFile called by main.
055.  
056.staticBOOL EncryptFile(
057.                        PCHARszSource, 
058.                        PCHARszDestination, 
059.                        PCHARszPassword)
060.                        //--------------------------------------------------------------------
061.                        //   Parameters passed are:
062.                        //     szSource, the name of the input, a plaintext file.
063.                        //     szDestination, the name of the output, an encrypted file to be 
064.                        //         created.
065.                        //     szPassword, the password.
066.
067.    //--------------------------------------------------------------------
068.    //   Declare and initialize local variables.
069.      
070.    FILE*hSource; 
071.    FILE*hDestination; 
072.      
073.    HCRYPTPROV hCryptProv; 
074.    HCRYPTKEY hKey; 
075.    HCRYPTHASH hHash; 
076.          
077.    PBYTEpbBuffer; 
078.    DWORDdwBlockLen; 
079.    DWORDdwBufferLen; 
080.    DWORDdwCount; 
081.      
082.    //--------------------------------------------------------------------
083.    // Open source file. 
084.    if(hSource =fopen(szSource,"rb"))
085.    {
086.        printf("The source plaintext file, %s, is open. \n", szSource);
087.    }
088.    else
089.    
090.        HandleError("Error opening source plaintext file!");
091.    
092.  
093.    //--------------------------------------------------------------------
094.    // Open destination file. 
095.    if(hDestination =fopen(szDestination,"wb"))
096.    {
097.        printf("Destination file %s is open. \n", szDestination);
098.    }
099.    else
100.    {
101.        HandleError("Error opening destination ciphertext file!"); 
102.    }
103.  
104.    //以下获得一个CSP句柄
105.    if(CryptAcquireContext(
106.        &hCryptProv, 
107.        NULL,              //NULL表示使用默认密钥容器,默认密钥容器名
108.//为用户登陆名
109.        NULL, 
110.        PROV_RSA_FULL, 
111.        0))
112.    {
113.        printf("A cryptographic provider has been acquired. \n");
114.    }
115.    else
116.    {
117.        if(CryptAcquireContext(
118.            &hCryptProv, 
119.            NULL, 
120.            NULL, 
121.            PROV_RSA_FULL, 
122.            CRYPT_NEWKEYSET))//创建密钥容器
123.        {
124.            //创建密钥容器成功,并得到CSP句柄
125.            printf("A new key container has been created.\n");
126.        }
127.        else
128.        {
129.            HandleError("Could not create a new key container.\n");
130.        }
131.          
132.    }
133.  
134.    //--------------------------------------------------------------------
135.    // 创建一个会话密钥(session key)
136.    // 会话密钥也叫对称密钥,用于对称加密算法。
137.    // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
138.    //   CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
139.  
140.    //--------------------------------------------------------------------
141.    // Create a hash object. 
142.    if(CryptCreateHash(
143.        hCryptProv, 
144.        CALG_MD5, 
145.        0, 
146.        0, 
147.        &hHash))
148.    {
149.        printf("A hash object has been created. \n");
150.    }
151.    else
152.    
153.        HandleError("Error during CryptCreateHash!\n");
154.    }  
155.  
156.    //--------------------------------------------------------------------
157.    // 用输入的密码产生一个散列
158.    if(CryptHashData(
159.        hHash, 
160.        (BYTE*)szPassword, 
161.        strlen(szPassword), 
162.        0))
163.    {
164.        printf("The password has been added to the hash. \n");
165.    }
166.    else
167.    {
168.        HandleError("Error during CryptHashData. \n"); 
169.    }
170.  
171.    //--------------------------------------------------------------------
172.    // 通过散列生成会话密钥
173.    if(CryptDeriveKey(
174.        hCryptProv, 
175.        ENCRYPT_ALGORITHM, 
176.        hHash, 
177.        KEYLENGTH, 
178.        &hKey))
179.    {
180.        printf("An encryption key is derived from the password hash. \n"); 
181.    }
182.    else
183.    {
184.        HandleError("Error during CryptDeriveKey!\n"); 
185.    }
186.    //--------------------------------------------------------------------
187.    // Destroy the hash object. 
188.      
189.    CryptDestroyHash(hHash); 
190.    hHash = NULL; 
191.      
192.    //--------------------------------------------------------------------
193.    //  The session key is now ready. 
194.      
195.    //--------------------------------------------------------------------
196.    // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
197.// 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
198.// 数据长度。
199.  
200.    dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; 
201.      
202.    //--------------------------------------------------------------------
203.    // Determine the block size. If a block cipher is used, 
204.    // it must have room for an extra block. 
205.      
206.    if(ENCRYPT_BLOCK_SIZE > 1) 
207.        dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; 
208.    else 
209.        dwBufferLen = dwBlockLen; 
210.      
211.    //--------------------------------------------------------------------
212.    // Allocate memory. 
213.    if(pbBuffer = (BYTE*)malloc(dwBufferLen))
214.    {
215.        printf("Memory has been allocated for the buffer. \n");
216.    }
217.    else
218.    
219.        HandleError("Out of memory. \n"); 
220.    }
221.    //--------------------------------------------------------------------
222.    // In a do loop, encrypt the source file and write to the source file. 
223.      
224.    do 
225.    
226.          
227.        //--------------------------------------------------------------------
228.        // Read up to dwBlockLen bytes from the source file. 
229.        dwCount =fread(pbBuffer, 1, dwBlockLen, hSource); 
230.        if(ferror(hSource))
231.        
232.            HandleError("Error reading plaintext!\n");
233.        }
234.          
235.        //--------------------------------------------------------------------
236.        // 加密数据
237.        if(!CryptEncrypt(
238.            hKey,          //密钥
239.            0,             //如果数据同时进行散列和加密,这里传入一个
240.//散列对象
241.            feof(hSource), //如果是最后一个被加密的块,输入TRUE.如果不是输.
242.                            //入FALSE这里通过判断是否到文件尾来决定是否为
243.//最后一块。
244.            0,             //保留
245.            pbBuffer,      //输入被加密数据,输出加密后的数据
246.            &dwCount,      //输入被加密数据实际长度,输出加密后数据长度
247.            dwBufferLen))  //pbBuffer的大小。
248.        
249.            HandleError("Error during CryptEncrypt. \n"); 
250.        
251.          
252.        //--------------------------------------------------------------------
253.        // Write data to the destination file. 
254.          
255.        fwrite(pbBuffer, 1, dwCount, hDestination); 
256.        if(ferror(hDestination))
257.        
258.            HandleError("Error writing ciphertext.");
259.        }
260.          
261.    
262.    while(!feof(hSource)); 
263.    //--------------------------------------------------------------------
264.    //  End the do loop when the last block of the source file has been
265.    //  read, encrypted, and written to the destination file.
266.      
267.    //--------------------------------------------------------------------
268.    // Close files.
269.      
270.    if(hSource) 
271.        fclose(hSource); 
272.    if(hDestination) 
273.        fclose(hDestination); 
274.      
275.    //--------------------------------------------------------------------
276.    // Free memory. 
277.      
278.    if(pbBuffer) 
279.        free(pbBuffer); 
280.      
281.    //--------------------------------------------------------------------
282.    // Destroy session key. 
283.      
284.    if(hKey) 
285.        CryptDestroyKey(hKey); 
286.      
287.    //--------------------------------------------------------------------
288.    // Destroy hash object. 
289.      
290.    if(hHash) 
291.        CryptDestroyHash(hHash); 
292.      
293.    //--------------------------------------------------------------------
294.    // Release provider handle. 
295.      
296.    if(hCryptProv) 
297.        CryptReleaseContext(hCryptProv, 0);
298.    return(TRUE); 
299.}// End of Encryptfile
300.  
301.//--------------------------------------------------------------------
302.//  This example uses the function HandleError, a simple error
303.//  handling function, to print an error message to the standard error 
304.//  (stderr) file and exit the program. 
305.//  For most applications, replace this function with one 
306.//  that does more extensive error reporting.
307.  
308.voidHandleError(char *s)
309.{
310.    fprintf(stderr,"An error occurred in running the program. \n");
311.    fprintf(stderr,"%s\n",s);
312.    fprintf(stderr,"Error number %x.\n", GetLastError());
313.    fprintf(stderr,"Program terminating. \n");
314.    exit(1);
315.}// End of HandleError

上面的代码来自MSDN,并作了修改。注释已经很详细了,这里就不赘述了,解密与加密大同小异,大家可以自己看代码。

这次先写这么多,也许很多人觉得我写这些大家都知道,并且也太简单了。不要急慢慢来,嘿嘿:)接下来会有一些比较深入和实用的技术。

参考:

MSDN相关章节。

(注:如果代码编译不过,加入宏定义:_WIN32_WINNT=0x0400)

 

 

0 0
原创粉丝点击