Version 5.15.0
[yaz-moved-to-github.git] / src / wrbuf_sha1.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file wrbuf_sha1.c
8  * \brief Implements SHA1 creation over WRBUF
9  */
10
11 #if HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18
19 #include <yaz/wrbuf.h>
20 #if HAVE_GCRYPT_H
21 #include <gcrypt.h>
22 #endif
23 #if HAVE_NETTLE
24 #include <nettle/sha.h>
25 #endif
26
27 int wrbuf_sha1_write(WRBUF b, const char *cp, size_t sz, int hexit)
28 {
29 #if HAVE_NETTLE
30     struct sha1_ctx ctx;
31     uint8_t digest[SHA1_DIGEST_SIZE];
32
33     sha1_init(&ctx);
34     sha1_update(&ctx, sz, (uint8_t *) cp);
35     sha1_digest(&ctx, SHA1_DIGEST_SIZE, digest);
36
37     if (hexit)
38     {
39         int i;
40         for (i = 0; i < SHA1_DIGEST_SIZE; i++)
41             wrbuf_printf(b, "%02x", digest[i]);
42     }
43     else
44         wrbuf_write(b, (const char *) digest, SHA1_DIGEST_SIZE);
45     return 0;
46 #elif HAVE_GCRYPT_H
47     gcry_error_t e;
48     gcry_md_hd_t hd;
49     const unsigned char *digest_buf;
50     int digest_len = gcry_md_get_algo_dlen(GCRY_MD_SHA1);
51
52     e = gcry_md_open(&hd, GCRY_MD_SHA1, 0);
53     if (e)
54         return -1;
55     gcry_md_write(hd, cp, sz);
56
57     digest_buf = gcry_md_read(hd, GCRY_MD_SHA1);
58     if (hexit)
59     {
60         int i;
61         for (i = 0; i < digest_len; i++)
62             wrbuf_printf(b, "%02x", digest_buf[i]);
63     }
64     else
65         wrbuf_write(b, (const char *) digest_buf, digest_len);
66     gcry_md_close(hd);
67     return 0;
68 #else
69     return -1;
70 #endif
71 }
72
73 int wrbuf_sha1_puts(WRBUF b, const char *cp, int hexit)
74 {
75     return wrbuf_sha1_write(b, cp, strlen(cp), hexit);
76 }
77
78 /*
79  * Local variables:
80  * c-basic-offset: 4
81  * c-file-style: "Stroustrup"
82  * indent-tabs-mode: nil
83  * End:
84  * vim: shiftwidth=4 tabstop=8 expandtab
85  */