sha2.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: sha512.h,v 1.3 2001/05/07 05:05:47 jgg Exp $
  4. /* ######################################################################
  5. SHA{512,256}SumValue - Storage for a SHA-{512,256} hash.
  6. SHA{512,256}Summation - SHA-{512,256} Secure Hash Algorithm.
  7. This is a C++ interface to a set of SHA{512,256}Sum functions, that mirrors
  8. the equivalent MD5 & SHA1 classes.
  9. ##################################################################### */
  10. /*}}}*/
  11. #ifndef APTPKG_SHA2_H
  12. #define APTPKG_SHA2_H
  13. #include <string>
  14. #include <cstring>
  15. #include <algorithm>
  16. #include <stdint.h>
  17. #include "sha2_internal.h"
  18. #include "hashsum_template.h"
  19. typedef HashSumValue<512> SHA512SumValue;
  20. typedef HashSumValue<256> SHA256SumValue;
  21. class SHA2SummationBase : public SummationImplementation
  22. {
  23. protected:
  24. bool Done;
  25. public:
  26. bool Add(const unsigned char *inbuf, unsigned long long len) = 0;
  27. void Result();
  28. };
  29. class SHA256Summation : public SHA2SummationBase
  30. {
  31. SHA256_CTX ctx;
  32. unsigned char Sum[32];
  33. public:
  34. bool Add(const unsigned char *inbuf, unsigned long long len)
  35. {
  36. if (Done)
  37. return false;
  38. SHA256_Update(&ctx, inbuf, len);
  39. return true;
  40. };
  41. using SummationImplementation::Add;
  42. SHA256SumValue Result()
  43. {
  44. if (!Done) {
  45. SHA256_Final(Sum, &ctx);
  46. Done = true;
  47. }
  48. SHA256SumValue res;
  49. res.Set(Sum);
  50. return res;
  51. };
  52. SHA256Summation()
  53. {
  54. SHA256_Init(&ctx);
  55. Done = false;
  56. memset(&Sum, 0, sizeof(Sum));
  57. };
  58. };
  59. class SHA512Summation : public SHA2SummationBase
  60. {
  61. SHA512_CTX ctx;
  62. unsigned char Sum[64];
  63. public:
  64. bool Add(const unsigned char *inbuf, unsigned long long len)
  65. {
  66. if (Done)
  67. return false;
  68. SHA512_Update(&ctx, inbuf, len);
  69. return true;
  70. };
  71. using SummationImplementation::Add;
  72. SHA512SumValue Result()
  73. {
  74. if (!Done) {
  75. SHA512_Final(Sum, &ctx);
  76. Done = true;
  77. }
  78. SHA512SumValue res;
  79. res.Set(Sum);
  80. return res;
  81. };
  82. SHA512Summation()
  83. {
  84. SHA512_Init(&ctx);
  85. Done = false;
  86. memset(&Sum, 0, sizeof(Sum));
  87. };
  88. };
  89. #endif