summaryrefslogtreecommitdiff
path: root/apt-pkg/contrib/sha2.h
blob: 8e0c99a1b6631d1e3ff74d5207f8a08f3a8dee91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// -*- mode: cpp; mode: fold -*-
// Description                                                          /*{{{*/
// $Id: sha512.h,v 1.3 2001/05/07 05:05:47 jgg Exp $
/* ######################################################################

   SHA{512,256}SumValue - Storage for a SHA-{512,256} hash.
   SHA{512,256}Summation - SHA-{512,256} Secure Hash Algorithm.
   
   This is a C++ interface to a set of SHA{512,256}Sum functions, that mirrors
   the equivalent MD5 & SHA1 classes. 

   ##################################################################### */
                                                                        /*}}}*/
#ifndef APTPKG_SHA2_H
#define APTPKG_SHA2_H

#include <string>
#include <cstring>
#include <algorithm>
#include <stdint.h>

#include "sha2_internal.h"
#include "hashsum_template.h"

typedef HashSumValue<512> SHA512SumValue;
typedef HashSumValue<256> SHA256SumValue;

class SHA2SummationBase : public SummationImplementation
{
 protected:
   bool Done;
 public:
   bool Add(const unsigned char *inbuf, unsigned long long len) = 0;

   void Result();
};

class SHA256Summation : public SHA2SummationBase
{
   SHA256_CTX ctx;
   unsigned char Sum[32];

   public:
   bool Add(const unsigned char *inbuf, unsigned long long len)
   {
      if (Done) 
         return false;
      SHA256_Update(&ctx, inbuf, len);
      return true;
   };
   using SummationImplementation::Add;

   SHA256SumValue Result()
   {
      if (!Done) {
         SHA256_Final(Sum, &ctx);
         Done = true;
      }
      SHA256SumValue res;
      res.Set(Sum);
      return res;
   };
   SHA256Summation()
   {
      SHA256_Init(&ctx);
      Done = false;
      memset(&Sum, 0, sizeof(Sum));
   };
};

class SHA512Summation : public SHA2SummationBase
{
   SHA512_CTX ctx;
   unsigned char Sum[64];

   public:
   bool Add(const unsigned char *inbuf, unsigned long long len)
   {
      if (Done) 
         return false;
      SHA512_Update(&ctx, inbuf, len);
      return true;
   };
   using SummationImplementation::Add;

   SHA512SumValue Result()
   {
      if (!Done) {
         SHA512_Final(Sum, &ctx);
         Done = true;
      }
      SHA512SumValue res;
      res.Set(Sum);
      return res;
   };
   SHA512Summation()
   {
      SHA512_Init(&ctx);
      Done = false;
      memset(&Sum, 0, sizeof(Sum));
   };
};


#endif