sha2.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. using std::string;
  20. using std::min;
  21. class SHA512Summation;
  22. class SHA256Summation;
  23. typedef HashSumValue<512> SHA512SumValue;
  24. typedef HashSumValue<256> SHA256SumValue;
  25. class SHA2SummationBase
  26. {
  27. protected:
  28. bool Done;
  29. public:
  30. virtual bool Add(const unsigned char *inbuf,unsigned long inlen) = 0;
  31. virtual bool AddFD(int Fd,unsigned long Size);
  32. inline bool Add(const char *Data)
  33. {
  34. return Add((unsigned char *)Data,strlen(Data));
  35. };
  36. inline bool Add(const unsigned char *Beg,const unsigned char *End)
  37. {
  38. return Add(Beg,End-Beg);
  39. };
  40. void Result();
  41. };
  42. class SHA256Summation : public SHA2SummationBase
  43. {
  44. SHA256_CTX ctx;
  45. unsigned char Sum[32];
  46. public:
  47. virtual bool Add(const unsigned char *inbuf, unsigned long len)
  48. {
  49. if (Done)
  50. return false;
  51. SHA256_Update(&ctx, inbuf, len);
  52. return true;
  53. };
  54. SHA256SumValue Result()
  55. {
  56. if (!Done) {
  57. SHA256_Final(Sum, &ctx);
  58. Done = true;
  59. }
  60. SHA256SumValue res;
  61. res.Set(Sum);
  62. return res;
  63. };
  64. SHA256Summation()
  65. {
  66. SHA256_Init(&ctx);
  67. Done = false;
  68. };
  69. };
  70. class SHA512Summation : public SHA2SummationBase
  71. {
  72. SHA512_CTX ctx;
  73. unsigned char Sum[64];
  74. public:
  75. virtual bool Add(const unsigned char *inbuf, unsigned long len)
  76. {
  77. if (Done)
  78. return false;
  79. SHA512_Update(&ctx, inbuf, len);
  80. return true;
  81. };
  82. SHA512SumValue Result()
  83. {
  84. if (!Done) {
  85. SHA512_Final(Sum, &ctx);
  86. Done = true;
  87. }
  88. SHA512SumValue res;
  89. res.Set(Sum);
  90. return res;
  91. };
  92. SHA512Summation()
  93. {
  94. SHA512_Init(&ctx);
  95. Done = false;
  96. };
  97. };
  98. #endif