欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

年轻时写过的傻1算法

程序员文章站 2024-03-19 14:10:52
...
#include<iostream>
#include<bitset>
#include<string>
#include<stdlib.h>
#include<fstream>
using namespace std;

unsigned int H0=0x67452301,H1=0xefcdab89,H2=0x98badcfe,H3=0x10325476,H4=0xc3d2e1f0; 
unsigned int A,B,C,D,E;
string bset(string str)
{
	unsigned int l = 0;
	string st;
	l = str.length();
	for (int i = 0; i < l; i++)
	{
		st += bitset<8>(str[i]).to_string();
	}
	return st;
}

int juge(string str)
{
	unsigned int l = 0, n = 0;
	unsigned int bl;
	l=str.length();
	while (n+1)
	{
		if (l < (448+512*n))
		{
			bl = 512 * (n+1);
			bl = bl - l - 65;
			break;
		}
		n++;
	}
	return bl;
}


string add(string str, unsigned int l)
{
	str = str + '1';
	for (int i= 0; i < l; i++)
	{
		str += '0';
	}
	return str;
}

string addlast(string str,unsigned int l)
{
	string s = bitset<64>(l*8).to_string();
	str += s;
	return str;
}

void apart(string str)
{
	unsigned int l = 0,temp = 0,temp1 = 0,flag = 0;
	unsigned long k,f,tep1 = 0,tep2 = 0,tep3 = 0,tep = 0;
	A = H0; B = H1; C = H2; D = H3; E = H4;
	l = str.length();
	l = l / 512;
	string s[16]; 
	unsigned long long bi[80];
	string st[10000];
	for (int i = 0; i < l; i++)
	{
		unsigned int j = 512 * (i+1);
		for ( int k= 512*i; k <j ; k++)
		{
			st[i] += str[k];
		}
	}
	for (int j = 0; j < l; j++)
	{
		for (int clear = 0; clear < 16; clear++)
		{
			s[clear]="";
		}
		for (int sl = 0; sl < 16; sl++)
		{
			for (int t = 32*sl; t < 32*(sl+1); t++)
			{
				s[sl] += st[j][t];
			}
			bi[sl] = stoll(s[sl],nullptr,2);
			cout<<bi[sl]<<endl;
		}
		for(int a=16;a<80;a++)
		{
			bi[a]=bi[a-16]^bi[a-14]^bi[a-8]^bi[a-3];
			temp=bi[a] << 1;
			temp1=bi[a]>>31;
			bi[a]=temp|temp1;
		}
		for(int h=0;h<80;h++)
		{
			flag=h/20;
			switch(flag)
			{
			case 0: k=0x5a827999;f=(B&C)^(~B&D);break;
			case 1: k=0x6ed9eba1;f=B^C^D;break;
			case 2: k=0x8f1bbcdc;f=(B&C)^(B&D)^(C&D);break;
			case 3: k=0xca62c1d6;f=B^C^D;break;
			}
			tep1=A<<5;
			tep2=A>>27;
			tep3=tep1|tep2;
			tep=tep3+f+E+k+bi[h];
			E=D;
			D=C;

			tep1=B<<30;
			tep2=B>>2;
			tep3=tep1|tep2;
			C=tep3;
			B=A;
			A=tep;
			cout<<dec<<h<<" ";
			cout<<hex<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<endl;
		}
		H0=H0+A;
		H1=H1+B;
		H2=H2+C;
		H3=H3+D;
		H4=H4+E;
		A=H0;B=H1;C=H2;D=H3;E=H4;
	}
	cout<<hex<<H0<<" "<<H1<<" "<<H2<<" "<<H3<<" "<<H4;
}

int main()
{
	unsigned int l;
	unsigned int bl;
	int size = 0;
	string name ;
	string str;
	char filestr[1000];
	while (true)
	{

		cout<<"Please input filename:";
		cin>>name;
		ifstream myfile(name);
		if (myfile)
		{
			myfile.seekg(0,ifstream::end);
			size = myfile.tellg();
			myfile.seekg(0,ifstream::beg);
			myfile.read(filestr,size);
			break;		
		}
		else
		{
			cout<<"not a filename"<<endl;
			continue;
		}
	}
	for (int i = 0; i < size; i++)
	{
		str += filestr[i];
	}
	l = str.length();
	string str2;
	str2 = bset(str);
	bl = juge(str2);
	str2 = add(str2,bl);
	str2 = addlast(str2,l);
	apart(str2);
}

相关标签: SHA1算法