2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <openssl/evp.h>
29 inline std::string pdns_hash(const EVP_MD * md, const std::string& input)
31 #if OPENSSL_VERSION_NUMBER < 0x1010000fL
32 auto mdctx = std::unique_ptr<EVP_MD_CTX, void(*)(EVP_MD_CTX*)>(EVP_MD_CTX_create(), EVP_MD_CTX_destroy);
34 auto mdctx = std::unique_ptr<EVP_MD_CTX, void(*)(EVP_MD_CTX*)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
37 throw std::runtime_error(std::string(EVP_MD_name(md)) + " context initialization failed");
40 if (EVP_DigestInit_ex(mdctx.get(), md, nullptr) != 1) {
41 throw std::runtime_error(std::string(EVP_MD_name(md)) + " EVP initialization failed");
44 if (EVP_DigestUpdate(mdctx.get(), input.data(), input.size()) != 1) {
45 throw std::runtime_error(std::string(EVP_MD_name(md)) + " EVP update failed");
50 result.resize(EVP_MD_size(md));
52 if (EVP_DigestFinal_ex(mdctx.get(), const_cast<unsigned char *>(reinterpret_cast<const unsigned char*>(result.c_str())), &written) != 1) {
53 throw std::runtime_error(std::string(EVP_MD_name(md)) + " EVP final failed");
56 if (written != result.size()) {
57 throw std::runtime_error(std::string(EVP_MD_name(md)) + " EVP final wrote " + std::to_string(written) + ", expected " + std::to_string(result.size()));
63 inline std::string pdns_md5sum(const std::string& input)
65 const auto md = EVP_md5();
67 throw std::runtime_error("The MD5 digest is not available via the OpenSSL EVP interface");
70 return pdns_hash(md, input);
73 inline std::string pdns_sha1sum(const std::string& input)
75 const auto md = EVP_sha1();
77 throw std::runtime_error("The SHA1 digest is not available via the OpenSSL EVP interface");
80 return pdns_hash(md, input);