副标题#e#
在这个信息爆炸的时代,我们不得差池信息的安详提高鉴戒。加密作为保障数据信息安详的一种方法,越来越受到人们的存眷。
下面,我将把本身对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)。个中前三者可用于对敏感信息举办加密或签名处理惩罚,可担保网络传输信心的私有性;后两者通过对质书的利用,可担保网络信息交换中的认证性。
#p#副标题#e#
三、 CSP
看到这里,各人也许对CSP还较量疑惑。其实CSP是真正实行加密的独立模块,他既可以由软件实现也可以由硬件实现。可是他必需切合CryptoAPI接口的类型。
每个CSP都有一个名字和一个范例。每个CSP的名字是独一的,这样便于CryptoAPI找到对应的CSP。今朝已经有9种CSP范例,而且还在增长。下表列出出它们支持的密钥互换算法、签名算法、对称加密算法和Hash算法。
(表一)
CSP范例 | 互换算法 | 签名算法 | 对称加密算法 | Hash算法 |
PROV_RSA_FULL | RSA | RSA | RC2
RC4 |
MD5
SHA |
PROV_RSA_SIG | none | RSA | none | MD5
SHA |
PROV_RSA_SCHANNEL | RSA | RSA | RC4
DES Triple DES |
MD5
SHA |
PROV_DSS | DSS | none | DSS | MD5
SHA |
PROV_DSS_DH | DH | DSS | CYLINK_MEK | MD5
SHA |
PROV_DH_SCHANNEL | DH | DSS | DES
Triple DES |
MD5
SHA |
PROV_FORTEZZA | KEA | DSS | Skipjack | SHA |
PROV_MS_EXCHANGE | RSA | RSA | CAST | MD5 |
PROV_SSL | RSA | RSA | Varies | Varies |
#p#分页标题#e#
从图一可以看到,每个CSP有一个密钥库,密钥库用于存储密钥。而每个密钥库包罗一个或多个密钥容器(Key Containers)。每个密钥容器中含属于一个特定用户的所有密钥对。每个密钥容器被赋予一个独一的名字。在销毁密钥容器前CSP将永久生存每一个密钥容器,包罗生存每个密钥容器中的公/私钥对(见图二)。
四、 建设密钥容器,获得CSP句柄
说了这么多只是一些理论性的对象,后头将具体先容一下Microsoft CryptoAPI的利用要领。
我们已经提过,每一个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 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);
//--------------------------------------------------------------------
// 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,并作了修改。注释已经很具体了,这里就不赘述了,
解密与加密大同小异,各人可以本身看代码。
这次先写这么多,也许许多人以为我写这些各人都知道,而且也太简朴了。不要急逐步来,嘿嘿:)接下来会有一些较量深入和实用的技能。
参考:
MSDN相关章节。
(注:假如代码编译不外,插手宏界说:_WIN32_WINNT=0x0400)