利用OpenSSL實現MD5加密函數(附帶Ubuntu 12.04安裝OpenSSL庫的方法)

來源:互聯網
上載者:User

一.安裝OpenSSL庫

 

把下面的東西一股腦兒的裝上,以免編譯時間出現連結錯誤

apt-get install openssl  libssl-dev libssl-doc libcurl4-openssl-dev

 

二.實現MD5加密函數,接受一個字串,返回它的常規32位小寫MD5值

/*   md5_encrypt.h*/#ifndef _ENCRYPT_H_#define _ENCRYPT_H_char *md5_encrypt(const unsigned char*);#endif

 

/*  md5_encrypt.c*/#include <stdio.h>#include <stdlib.h>#include <openssl/md5.h>#include <string.h>#include <strings.h>#include "md5_encrypt.h"char *md5_encrypt(const unsigned char *str){unsigned char md[16];char tmp[3] = {'\0'};char *buf = (char*)malloc(33);bzero(buf,33);MD5(str,strlen(str),md);int i = 0;for(i=0;i<16;i++){sprintf(tmp,"%2.2x",md[i]);strcat(buf,tmp);}return buf;}

編譯此函數: gcc md5_encrypt.c -c -lcrypto

上面實現的MD5加密函數char *md5_encrypt(const unsigned char *str)接受一個const unsigned char字串,返回它的32位常規小寫字元md5值。

注意返回的md5值儲存在堆區,佔33個位元組,使用後記得用free釋放。

 

還有一種用庫中MD5_Init等函數實現的方法。以後附上。順便研究一下OpenSSL庫,沒準以後用的著。

OpenSSL是跨平台的,而且提供了命令列工具。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.