异想天开

What's the true meaning of light, Could you tell me why

openssl库简单demo

日期:2014-04-16 17:33:28
  
最后更新日期:2014-11-11 15:17:40
【技术】
最后更新-2014-11-11
先不究原理,贴出示例代码。ps:关于md5的hash算法,我曾问过某个朋友,他给我讲解后,没有看出那种直观性,所以先暂时放弃理解它。这里记下用得到的几个接口。
1.aes可逆加密和解密
[code lang="cpp"]
//例1:test1.cpp
//g++ -lssl test1.cpp -o test1
#include<stdio.h>
#include<string.h>
#include<openssl/aes.h>
typedef unsigned char uint8 ;
int main()
{
int bits=128;
unsigned char userKey[16];
strncpy(reinterpret_cast<char *>(userKey),"0123456789abcdef",sizeof(userKey));
unsigned char buf[32];
unsigned char hexbuf[64];
strncpy((char *)buf,"hello world",sizeof(buf));
AES_KEY aesKey1;
AES_set_encrypt_key((uint8 *)userKey, bits, &aesKey1);
unsigned char *in=buf,*out=buf;
AES_encrypt(in, out, &aesKey1);
for(int i=0; i<16; ++i)
{
sprintf((char*)hexbuf+i*2,"%02X",out[i]);
}
printf("%s\n",hexbuf);
AES_KEY aesKey2;
AES_set_decrypt_key((uint8 *)userKey, bits, &aesKey2);
AES_decrypt(in, out, &aesKey2);
printf("%s\n",out);
for(int i=0; i<16; ++i)
{
sprintf((char*)hexbuf+i*2,"%02X",out[i]);
}
printf("%s\n",hexbuf);
}
[/code]
注:
1.in,out不要用同一个缓冲
2.aes加密并不改变加密后的长度,128 bit即每块为16字节。对称加密分为ecb,cbc和cfb等模式,openssl的aes函数默认是ecb模式

2.md5计算hash值
[code lang="cpp"]
//test2.cpp
//g++ -lssl test2.cpp -o test2
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <openssl/md5.h>
int main()
{
MD5_CTX ctx;
const char *psignature="hello";
time_t now=time(NULL);
char now_time[64];
sprintf(now_time,"%lu",now);
printf("now is %s\n",now_time);
const char *ptime=now_time;
printf("calculate time :%s\n",ptime);
char buf[33]={'\0'};
char tmp[3]={'\0'};
//md5加密结果为16个范围为0-255的数,所以用的unsigned char,要变为16进制,需要32个char
unsigned char md5[16];
MD5_Init(&ctx);
MD5_Update(&ctx,psignature,strlen(psignature));
MD5_Update(&ctx,ptime,strlen(ptime));
MD5_Final(md5,&ctx);
for(int i =0;i<16;i++)
{
sprintf(tmp,"%02x",md5[i]);
strcat(buf,tmp);
}
printf("MD5 HASH VALUE: %s\n",buf);
return 0;
}
[/code]