xref: /aosp_15_r20/external/angle/src/common/base/anglebase/sha1.h (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef ANGLEBASE_SHA1_H_
6 #define ANGLEBASE_SHA1_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <array>
12 #include <string>
13 
14 #include "anglebase/base_export.h"
15 
16 namespace angle
17 {
18 
19 namespace base
20 {
21 
22 // These functions perform SHA-1 operations.
23 
24 static const size_t kSHA1Length = 20;  // Length in bytes of a SHA-1 hash.
25 
26 // Computes the SHA-1 hash of the input string |str| and returns the full
27 // hash.
28 ANGLEBASE_EXPORT std::string SHA1HashString(const std::string &str);
29 
30 // Computes the SHA-1 hash of the |len| bytes in |data| and puts the hash
31 // in |hash|. |hash| must be kSHA1Length bytes long.
32 ANGLEBASE_EXPORT void SHA1HashBytes(const unsigned char *data, size_t len, unsigned char *hash);
33 
34 // Implementation of SHA-1. Only handles data in byte-sized blocks,
35 // which simplifies the code a fair bit.
36 
37 // Identifier names follow notation in FIPS PUB 180-3, where you'll
38 // also find a description of the algorithm:
39 // http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf
40 
41 // Usage example:
42 //
43 // SecureHashAlgorithm sha;
44 // while(there is data to hash)
45 //   sha.Update(moredata, size of data);
46 // sha.Final();
47 // memcpy(somewhere, sha.Digest(), 20);
48 //
49 // to reuse the instance of sha, call sha.Init();
50 
51 // TODO(jhawkins): Replace this implementation with a per-platform
52 // implementation using each platform's crypto library.  See
53 // http://crbug.com/47218
54 
55 class SecureHashAlgorithm
56 {
57   public:
SecureHashAlgorithm()58     SecureHashAlgorithm() { Init(); }
59 
60     static const int kDigestSizeBytes;
61 
62     void Init();
63     void Update(const void *data, size_t nbytes);
64     void Final();
65 
66     // 20 bytes of message digest.
Digest()67     const unsigned char *Digest() const { return reinterpret_cast<const unsigned char *>(H); }
68 
69     std::array<uint8_t, kSHA1Length> DigestAsArray() const;
70 
71   private:
72     void Pad();
73     void Process();
74 
75     uint32_t A, B, C, D, E;
76 
77     uint32_t H[5];
78 
79     union
80     {
81         uint32_t W[80];
82         uint8_t M[64];
83     };
84 
85     uint32_t cursor;
86     uint64_t l;
87 };
88 
89 }  // namespace base
90 
91 }  // namespace angle
92 
93 #endif  // ANGLEBASE_SHA1_H_
94