1 /* sha1.c - Interfaces to SHA-1 hash for the notmuch mail system
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "notmuch-private.h"
25 /* Just some simple interfaces on top of libsha1 so that we can leave
26 * libsha1 as untouched as possible. */
29 _hex_of_sha1_digest (const unsigned char digest[SHA1_DIGEST_SIZE])
34 result = xcalloc (SHA1_DIGEST_SIZE * 2 + 1, 1);
36 for (r = result, i = 0;
40 sprintf (r, "%02x", digest[i]);
46 /* Create a hexadecimal string version of the SHA-1 digest of 'str'
47 * (including its null terminating character).
49 * This function returns a newly allocated string which the caller
50 * should free() when finished.
53 _notmuch_sha1_of_string (const char *str)
56 unsigned char digest[SHA1_DIGEST_SIZE];
60 sha1_hash ((unsigned char *) str, strlen (str) + 1, &sha1);
62 sha1_end (digest, &sha1);
64 return _hex_of_sha1_digest (digest);
67 /* Create a hexadecimal string version of the SHA-1 digest of the
68 * contents of the named file.
70 * This function returns a newly allocated string which the caller
71 * should free() when finished.
73 * If any error occurs while reading the file, (permission denied,
74 * file not found, etc.), this function returns NULL.
77 _notmuch_sha1_of_file (const char *filename)
80 #define BLOCK_SIZE 4096
81 unsigned char block[BLOCK_SIZE];
84 unsigned char digest[SHA1_DIGEST_SIZE];
87 file = fopen (filename, "r");
94 bytes_read = fread (block, 1, 4096, file);
95 if (bytes_read == 0) {
98 } else if (ferror (file)) {
103 sha1_hash (block, bytes_read, &sha1);
107 sha1_end (digest, &sha1);
109 result = _hex_of_sha1_digest (digest);