]> wimlib.net Git - wimlib/blob - include/wimlib/sha1.h
Place headers that could be useful in unrelated projects in public domain
[wimlib] / include / wimlib / sha1.h
1 /*
2  * sha1.h
3  *
4  * The author dedicates this file to the public domain.
5  * You can do whatever you want with this file.
6  */
7
8 #ifndef _WIMLIB_SHA1_H
9 #define _WIMLIB_SHA1_H
10
11 #include "wimlib/types.h"
12 #include "wimlib/util.h"
13
14 #include <string.h>
15
16 #define SHA1_HASH_SIZE 20
17
18 extern const u8 zero_hash[SHA1_HASH_SIZE];
19
20 static inline void
21 copy_hash(u8 dest[SHA1_HASH_SIZE], const u8 src[SHA1_HASH_SIZE])
22 {
23         memcpy(dest, src, SHA1_HASH_SIZE);
24 }
25
26 static inline void
27 random_hash(u8 hash[SHA1_HASH_SIZE])
28 {
29         randomize_byte_array(hash, SHA1_HASH_SIZE);
30 }
31
32 static inline int
33 hashes_cmp(const u8 h1[SHA1_HASH_SIZE], const u8 h2[SHA1_HASH_SIZE])
34 {
35         return memcmp(h1, h2, SHA1_HASH_SIZE);
36 }
37
38 static inline bool
39 hashes_equal(const u8 h1[SHA1_HASH_SIZE], const u8 h2[SHA1_HASH_SIZE])
40 {
41         return !hashes_cmp(h1, h2);
42 }
43
44 static inline void
45 print_hash(const u8 hash[SHA1_HASH_SIZE], FILE *out)
46 {
47         print_byte_field(hash, SHA1_HASH_SIZE, out);
48 }
49
50 static inline bool
51 is_zero_hash(const u8 *hash)
52 {
53         return (hash == zero_hash || hashes_equal(hash, zero_hash));
54 }
55
56 static inline void
57 zero_out_hash(u8 hash[SHA1_HASH_SIZE])
58 {
59         copy_hash(hash, zero_hash);
60 }
61
62 #ifdef WITH_LIBCRYPTO
63
64 #include <openssl/sha.h>
65
66 #define sha1_init     SHA1_Init
67 #define sha1_update   SHA1_Update
68 #define sha1_final    SHA1_Final
69
70 static inline void
71 sha1_buffer(const void *buffer, size_t len, u8 hash[SHA1_HASH_SIZE])
72 {
73         SHA1(buffer, len, hash);
74 }
75
76 #else /* WITH_LIBCRYPTO */
77
78 typedef struct {
79         u64 bytecount;
80         u32 state[5];
81         u8 buffer[64];
82 } SHA_CTX;
83
84 extern void
85 sha1_init(SHA_CTX *ctx);
86
87 extern void
88 sha1_update(SHA_CTX *ctx, const void *data, size_t len);
89
90 extern void
91 sha1_final(u8 hash[SHA1_HASH_SIZE], SHA_CTX *ctx);
92
93 extern void
94 sha1_buffer(const void *buffer, size_t len, u8 hash[SHA1_HASH_SIZE]);
95
96 #endif /* !WITH_LIBCRYPTO */
97
98 #endif /* _WIMLIB_SHA1_H */