2 digest.c -- Digest handling
3 Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
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 2 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, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 {"none", GCRY_MD_NONE, 0},
33 {"sha1", GCRY_MD_SHA1, 64},
34 {"sha256", GCRY_MD_SHA256, 672},
35 {"sha384", GCRY_MD_SHA384, 673},
36 {"sha512", GCRY_MD_SHA512, 674},
39 static bool nametodigest(const char *name, int *algo) {
42 for(i = 0; i < sizeof digesttable / sizeof *digesttable; i++) {
43 if(digesttable[i].name && !strcasecmp(name, digesttable[i].name)) {
44 *algo = digesttable[i].algo;
52 static bool nidtodigest(int nid, int *algo) {
55 for(i = 0; i < sizeof digesttable / sizeof *digesttable; i++) {
56 if(nid == digesttable[i].nid) {
57 *algo = digesttable[i].algo;
65 static bool digesttonid(int algo, int *nid) {
68 for(i = 0; i < sizeof digesttable / sizeof *digesttable; i++) {
69 if(algo == digesttable[i].algo) {
70 *nid = digesttable[i].nid;
78 static bool digest_open(digest_t *digest, int algo) {
79 if(!digesttonid(algo, &digest->nid)) {
80 logger(LOG_DEBUG, _("Digest %d has no corresponding nid!"), algo);
84 digest->len = gcry_md_get_algo_dlen(algo);
89 bool digest_open_by_name(digest_t *digest, const char *name) {
92 if(!nametodigest(name, &algo)) {
93 logger(LOG_DEBUG, _("Unknown digest name '%s'!"), name);
97 return digest_open(digest, algo);
100 bool digest_open_by_nid(digest_t *digest, int nid) {
103 if(!nidtodigest(nid, &algo)) {
104 logger(LOG_DEBUG, _("Unknown digest ID %d!"), nid);
108 return digest_open(digest, algo);
111 bool digest_open_sha1(digest_t *digest) {
112 return digest_open(digest, GCRY_MD_SHA1);
115 void digest_close(digest_t *digest) {
118 bool digest_create(digest_t *digest, const void *indata, size_t inlen, void *outdata) {
119 gcry_md_hash_buffer(digest->algo, outdata, indata, inlen);
123 bool digest_verify(digest_t *digest, const void *indata, size_t inlen, const void *cmpdata) {
124 char outdata[digest->len];
126 gcry_md_hash_buffer(digest->algo, outdata, indata, inlen);
127 return !memcmp(cmpdata, outdata, digest->len);
130 int digest_get_nid(const digest_t *digest) {
134 size_t digest_length(const digest_t *digest) {
138 bool digest_active(const digest_t *digest) {
139 return digest->algo != GCRY_MD_NONE;