linux下用openssl获取数据文件摘要(C源码)

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中.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值