crypto++编程

1.AES 举例

#include "stdafx.h"
#include 
using namespace std;
#include 
using namespace CryptoPP;
int main()
{
//AES 中使用的固定参数是以类 AES 中定义的 enum 数据类型出现的,而不是成员函数或变量
//因此需要用::符号来索引
cout << "AES Parameters: " << endl;
cout << "Algorithm name : " << AES::StaticAlgorithmName() << endl;
//Crypto++库中一般用字节数来表示长度,而不是常用的字节数
cout << "Block size : " << AES::BLOCKSIZE * 8 << endl;
cout << "Min key length : " << AES::MIN_KEYLENGTH * 8 << endl;
cout << "Max key length : " << AES::MAX_KEYLENGTH * 8 << endl;
//AES 中只包含一些固定的数据,而加密解密的功能由 AESEncryption 和 AESDecryption 来完成
//加密过程
AESEncryption aesEncryptor; //加密器
unsigned char aesKey[AES::DEFAULT_KEYLENGTH]; //密钥
unsigned char inBlock[AES::BLOCKSIZE] = "123456789"; //要加密的数据块
unsigned char outBlock[AES::BLOCKSIZE]; //加密后的密文块
unsigned char xorBlock[AES::BLOCKSIZE]; //必须设定为全零
memset( xorBlock, 0, AES::BLOCKSIZE ); //置零
aesEncryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH ); //设定加密密钥
aesEncryptor.ProcessAndXorBlock( inBlock, xorBlock, outBlock ); //加密
//以进制显示加密后的数据
for( int i=0; i<16; i++ )
{
cout << hex << (int)outBlock << " ";
}
cout << endl;
//解密
AESDecryption aesDecryptor;unsigned char plainText[AES::BLOCKSIZE];
aesDecryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH );
aesDecryptor.ProcessAndXorBlock( outBlock, xorBlock, plainText );
for( int i=0; i<16; i++ ) { cout << plainText; }
cout << endl;
return 0;
}

2.SHA1 举例
2.1 一次哈希

#include "stdafx.h"
#include 
using namespace std;
#include 
#include 
using namespace CryptoPP;
int main()
{
//byte mess[]="abc";
byte mess[]="abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
byte const* pbData = (byte const*)mess;
unsigned int nDataLen = 57;
byte abDigest[SHA::DIGESTSIZE];
SHA().CalculateDigest(abDigest, pbData, nDataLen);
// abDigest now contains the hash of pbData
if (!SHA().VerifyDigest(abDigest, pbData, nDataLen))
throw "abDigest does not contain the right hash";
for(int i=0;i

2.2 多次哈希

#include "stdafx.h"
#include 
using namespace std;
#include 
#include 
using namespace CryptoPP;
int main()
{
byte mess1[]="abc";
byte mess2[]="abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
// byte const* pbData = (byte const*)mess;
byte const* pbData1 =(byte const*)mess1;
byte const* pbData2 = (byte const*)mess2;
unsigned int nData1Len =3;
unsigned int nData2Len = 57;
byte abDigest[SHA::DIGESTSIZE];
SHA hash;
hash.Update(pbData1, nData1Len);
hash.Update(pbData2, nData2Len);
hash.Final(abDigest);
for(int i=0;i

3 SHA256 举例
只需把 sha1 中的 SHA 替换为 SHA256 即可

#include "stdafx.h"
#include 
using namespace std;
#include 
#include 
using namespace CryptoPP;
int main()
{
byte mess1[]="abc";
byte mess2[]="abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
byte const* pbData1 =(byte const*)mess1;
byte const* pbData2 = (byte const*)mess2;
unsigned int nData1Len =3;
unsigned int nData2Len = 57;
byte abDigest[SHA256::DIGESTSIZE];
SHA256 hash;
hash.Update(pbData1, nData1Len);
hash.Update(pbData2, nData2Len);
hash.Final(abDigest);
for(int i=0;i

 

你可能感兴趣的:(加密)