#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;
#define rotateleft(x,n) ((x<<n) | (x>>(32-n)))
ifstream f("in.txt");
ofstream g("out.txt");
void sha1(unsigned char * txt)
{
unsigned long int h0,h1,h2,h3,h4,a,b,c,d,e,f,k,temp;
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
h4 = 0xC3D2E1F0;
unsigned char * text=new unsigned char[ strlen( (const char *) txt )+100 ];
strcpy((char *)text,(const char *)txt);
int current_length = strlen((const char *)text);
int original_length = current_length;
text[current_length] = 0x80; //am pus 1
text[current_length + 1] = '\0';
current_length++;
int ib = current_length % 64;
if(ib<56) ib = 56-ib;// ultimii 8 octeti se lasa pt long
else ib = 120 - ib;
for(int i=0;i<ib;i++) //punem 0-uri
{
text[current_length]=0x00;
current_length++;
}
text[current_length + 1]='\0';
for(int i=0;i<6;i++)
{
text[current_length]=0x0;
current_length++;
}
text[current_length] = (original_length * 8) / 0x100 ; current_length++;
text[current_length] = (original_length * 8) % 0x100; current_length++;
text[current_length+1]='\0';
int nr_chunks = current_length/64;
unsigned long int word[80];
cout<<"N = "<<nr_chunks<<endl;
for(int i=0;i<nr_chunks;i++)
{
//Prepare the message schedule, {Wt}
for(int j=0;j<16;j++)//Mt daca 0 <= t <= 15;
{
word[j] = text[i*64 + j*4 + 0] * 0x1000000 + text[i*64 + j*4 + 1] * 0x10000 + text[i*64 + j*4 + 2] * 0x100 + text[i*64 + j*4 + 3];
}
for(int j=16;j<80;j++)//ROTL(Wt−3 xor Wt−8 xor Wt−14 xor Wt−16) daca 16 <= t <= 79
{
word[j] = rotateleft((word[j-3] ^ word[j-8] ^ word[j-14] ^ word[j-16]),1);
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
for(int m=0;m<80;m++)
{
if(m<=19)
{
f = (b & c) | ((~b) & d);
k = 0x5A827999;
}
else if(m<=39)
{
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if(m<=59)
{
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
}
else
{
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
temp = (rotateleft(a,5) + f + e + k + word[m]) & 0xFFFFFFFF;
e = d;
d = c;
c = rotateleft(b,30);
b = a;
a = temp;
}
h0 = (h0 + a)&0xFFFFFFFF;
h1 = (h1 + b)&0xFFFFFFFF;
h2 = (h2 + c)&0xFFFFFFFF;
h3 = (h3 + d)&0xFFFFFFFF;
h4 = (h4 + e)&0xFFFFFFFF;
}
g<<hex<<showbase<<uppercase<<h0<<" "<<h1<<" "<<h2<<" "<<h3<<" "<<h4<<flush;
cout<<"Message : "<<txt<<endl;
cout<<"HASH : "<<hex<<showbase<<uppercase<<h0<<" "<<h1<<" "<<h2<<" "<<h3<<" "<<h4<<endl;
}
int main()
{
string in;
f>>in;
sha1((unsigned char *) in.c_str());
return 0;
}