hash.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. 20080913
  3. D. J. Bernstein
  4. Public domain.
  5. */
  6. #include "crypto_hashblocks_sha256.h"
  7. #include "crypto_hash.h"
  8. #define blocks crypto_hashblocks_sha256
  9. typedef unsigned int uint32;
  10. static const char iv[32] = {
  11. 0x6a,0x09,0xe6,0x67,
  12. 0xbb,0x67,0xae,0x85,
  13. 0x3c,0x6e,0xf3,0x72,
  14. 0xa5,0x4f,0xf5,0x3a,
  15. 0x51,0x0e,0x52,0x7f,
  16. 0x9b,0x05,0x68,0x8c,
  17. 0x1f,0x83,0xd9,0xab,
  18. 0x5b,0xe0,0xcd,0x19,
  19. } ;
  20. int crypto_hash(unsigned char *out,const unsigned char *in,unsigned long long inlen)
  21. {
  22. unsigned char h[32];
  23. unsigned char padded[128];
  24. int i;
  25. unsigned long long bits = inlen << 3;
  26. for (i = 0;i < 32;++i) h[i] = iv[i];
  27. blocks(h,in,inlen);
  28. in += inlen;
  29. inlen &= 63;
  30. in -= inlen;
  31. for (i = 0;i < inlen;++i) padded[i] = in[i];
  32. padded[inlen] = 0x80;
  33. if (inlen < 56) {
  34. for (i = inlen + 1;i < 56;++i) padded[i] = 0;
  35. padded[56] = bits >> 56;
  36. padded[57] = bits >> 48;
  37. padded[58] = bits >> 40;
  38. padded[59] = bits >> 32;
  39. padded[60] = bits >> 24;
  40. padded[61] = bits >> 16;
  41. padded[62] = bits >> 8;
  42. padded[63] = bits;
  43. blocks(h,padded,64);
  44. } else {
  45. for (i = inlen + 1;i < 120;++i) padded[i] = 0;
  46. padded[120] = bits >> 56;
  47. padded[121] = bits >> 48;
  48. padded[122] = bits >> 40;
  49. padded[123] = bits >> 32;
  50. padded[124] = bits >> 24;
  51. padded[125] = bits >> 16;
  52. padded[126] = bits >> 8;
  53. padded[127] = bits;
  54. blocks(h,padded,128);
  55. }
  56. for (i = 0;i < 32;++i) out[i] = h[i];
  57. return 0;
  58. }