C++加密库botan混合编译和简单使用

来源:互联网 发布:mac口红怎么样 编辑:程序博客网 时间:2024/06/07 00:22

C++加密库botan混合编译和简单使用

最近要用到加密数据,找了半天,有许多加密库:

  • botan
  • crypto++
  • tomcrypt
  • openssl
  • MCrypt
  • Cryptlib
  • PolarSSL
  • yaSSL
  • GnuPG

尝试后发现还是botan简单好用。botan加密库是什么,百度一下就知道,在这里就不多说了。

首先,我不想用lib或者dll,于是乎想直接生成.h和.cpp文件加入工程使用。好在botan支持我的这种想法,我试了其他的几种库,不是使用静态库就是使用动态库,并没有办法直接将.h和.cpp文件加入工程编译。

1.到官网 http://botan.randombit.net/ 下载源文件,我下载的是最新版Botan-1.10.5,解压。

2.下载安装python,我是下载Python2.7.3版本,2.7的应该都行,别下载3.x.x的版本,用来编译botan会失败的,官网有说明,解决办法还没搞懂。

3.找到安装的python目录,复制python.exe的路径,我的是C:\Python27\python.exe,打开vs2008命令提示工具,定位到botan解压后的文件夹根目录下,将复制的python.exe路径粘贴,然后编辑成如下语句:C:\Python27\python.exe configure.py --c=msvc --gen-amalgamation 回车,之后会在botan根目录下生成botan_all.cpp和botan_all.h两个文件,这正是我们需要的。

4.新建控制台工程,将生成的cpp和h文件加入工程中,测试代码如下:

#include "stdafx.h"#include "botan_all.h"using namespace Botan;#include <iostream>#include <string>using namespace std;string cryptoAES(string input,string passphrase/*密码种子,MD5加密后作为密钥*/,Cipher_Dir opt) {//AES加密和解密    HashFunction* hash = get_hash("MD5");    SymmetricKey key = hash->process(passphrase);    SecureVector<byte> raw_iv = hash->process('0'+ passphrase);    InitializationVector iv(raw_iv, 16);    string output="";    if (opt==ENCRYPTION)    {        Pipe pipe(get_cipher("AES-128/CBC", key, iv, opt),new Hex_Encoder);//Hex_Encoder表示加密后转码为十六进制输出        pipe.process_msg(input);        output=pipe.read_all_as_string();    }    else if(opt==DECRYPTION)    {        Pipe pipe(new Hex_Decoder,get_cipher("AES-128/CBC", key, iv, opt));//Hex_Decoder表示以十六进制字符串为输入,转码后进行解密        pipe.process_msg(input);        output=pipe.read_all_as_string();    }    return output;}int main(int argc, char* argv[]){         try    {        Botan::LibraryInitializer init;//初始化                string aes=cryptoAES("57ADD6949178720A6AAC4CD2B740B8BB","0000",DECRYPTION);//AES解密        cout<<aes<<endl;        Botan::Pipe pipe(new Botan::Hash_Filter("MD5"),            new Botan::Hex_Encoder);//MD5加密        pipe.process_msg("11112222");        string md5=pipe.read_all_as_string();        cout<<md5<<endl;    }    catch(std::exception& e)    {        std::cout << "Exception caught: " << e.what() << std::endl;    }    getchar();    return 0;}

如果编译不通过,在工程宏定义处加入宏NOMINMAX ,可以解决问题。参考资料:
http://www.cppblog.com/everett/archive/2012/07/07/182122.aspx

0 0