C语言实现SHA-1
參考:《密碼學引論》第二版 武漢大學出版社
SHA-1簡介
SHA-1(英語:Secure Hash Algorithm 1,中文名:安全散列算法1)是一種密碼散列函數,美國國家安全局設計,并由美國國家標準技術研究所(NIST)發布為聯邦數據處理標準(FIPS)。SHA-1可以生成一個被稱為消息摘要的160位(20字節)散列值,散列值通常的呈現形式為40個十六進制數。(源自百度百科)
具體實現
數據填充
填充數據的母的是使數據長度與448模512同余(這里是指位數)。若數據本身已經滿足上述長度要求,讓需要進行填充(例如,若數據長度為448位,則仍需要填充512位使其長度變為960,原因最后一組填充需要在數據后附加一個1(8位)以及填充前數據的長度(64位),因此最后一組長度最長為440(輸入為字符串格式下)),因此填充位數在1~512之間。
填充方法為在數據后附加一個1和若干個0,然后附上表示填充前數據長度的64位數據(最高有效位在前)。
以"this is a test"為例:
填充前:
填充后(0x70表示輸入字符串的位數):
其他情況詳見代碼
初始化緩沖區
Hash函數中間結果和最終結果都保存于160位的緩沖區中,緩沖區由5個32位寄存器組成,將這些寄存器初始化為下列32為的整數值。
unsigned int h[5]={0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0};
需要注意的是,在SHA-1中,字的最高有效字節存于低地址字節位置。
執行算法主循環
如圖所示:
每次循環處理一個512位的分組,故循環次數位填充后的數據分組數。
具體代碼
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define rol(x,y) ((x<<y)|(x>>(32-y))) //循環左移 //一次循環過程,str為填充后的數據或是數據中的一部分
void round(unsigned char str[64],unsigned int h[5]){unsigned int a, b, c, d, e,tmp,w[80];unsigned int i;for(i=0;i<16;i++){w[i]=((unsigned int)str[i*4]<<24)|(((unsigned int)str[i*4+1])<<16)|(((unsigned int)str[i*4+2])<<8)|(((unsigned int)str[i*4+3])<<0);}for (i=16;i<80;i++ ){tmp = w[i-3]^w[i-8]^w[i-14]^w[i-16];w[i]=rol(tmp,1);}a=h[0];b=h[1];c=h[2];d=h[3];e=h[4];for(i=0;i<80;i++){switch(i/20){case 0:tmp=rol(a,5)+((b&c)|(d&~b))+e+w[i]+0x5a827999;break;case 1:tmp=rol(a,5)+(b^c^d)+e+w[i]+0x6ed9eba1;break;case 2:tmp=rol(a,5)+((b&c)|(b&d)|(c&d))+e+w[i] +0x8f1bbcdc;break;case 3:tmp=rol(a,5)+(b^c^d)+e+w[i] + 0xca62c1d6;break;}e=d;d=c;c=rol(b,30);b=a;a=tmp;}h[0]+=a;h[1]+=b;h[2]+=c;h[3]+=d;h[4]+=e;
}//sha-1算法
void sha1(unsigned char*input,long long len,unsigned char*output){unsigned char temp[64];unsigned int h[5]={0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0};unsigned int i,n=len,tmp;while(n>=64){memcpy(temp,input+len-n,64);round(temp,h);n-=64;}if(n>=56){memset(temp,0,64);memcpy(temp,input+len-n,n);temp[n]=128;round(temp,h);memset(temp,0,64);for(i=56;i<64;i++)temp[i]=((len*8)>>(63-i)*8)&0xff;round(temp,h);}else{memset(temp,0,64);memcpy(temp,input+len-n,n);temp[n]=128;for(i=56;i<64;i++)temp[i]=((len*8)>>(63-i)*8)&0xff;round(temp,h); }for(i=0;i<20;i++){tmp=(h[i/4]>>((3-i%4)*8))&0xff;sprintf((char*)output+2*i,"%02x",tmp);}
}//測試
int main(){unsigned char input[]="this is a test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",output[40]={0};sha1(input,strlen((char*)input),output);printf("%s\n",output);
}
代碼效果:
在線工具網址:http://ctf.ssleye.com/hash.html
工具求hash結果:
總結
以上是生活随笔為你收集整理的C语言实现SHA-1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matlab实现图像白平衡(灰度世界法、
- 下一篇: Miller方法产生、检验素数