Added new EVP/KDF API.
[openssl.git] / crypto / kdf / kdf_util.c
1 /*
2  * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2018, Oracle and/or its affiliates.  All rights reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <string.h>
12 #include <stdarg.h>
13 #include <openssl/kdf.h>
14 #include <openssl/evp.h>
15 #include "internal/cryptlib.h"
16 #include "internal/evp_int.h"
17 #include "internal/numbers.h"
18 #include "kdf_local.h"
19
20 int call_ctrl(int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
21               EVP_KDF_IMPL *impl, int cmd, ...)
22 {
23     int ret;
24     va_list args;
25
26     va_start(args, cmd);
27     ret = ctrl(impl, cmd, args);
28     va_end(args);
29
30     return ret;
31 }
32
33 /* Utility functions to send a string or hex string to a ctrl */
34
35 int kdf_str2ctrl(EVP_KDF_IMPL *impl,
36                  int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
37                  int cmd, const char *str)
38 {
39     return call_ctrl(ctrl, impl, cmd, (const unsigned char *)str, strlen(str));
40 }
41
42 int kdf_hex2ctrl(EVP_KDF_IMPL *impl,
43                  int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
44                  int cmd, const char *hex)
45 {
46     unsigned char *bin;
47     long binlen;
48     int ret = -1;
49
50     bin = OPENSSL_hexstr2buf(hex, &binlen);
51     if (bin == NULL)
52         return 0;
53
54     if (binlen <= INT_MAX)
55         ret = call_ctrl(ctrl, impl, cmd, bin, (size_t)binlen);
56     OPENSSL_free(bin);
57     return ret;
58 }
59
60 /* Pass a message digest to a ctrl */
61 int kdf_md2ctrl(EVP_KDF_IMPL *impl,
62                 int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
63                 int cmd, const char *md_name)
64 {
65     const EVP_MD *md;
66
67     if (md_name == NULL || (md = EVP_get_digestbyname(md_name)) == NULL) {
68         KDFerr(KDF_F_KDF_MD2CTRL, KDF_R_INVALID_DIGEST);
69         return 0;
70     }
71     return call_ctrl(ctrl, impl, cmd, md);
72 }
73