You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.6 KiB

7 years ago
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <string>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <stdint.h>
  7. #include "genSha1.h"
  8. #define rol(x,n) ((x << n) | (x >> (32-n)))
  9. void getSha1FromBlock(unsigned char* str, uint32_t &h0, uint32_t &h1, //obliczenia na każdym bloku
  10. uint32_t &h2, uint32_t &h3, uint32_t &h4){
  11. uint32_t *w, a, b, c, d, e, k, f, tmp;
  12. w = new uint32_t[80];
  13. for(int j = 0; j < 16; j++){
  14. w[j] = str[j*4 + 0] * 0x1000000 //ustawianie szesnastu 32-bitowych słów
  15. + str[j*4 + 1] * 0x10000
  16. + str[j*4 + 2] * 0x100
  17. + str[j*4 + 3];
  18. }
  19. for(int j = 16; j < 80; j++){ //rozszerzanie szesnastu słów do osiemdziesięciu
  20. w[j] = rol((w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]),1);
  21. }
  22. a = h0; //inicjalizacja a,b,c,d,e
  23. b = h1;
  24. c = h2;
  25. d = h3;
  26. e = h4;
  27. for(int m=0;m<80;m++){ //działania...
  28. if(m <= 19){
  29. f = (b & c) | ((~b) & d);
  30. k = 0x5A827999;
  31. } else if(m <= 39){
  32. f = b ^ c ^ d;
  33. k = 0x6ED9EBA1;
  34. } else if(m <= 59){
  35. f = (b & c) | (b & d) | (c & d);
  36. k = 0x8F1BBCDC;
  37. } else {
  38. f = b ^ c ^ d;
  39. k = 0xCA62C1D6;
  40. }
  41. tmp = (rol(a,5) + f + e + k + w[m]);
  42. e = d;
  43. d = c;
  44. c = rol(b,30);
  45. b = a;
  46. a = tmp;
  47. }
  48. h0 = h0 + a; //przypis wartości
  49. h1 = h1 + b;
  50. h2 = h2 + c;
  51. h3 = h3 + d;
  52. h4 = h4 + e;
  53. delete[] w;
  54. }
  55. void sha1(unsigned char* message,unsigned short messageLength,char *result){
  56. int size = 64; //rozmiar jednego bloku musi być 512bit
  57. unsigned char *block;
  58. block = new unsigned char[size];
  59. memset(block,0,size);
  60. memcpy(block, message,messageLength* sizeof(char));
  61. block[messageLength] = 0x80;//tuż po zakończeniu wiadomości dodaje bity 10000000
  62. messageLength =messageLength* sizeof(char)*8; //rozmiar wiadomości w bitach
  63. block[63] = messageLength; // rozmiar wiadomość zapisany jako big-endian
  64. block[62] = messageLength >> 8;
  65. uint32_t h0, h1, h2, h3, h4; //wartości początkowe (z wikipedii)
  66. h0 = 0x67452301;
  67. h1 = 0xEFCDAB89;
  68. h2 = 0x98BADCFE;
  69. h3 = 0x10325476;
  70. h4 = 0xC3D2E1F0;
  71. getSha1FromBlock(block, h0, h1, h2, h3, h4);
  72. sprintf(result, "%08x%08x%08x%08x%08x", h0, h1, h2, h3, h4);
  73. delete[] block;
  74. }