SHA-1密码哈希算法(c语言实现)

SHA-1密码哈希算法(c语言实现)


本人为在校大学生,所写代码有诸多不足,希望各位多多指正。编译器为Dev
C++

using namespace std;
//明文
char M[100000]="abcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyzabcdefghigklmnopqrszuvwxyz"; 
//五个寄存器
unsigned int A,B,C,D,E;
//明文分组及其拓展 
unsigned int X[80];
//初始值
unsigned int IV[5]={0x67452301,0xefcdab89,0x98badcfb,0x10325476,0xc3d2e1f0}; 
//压缩函数所需常数K
unsigned int K[4]={0x5a827999,0x6ed93ba1,0x8f1bbcdc,0xca62c1d6};
//移位函数
 int move(int i,unsigned int x)
 {
 	unsigned int y;
 	y=x<>(32-i);
 	return x;
 }  
 //四轮压缩函数 
 int F1(int i)
 {
 	unsigned int m;
 	m=A;
 	A=K[0]+X[i]+move(5,A)+E+((B&C)|(~B&D));
 	E=D;
 	D=C;
 	C=move(30,B);
 	B=m;
 }
 int F2(int i)
 {
 	unsigned int m;
 	m=A;
 	A=K[1]+X[i]+move(5,A)+E+(B^C^D);
 	E=D;
 	D=C;
 	C=move(30,B);
 	B=m;
 }
 int F3(int i)
 {
 	unsigned int m;
 	m=A;
 	A=K[2]+X[i]+move(5,A)+E+((B&C)|(B&D)|(C&D));
 	E=D;
 	D=C;
 	C=move(30,B);
 	B=m;
 }
 int F4(int i)
 {
 	unsigned int m;
 	m=A;
 	A=K[3]+X[i]+move(5,A)+E+(B^C^D);
 	E=D;
 	D=C;
 	C=move(30,B);
 	B=m;
 }
 //将字符串转为可处理的32bit字,32bit为四字节由四个字符组成,每个消息分组消耗4*16=64个字符 
int code(int n,int k=16)
{
	for(int i=0;i>31)>>1;//大端存储数据位数 
	X[15]=len;
	for(int j=0;j<16;j++)printf("%08x",X[j]);
	return 0;
}
int extendsion2(unsigned long len,unsigned long n)
{
	int x=len%64;
	int y=x/4;
	int z=x%4;
	code(n-1,y);
	if(z==1)X[y]=M[64*(n-1)+4*y+1]<<24|0x800000;
	if(z==2)X[y]=M[64*(n-1)+4*y+1]<<24| M[64*(n-1)+4*y+2]<<16|0x8000;
	if(z==3)X[y]=M[64*(n-1)+4*y+1]<<24|M[64*(n-1)+4*y+2]<<16|M[64*(n-1)+4*y+3]<<8|0x80;
	if(z==0)X[y]=0x80000000;
	for(int i=y+1;i<16;i++)X[i]=0x0;
	for(int j=0;j<16;j++)printf("%08x",X[j]);
	extendsion();
	enSHA1();
	for(int i=0;i<14;i++)X[i]=0x0;
	X[14]=(len>>31)>>1;
	X[15]=len;
	for(int j=0;j<16;j++)printf("%08x",X[j]);
	return 0;
}
int main()
{
	unsigned long len=strlen(M);
	unsigned long lbit=8*len;
	int a=((lbit%512)<448)?1:0;
	unsigned long n=(a==1)?(lbit/512+1):(lbit/512+2);
	if(a==1)
	{
		for(int i=0;i

你可能感兴趣的:(SHA-1密码哈希算法(c语言实现))