c++ md5加密函数

1. 环境

系统: centos 7

依赖库

yum install openssl-devel

(1) 代码

#md5.cpp

#include <string>
#include <openssl/md5.h>
#include <stdio.h>
#include <string.h>



#define MD5_SECRET_LEN_16     (16)
#define MD5_BYTE_STRING_LEN   (4)

std::string commonMd5Secret32(const std::string& src)
{
    MD5_CTX ctx;

    std::string md5String;
    unsigned char md[MD5_SECRET_LEN_16] = { 0 };
    char tmp[MD5_BYTE_STRING_LEN] = { 0 };

    MD5_Init( &ctx );
    MD5_Update( &ctx, src.c_str(), src.size() );
    MD5_Final( md, &ctx );

    for( int i = 0; i < 16; ++i )
    {
        memset( tmp, 0x00, sizeof( tmp ) );
        snprintf( tmp,sizeof(tmp) , "%02X", md[i] );
        md5String += tmp;
    }
    return md5String;
}


int main()
{
    printf("%s\n", commonMd5Secret32("12345678").c_str());
    printf("%s\n", commonMd5Secret32("123abc").c_str());

    return 0;
}

(2) 编译

g++ -o md5 md5.cpp  -lcrypto

(3) 执行结果

猜你喜欢

转载自blog.csdn.net/u011857683/article/details/81159948
今日推荐