opensslmd5算法源码c++版

#include "stdafx.h"  
#include <iostream>  
#include <string>  
#include <vector>  
#include <cstdio>  
#include <iomanip>  
#include <stdlib.h>  
#include <openssl/md5.h>  

#include "cryptotest.h"  

using namespace std; // C++STL库

string MD5_Digest(const string cleartext)  
{  
    string strDigest;  // 密文
    unsigned char tmp[16] = {0};  //声明tmp[]


    MD5((const unsigned char*)cleartext.c_str(), cleartext.length(), tmp); 
//补位填充
//cleartext.c_str():c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同

    MD5_CTX c;  //MD5_CTX结构体指针
    MD5_Init(&c);  //初始化MD5_CTX
    MD5_Update(&c, cleartext.c_str(), cleartext.length());  //进行hash
    MD5_Final(tmp, &c);  //tmp是当前加密结果,放置结果


    char* tmp1 = new char[32 + 1];  //声明tmp1[]
    memset(tmp1, 0, 32 + 1);  

    for(int i = 0; i < 16; i++)   
        sprintf(&(tmp1[i*2]), "%02x", tmp[i]);  


    strDigest = (char*)tmp1;  //密文就是tmp1

    delete [] tmp1;  

    return strDigest;  //返回32位密文
}  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章