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.
28 enum gcry_md_algos algo,
31 {"none", GCRY_MD_NONE, 0},
32 {"sha1", GCRY_MD_SHA1, 64},
33 {"sha256", GCRY_MD_SHA256, 672},
34 {"sha384", GCRY_MD_SHA384, 673},
35 {"sha512", GCRY_MD_SHA512, 674},
38 static bool nidtodigest(int nid, enum gcry_md_algos *algo) {
41 for(i = 0; i < sizeof digesttable / sizeof *digesttable; i++) {
42 if(nid == digesttable[i].nid) {
43 *algo = digesttable[i].algo;
51 static bool digesttonid(enum gcry_md_algos algo, int *nid) {
54 for(i = 0; i < sizeof digesttable / sizeof *digesttable; i++) {
55 if(algo == digesttable[i].algo) {
56 *nid = digesttable[i].nid;
64 static bool digest_open(digest_t *digest, int algo) {
65 if(!digesttonid(algo, &digest->nid)) {
66 logger(LOG_DEBUG< _("Digest %d has no corresponding nid!"), algo);
70 digest->len = gcry_md_get_algo_dlen(algo);
75 bool digest_open_by_name(digest_t *digest, const char *name) {
78 if(!nametodigest(name, &algo)) {
79 logger(LOG_DEBUG, _("Unknown digest name '%s'!"), name);
83 return digest_open(digest, algo);
86 bool digest_open_by_nid(digest_t *digest, int nid) {
89 if(!nidtodigest(nid, &algo)) {
90 logger(LOG_DEBUG, _("Unknown digest ID %d!"), nid);
94 return digest_open(digest, algo, mode);
97 bool digest_open_sha1(digest_t *digest) {
98 return digest_open(digest, GCRY_MD_SHA1);
101 void digest_close(digest_t *digest) {
104 bool digest_create(digest_t *digest, void *indata, size_t inlen, void *outdata) {
107 if((err = gcry_md_hash_buffer(digest->algo, outdata, indata, inlen))) {
108 logger(LOG_ERR, _("Error while creating digest!"));
112 *outlen = digest->len;
116 bool digest_verify(digest_t *digest, void *indata, size_t inlen, void *cmpdata) {
118 char outdata[digest->len];
120 if((err = gcry_md_hash_buffer(digest->algo, outdata, indata, inlen))) {
121 logger(LOG_ERR, _("Error while creating digest!"));
125 return !memcmp(indata, outdata, digest->len);
128 int digest_get_nid(digest_t *digest) {