blob: 8131ba385b2770ed6e26daa6833f0b1be9c07cd0 [file] [log] [blame]
Alexandre Lisionddd731e2014-01-31 11:50:08 -05001// Copyright (C) 2010 David Sugar, Tycho Softworks.
2//
3// This file is part of GNU uCommon C++.
4//
5// GNU uCommon C++ is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published
7// by the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// GNU uCommon C++ 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 Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with GNU uCommon C++. If not, see <http://www.gnu.org/licenses/>.
17
18#include "local.h"
19
20bool HMAC::has(const char *id)
21{
22 return (EVP_get_digestbyname(id) != NULL);
23}
24
25void HMAC::set(const char *digest, const char *key, size_t len)
26{
27 secure::init();
28
29 release();
30
31 if(!len)
32 len = strlen(key);
33
34 hmactype = EVP_get_digestbyname(digest);
35 if(hmactype && len) {
36 context = new HMAC_CTX;
37 HMAC_CTX_init((HMAC_CTX *)context);
38 HMAC_Init((HMAC_CTX *)context, key, len, (const EVP_MD *)hmactype);
39 }
40}
41
42void HMAC::release(void)
43{
44 if(context)
45 HMAC_cleanup((HMAC_CTX *)context);
46
47 if(context) {
48 delete (HMAC_CTX *)context;
49 context = NULL;
50 }
51
52 bufsize = 0;
53 textbuf[0] = 0;
54}
55
56bool HMAC::put(const void *address, size_t size)
57{
58 if(!context)
59 return false;
60
61 HMAC_Update((HMAC_CTX *)context, (const unsigned char *)address, size);
62 return true;
63}
64
65const unsigned char *HMAC::get(void)
66{
67 unsigned count = 0;
68 unsigned size = 0;
69
70 if(bufsize)
71 return buffer;
72
73 if(!context)
74 return NULL;
75
76 HMAC_Final((HMAC_CTX *)context, buffer, &size);
77 release();
78
79 if(!size)
80 return NULL;
81
82 bufsize = size;
83
84 while(count < bufsize) {
85 snprintf(textbuf + (count * 2), 3, "%2.2x",
86buffer[count]);
87 ++count;
88 }
89 return buffer;
90}
91