Merge branch 'master' into 1.1
[tinc] / src / openssl / digest.c
1 /*
2     digest.c -- Digest handling
3     Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
4
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.
9
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.
14
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.
18
19     $Id$
20 */
21
22 #include "system.h"
23
24 #include <openssl/err.h>
25
26 #include "digest.h"
27 #include "logger.h"
28
29 bool digest_open_by_name(digest_t *digest, const char *name) {
30         digest->digest = EVP_get_digestbyname(name);
31         if(digest->digest)
32                 return true;
33
34         logger(LOG_DEBUG, _("Unknown digest name '%s'!"), name);
35         return false;
36 }
37
38 bool digest_open_by_nid(digest_t *digest, int nid) {
39         digest->digest = EVP_get_digestbynid(nid);
40         if(digest->digest)
41                 return true;
42
43         logger(LOG_DEBUG, _("Unknown digest nid %d!"), nid);
44         return false;
45 }
46
47 bool digest_open_sha1(digest_t *digest) {
48         digest->digest = EVP_sha1();
49         return true;
50 }
51
52 void digest_close(digest_t *digest) {
53 }
54
55 bool digest_create(digest_t *digest, const void *indata, size_t inlen, void *outdata) {
56         EVP_MD_CTX ctx;
57
58         if(EVP_DigestInit(&ctx, digest->digest)
59                         && EVP_DigestUpdate(&ctx, indata, inlen)
60                         && EVP_DigestFinal(&ctx, outdata, NULL))
61                 return true;
62         
63         logger(LOG_DEBUG, _("Error creating digest: %s"), ERR_error_string(ERR_get_error(), NULL));
64         return false;
65 }
66
67 bool digest_verify(digest_t *digest, const void *indata, size_t inlen, const void *cmpdata) {
68         size_t len = EVP_MD_size(digest->digest);
69         char outdata[len];
70
71         return digest_create(digest, indata, inlen, outdata) && !memcmp(cmpdata, outdata, len);
72 }
73
74 int digest_get_nid(const digest_t *digest) {
75         return digest->digest ? digest->digest->type : 0;
76 }
77
78 size_t digest_length(const digest_t *digest) {
79         return EVP_MD_size(digest->digest);
80 }
81
82 bool digest_active(const digest_t *digest) {
83         return digest->digest && digest->digest->type != 0;
84 }