util.h
#ifndef MY_SSL_UTIL
#define MY_SSL_UTIL
#include <stdio.h>
#include <string.h>
/* OpenSSL headers */
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#define BLOCKSIZE 5
#define SUCCESS 0
#define FAIL 1
/*----------------------------------------------------
Method Name: get_digest
Summary: 获取指定文件的摘要信息, 并保存到digest.dat文件中
Parameter:
Input Parameters:
filename: 文件名
OutPut Parameters:
无
Return Vaule:
成功: 0
失败: 1
------------------------------------------------------*/
int get_digest(const char* filename);
#endif
util.c
#include "util.h"
int get_digest(const char* filename)
{
FILE *fp, *fdig; /* fp用于打开数据文件, fdig用于写摘要数据 */
unsigned char md[SHA_DIGEST_LENGTH]; /* 用于存入摘要数据 */
unsigned char buf[BLOCKSIZE]; /* 存入每次从文件读取数据的缓冲区 */
int i = 0;
memset(md, 0, sizeof(md));
memset(buf, 0, sizeof(buf));
EVP_MD_CTX ctx;
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_sha1(), NULL);
if (NULL == (fp = fopen(filename, "r")))
{
perror("can't open this file");
return FAIL;
}
/* 读取文件中的数据进行摘要运算 */
while (!feof(fp))
{
fread(buf, BLOCKSIZE-1, 1, fp);
EVP_DigestUpdate(&ctx, buf, strlen(buf));
}
EVP_DigestFinal_ex(&ctx, md, NULL); /* 至此得到数据的摘要 */
/* 打印20个字节的摘要信息 */
while (i <= SHA_DIGEST_LENGTH)
{
printf("%x ", md[i]);
i++;
}
putchar('/n');
/* 将摘要数据写入digest.dat文件 */
if ((fdig = fopen("digest.dat", "w")) == NULL)
{
perror("open digest.dat failed");
return FAIL;
}
if (fwrite(md, sizeof(md), 1, fdig) < 1)
{
perror("write data to digest failed");
return FAIL;
}
//关闭文件
fclose(fp);
fclose(fdig);
return SUCCESS;
}
main.c(调用)
#include "util.h"
int main(int argc, char** argv)
{
get_digest("a.txt");
return 0;
}
在linux下键入如下命令:gcc main.c util.c -lssl,在生成可执行文件的地方新建一个a.txt的文件,随便输入些内容,运行a.out,对于a.txt的摘要就写到了当前目录的digest.dat中.