#include <stdio.h>
|
|
#include <iostream>
|
|
#include <string>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdint.h>
|
|
#include "genSha1.h"
|
|
|
|
#define rol(x,n) ((x << n) | (x >> (32-n)))
|
|
|
|
|
|
void getSha1FromBlock(unsigned char* str, uint32_t &h0, uint32_t &h1, //obliczenia na każdym bloku
|
|
uint32_t &h2, uint32_t &h3, uint32_t &h4){
|
|
|
|
uint32_t *w, a, b, c, d, e, k, f, tmp;
|
|
w = new uint32_t[80];
|
|
|
|
for(int j = 0; j < 16; j++){
|
|
w[j] = str[j*4 + 0] * 0x1000000 //ustawianie szesnastu 32-bitowych słów
|
|
+ str[j*4 + 1] * 0x10000
|
|
+ str[j*4 + 2] * 0x100
|
|
+ str[j*4 + 3];
|
|
}
|
|
|
|
|
|
for(int j = 16; j < 80; j++){ //rozszerzanie szesnastu słów do osiemdziesięciu
|
|
w[j] = rol((w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]),1);
|
|
}
|
|
|
|
a = h0; //inicjalizacja a,b,c,d,e
|
|
b = h1;
|
|
c = h2;
|
|
d = h3;
|
|
e = h4;
|
|
|
|
for(int m=0;m<80;m++){ //działania...
|
|
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;
|
|
}
|
|
|
|
tmp = (rol(a,5) + f + e + k + w[m]);
|
|
e = d;
|
|
d = c;
|
|
c = rol(b,30);
|
|
b = a;
|
|
a = tmp;
|
|
}
|
|
|
|
h0 = h0 + a; //przypis wartości
|
|
h1 = h1 + b;
|
|
h2 = h2 + c;
|
|
h3 = h3 + d;
|
|
h4 = h4 + e;
|
|
|
|
delete[] w;
|
|
}
|
|
|
|
void sha1(unsigned char* message,unsigned short messageLength,char *result){
|
|
|
|
int size = 64; //rozmiar jednego bloku musi być 512bit
|
|
unsigned char *block;
|
|
|
|
block = new unsigned char[size];
|
|
memset(block,0,size);
|
|
memcpy(block, message,messageLength* sizeof(char));
|
|
block[messageLength] = 0x80;//tuż po zakończeniu wiadomości dodaje bity 10000000
|
|
messageLength =messageLength* sizeof(char)*8; //rozmiar wiadomości w bitach
|
|
block[63] = messageLength; // rozmiar wiadomość zapisany jako big-endian
|
|
block[62] = messageLength >> 8;
|
|
|
|
|
|
uint32_t h0, h1, h2, h3, h4; //wartości początkowe (z wikipedii)
|
|
h0 = 0x67452301;
|
|
h1 = 0xEFCDAB89;
|
|
h2 = 0x98BADCFE;
|
|
h3 = 0x10325476;
|
|
h4 = 0xC3D2E1F0;
|
|
|
|
getSha1FromBlock(block, h0, h1, h2, h3, h4);
|
|
sprintf(result, "%08x%08x%08x%08x%08x", h0, h1, h2, h3, h4);
|
|
|
|
delete[] block;
|
|
|
|
|
|
}
|