1/*
2 Copyright (C) 2018 MariaDB Corporation AB
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public
15 License along with this library; if not see <http://www.gnu.org/licenses>
16 or write to the Free Software Foundation, Inc.,
17 51 Franklin St., Fifth Floor, Boston, MA 02110, USA
18*/
19#include <ma_global.h>
20#include <ma_crypt.h>
21#include <openssl/evp.h>
22
23static const EVP_MD *ma_hash_get_algorithm(unsigned int alg)
24{
25 switch(alg)
26 {
27 case MA_HASH_MD5:
28 return EVP_md5();
29 case MA_HASH_SHA1:
30 return EVP_sha1();
31 case MA_HASH_SHA224:
32 return EVP_sha224();
33 case MA_HASH_SHA256:
34 return EVP_sha256();
35 case MA_HASH_SHA384:
36 return EVP_sha384();
37 case MA_HASH_SHA512:
38 return EVP_sha512();
39 case MA_HASH_RIPEMD160:
40 return EVP_ripemd160();
41 default:
42 return NULL;
43 }
44}
45
46MA_HASH_CTX *ma_hash_new(unsigned int algorithm, MA_HASH_CTX *unused __attribute__((unused)))
47{
48 EVP_MD_CTX *ctx= NULL;
49 const EVP_MD *evp_md= ma_hash_get_algorithm(algorithm);
50
51 /* unknown or unsupported hash algorithm */
52 if (!evp_md)
53 return NULL;
54#if OPENSSL_VERSION_NUMBER >= 0x10100000L
55 if (!(ctx= EVP_MD_CTX_new()))
56#else
57 if (!(ctx= EVP_MD_CTX_create()))
58#endif
59 return NULL;
60 if (!EVP_DigestInit(ctx, evp_md))
61 {
62 ma_hash_free(ctx);
63 return NULL;
64 }
65 return ctx;
66}
67
68void ma_hash_free(MA_HASH_CTX *ctx)
69{
70 if (ctx)
71#if OPENSSL_VERSION_NUMBER >= 0x10100000L
72 EVP_MD_CTX_free(ctx);
73#else
74 EVP_MD_CTX_destroy(ctx);
75#endif
76}
77
78void ma_hash_input(MA_HASH_CTX *ctx,
79 const unsigned char *buffer,
80 size_t len)
81{
82 EVP_DigestUpdate(ctx, buffer, len);
83}
84
85void ma_hash_result(MA_HASH_CTX *ctx, unsigned char *digest)
86{
87 EVP_DigestFinal_ex(ctx, digest, NULL);
88}
89