SHA-1算法的C语言实现(源码来自网络)

本文详细介绍了如何使用C语言实现SHA-1算法,包括代码实现、函数解析和使用示例,帮助读者理解并应用SHA-1哈希计算。
摘要由CSDN通过智能技术生成

来自网络上的SHA-1算法,自己加了少量注释,方便以后需要的时候可以利用。

代码:

/* sha1sum.c - print SHA-1 Message-Digest Algorithm
 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
 * Copyright (C) 2004 g10 Code GmbH
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* SHA-1 coden take from gnupg 1.3.92.

   Note, that this is a simple tool to be used for MS Windows.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>

#undef BIG_ENDIAN_HOST
typedef unsigned int u32;

/****************
 * Rotate a 32 bit integer by n bytes
 ****************/
#if defined(__GNUC__) && defined(__i386__)
static inline u32 rol( u32 x, int n)
{
 __asm__("roll %%cl,%0"
            :"=r" (x)
            :"0" (x),"c" (n));
 return x;
}
#else
#define rol(x,n) ( ((x) << (n)) | ((x) >> (32-(n))) )
#endif


typedef struct {
    u32  h0,h1,h2,h3,h4;   //哈希计算后的结果是20个bit,刚好相当于5个unsigned int(4字节)类型的数据
    u32  nblocks;
    unsigned char buf[64];
    int  count;
} SHA1_CONTEXT;

 

void sha1_init( SHA1_CONTEXT *hd ) //计算前进行初始化
{
    hd->h0 = 0x67452301;
    hd->h1 = 0xefcdab89;
    hd->h2 = 0x98badcfe;
    hd->h3 = 0x10325476;
    hd->h4 = 0xc3d2e1f0;
    hd->nblocks = 0;
    hd->count = 0;
}


/*
 * Transform the message X which consists of 16 32-bit-words
 */
static void
transform( SHA1_CONTEXT *hd, unsigned char *data )
{
    u32 a,b,c,d,e,tm;
    u32 x[16];

    /* get values from the chaining vars */
    a &#

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值