• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //==- SHA1.h - SHA1 implementation for LLVM                     --*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // This code is taken from public domain
10 // (http://oauth.googlecode.com/svn/code/c/liboauth/src/sha1.c)
11 // and modified by wrapping it in a C++ interface for LLVM,
12 // and removing unnecessary code.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_SUPPORT_SHA1_H
17 #define LLVM_SUPPORT_SHA1_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 
21 #include <cstdint>
22 
23 namespace llvm {
24 template <typename T> class ArrayRef;
25 class StringRef;
26 
27 /// A class that wrap the SHA1 algorithm.
28 class SHA1 {
29 public:
SHA1()30   SHA1() { init(); }
31 
32   /// Reinitialize the internal state
33   void init();
34 
35   /// Digest more data.
36   void update(ArrayRef<uint8_t> Data);
37 
38   /// Digest more data.
update(StringRef Str)39   void update(StringRef Str) {
40     update(ArrayRef<uint8_t>((uint8_t *)const_cast<char *>(Str.data()),
41                              Str.size()));
42   }
43 
44   /// Return a reference to the current raw 160-bits SHA1 for the digested data
45   /// since the last call to init(). This call will add data to the internal
46   /// state and as such is not suited for getting an intermediate result
47   /// (see result()).
48   StringRef final();
49 
50   /// Return a reference to the current raw 160-bits SHA1 for the digested data
51   /// since the last call to init(). This is suitable for getting the SHA1 at
52   /// any time without invalidating the internal state so that more calls can be
53   /// made into update.
54   StringRef result();
55 
56 private:
57   /// Define some constants.
58   /// "static constexpr" would be cleaner but MSVC does not support it yet.
59   enum { BLOCK_LENGTH = 64 };
60   enum { HASH_LENGTH = 20 };
61 
62   // Internal State
63   struct {
64     uint32_t Buffer[BLOCK_LENGTH / 4];
65     uint32_t State[HASH_LENGTH / 4];
66     uint32_t ByteCount;
67     uint8_t BufferOffset;
68   } InternalState;
69 
70   // Internal copy of the hash, populated and accessed on calls to result()
71   uint32_t HashResult[HASH_LENGTH / 4];
72 
73   // Helper
74   void writebyte(uint8_t data);
75   void hashBlock();
76   void addUncounted(uint8_t data);
77   void pad();
78 };
79 
80 } // end llvm namespace
81 
82 #endif
83