sha2.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 <cstring>
  14. #include "sha2_internal.h"
  15. #include "hashsum_template.h"
  16. #ifndef APT_10_CLEANER_HEADERS
  17. #include <string>
  18. #include <algorithm>
  19. #include <stdint.h>
  20. #endif
  21. typedef HashSumValue<512> SHA512SumValue;
  22. typedef HashSumValue<256> SHA256SumValue;
  23. class SHA2SummationBase : public SummationImplementation
  24. {
  25. protected:
  26. bool Done;
  27. public:
  28. bool Add(const unsigned char *inbuf, unsigned long long len) APT_OVERRIDE APT_NONNULL(2) = 0;
  29. void Result();
  30. };
  31. class SHA256Summation : public SHA2SummationBase
  32. {
  33. SHA256_CTX ctx;
  34. unsigned char Sum[32];
  35. public:
  36. bool Add(const unsigned char *inbuf, unsigned long long len) APT_OVERRIDE APT_NONNULL(2)
  37. {
  38. if (Done)
  39. return false;
  40. SHA256_Update(&ctx, inbuf, len);
  41. return true;
  42. };
  43. using SummationImplementation::Add;
  44. SHA256SumValue Result()
  45. {
  46. if (!Done) {
  47. SHA256_Final(Sum, &ctx);
  48. Done = true;
  49. }
  50. SHA256SumValue res;
  51. res.Set(Sum);
  52. return res;
  53. };
  54. SHA256Summation()
  55. {
  56. SHA256_Init(&ctx);
  57. Done = false;
  58. memset(&Sum, 0, sizeof(Sum));
  59. };
  60. };
  61. class SHA512Summation : public SHA2SummationBase
  62. {
  63. SHA512_CTX ctx;
  64. unsigned char Sum[64];
  65. public:
  66. bool Add(const unsigned char *inbuf, unsigned long long len) APT_OVERRIDE APT_NONNULL(2)
  67. {
  68. if (Done)
  69. return false;
  70. SHA512_Update(&ctx, inbuf, len);
  71. return true;
  72. };
  73. using SummationImplementation::Add;
  74. SHA512SumValue Result()
  75. {
  76. if (!Done) {
  77. SHA512_Final(Sum, &ctx);
  78. Done = true;
  79. }
  80. SHA512SumValue res;
  81. res.Set(Sum);
  82. return res;
  83. };
  84. SHA512Summation()
  85. {
  86. SHA512_Init(&ctx);
  87. Done = false;
  88. memset(&Sum, 0, sizeof(Sum));
  89. };
  90. };
  91. #endif