OPENSSL安装:(VS)
1:第一步和所有的软件安装一样。
2:将OPENSSL中INLUCDE 和 LIB 分别拷贝到VS中VC的INLUCDE 和LIB目录下(我的机器上的目录是:C:\Program Files\Microsoft Visual Studio 10.0\VC。
3:在VS中项目的属性中,添加链接库,include链接库
如下图:
(1)添加链接库
加入下图红色的LIB
(2)添加INCLUDE文件,指向OPENSSL的INCLUDE文件夹
搞定!!
下面是源码!
#pragma once //#include "targetver.h" #include <stdio.h> #include <tchar.h> #include "openssl/evp.h" #include "openssl/rsa.h" #include "openssl/aes.h" #include "openssl/rand.h" #include<iostream> using namespace std; void main() { bool do_encrypt(unsigned char *iv,unsigned char *key,unsigned char *inBuffer,int inLen,unsigned char *outBuffer,int * pOutLen); bool do_decrypt(unsigned char *iv,unsigned char *key,unsigned char *inBuffer,int inLen,unsigned char *outBuffer,int * pOutLen); void print_hex(unsigned char *buf,unsigned int len); void print_char(unsigned char *buf,unsigned int len); char RIV[] = "helloUSTCThisCourseIsCalledInformationSecurtiy"; unsigned char iv[16]; unsigned char *inBuffer=new unsigned char[]; unsigned char *aseOutBuffer=new unsigned char[]; unsigned char key[16]="this'is'a'test!"; char c=' '; int i=0,outLen,inLen; for (int k=0;k<16;k++) { int x = rand()%sizeof(RIV); iv[k] = RIV[x]; } cout<<"请输入需要加密的明文,以*作为结束符:"; while(c!='*') { c=getchar(); inBuffer[i++]=c; } cout<<endl; do_encrypt(iv,key,inBuffer,i-1,aseOutBuffer,&outLen); cout<<"使用AES进行加密,生成的密文为:"; print_hex(aseOutBuffer,outLen); cout<<endl<<endl; do_decrypt(iv,key,aseOutBuffer,outLen,inBuffer,&inLen); cout<<"使用AES进行解密,解密得到明文为:"; print_hex(inBuffer,inLen); cout<<endl; cout<<"即:"; print_char(inBuffer,inLen); cout<<endl<<endl; system("pause"); } bool do_encrypt(unsigned char *iv,unsigned char *key,unsigned char *inBuffer,int inLen,unsigned char *outBuffer,int * pOutLen) { int tmplen; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv); if(!EVP_EncryptUpdate(&ctx,outBuffer,pOutLen,inBuffer,inLen)) { return false; } if(!EVP_EncryptFinal_ex(&ctx,outBuffer+*pOutLen,&tmplen)) { return false; } *pOutLen+=tmplen; EVP_CIPHER_CTX_cleanup(&ctx); return true; } bool do_decrypt(unsigned char *iv,unsigned char *key,unsigned char *inBuffer,int inLen,unsigned char *outBuffer,int * pOutLen) { int tmplen; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_DecryptInit_ex(&ctx,EVP_aes_128_cbc(),NULL,key,iv); if(!EVP_DecryptUpdate(&ctx,outBuffer,pOutLen,inBuffer,inLen)) { return false; } if(!EVP_DecryptFinal_ex(&ctx,outBuffer+*pOutLen,&tmplen)) { return false; } *pOutLen+=tmplen; EVP_CIPHER_CTX_cleanup(&ctx); return true; } void print_hex(unsigned char *buf,unsigned int len) { for(int i=0;i<len;i++) printf("%0.2x",buf[i]); } void print_char(unsigned char *buf,unsigned int len)//字符形式显示数组内容 { for(int i=0;i<len;i++) printf("%c",buf[i]); }