最新消息:

Linux下调用openssl的md5类生成文件和字符串md5

未分类 admin 3536浏览 0评论

Neeao’s Blog ( http://neeao.com/ ) :

找个能使用的c++调用openssl的代码都这么难,自己写了个,记录下。

以下代码在CentOS5下测试可用。

//============================================================================
// Name        : m d 5.cpp
// Author      : Neeao
// Version     :
// Copyright   : http://Neeao.com
//============================================================================

#include <iostream>
#include <openssl/md5.h>
#include <fstream>

using namespace std;
/**
 * 字符串md5
 */
string string_md5(string str)
{
		unsigned char md[16];
		char tmp[33]={''};
		string hash="";
		MD5((const unsigned char*)str.c_str(), str.size(), md);
		for(int i=0; i<16; i++){
				sprintf(tmp, "%02X", md[i]);
				hash+=(string)tmp;
		}
		return hash;
}
/**
 * 文件 md5
 */
string file_md5(string file_name)
{
		MD5_CTX md5;
		unsigned char md[16];
		char tmp[33]={''};
		int length,i;
		char buffer[1024];
		string hash="";
		MD5_Init(&md5);
		ifstream fin(file_name.c_str(),ios::in|ios::binary);
		while(!fin.eof())
			{
						fin.read(buffer, 1024);
						length = fin.gcount();
						if (length > 0) {
							MD5_Update(&md5,buffer, length);
						}
			}
			MD5_Final(md,&md5);
			for(i=0; i<16; i++){
					sprintf(tmp, "%02X", md[i]);
					hash+=(string)tmp;
		    }
			return hash;
}
int main() {
		string file_name = "/root/install.log";
		cout<<file_md5(file_name)<<endl;
		cout<<string_md5(file_name)<<endl;
		return 0;
}

转载请注明:爱开源 » Linux下调用openssl的md5类生成文件和字符串md5

您必须 登录 才能发表评论!