2 * Copyright (C) 2008-2017 Tobias Brunner
3 * HSR Hochschule fuer Technik Rapperswil
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 #include "openssl_hasher.h"
18 #include <openssl/evp.h>
20 typedef struct private_openssl_hasher_t private_openssl_hasher_t
;
23 * Private data of openssl_hasher_t
25 struct private_openssl_hasher_t
{
28 * Public part of this class.
30 openssl_hasher_t
public;
38 * the current digest context
43 METHOD(hasher_t
, get_hash_size
, size_t,
44 private_openssl_hasher_t
*this)
46 return EVP_MD_size(this->hasher
);
49 METHOD(hasher_t
, reset
, bool,
50 private_openssl_hasher_t
*this)
52 return EVP_DigestInit_ex(this->ctx
, this->hasher
, NULL
) == 1;
55 METHOD(hasher_t
, get_hash
, bool,
56 private_openssl_hasher_t
*this, chunk_t chunk
, uint8_t *hash
)
58 if (EVP_DigestUpdate(this->ctx
, chunk
.ptr
, chunk
.len
) != 1)
64 if (EVP_DigestFinal_ex(this->ctx
, hash
, NULL
) != 1)
73 METHOD(hasher_t
, allocate_hash
, bool,
74 private_openssl_hasher_t
*this, chunk_t chunk
, chunk_t
*hash
)
78 *hash
= chunk_alloc(get_hash_size(this));
79 return get_hash(this, chunk
, hash
->ptr
);
81 return get_hash(this, chunk
, NULL
);
84 METHOD(hasher_t
, destroy
, void,
85 private_openssl_hasher_t
*this)
87 EVP_MD_CTX_destroy(this->ctx
);
94 const EVP_MD
*openssl_get_md(hash_algorithm_t hash
)
99 name
= strdupnull(enum_to_name(hash_algorithm_short_names
, hash
));
104 /* for SHA3, we use underscores, while OpenSSL uses dashes */
105 translate(name
, "_", "-");
106 md
= EVP_get_digestbyname(name
);
112 * Described in header
114 openssl_hasher_t
*openssl_hasher_create(hash_algorithm_t algo
)
116 private_openssl_hasher_t
*this;
121 .get_hash
= _get_hash
,
122 .allocate_hash
= _allocate_hash
,
123 .get_hash_size
= _get_hash_size
,
130 this->hasher
= openssl_get_md(algo
);
133 /* OpenSSL does not support the requested algo */
138 this->ctx
= EVP_MD_CTX_create();
147 return &this->public;