2 * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
14 #include <openssl/bio.h>
15 #include <openssl/err.h>
16 #include <openssl/evp.h>
17 #include <openssl/kdf.h>
18 #include <openssl/params.h>
20 typedef enum OPTION_choice {
21 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
22 OPT_KDFOPT, OPT_BIN, OPT_KEYLEN, OPT_OUT,
26 const OPTIONS kdf_options[] = {
27 {OPT_HELP_STR, 1, '-', "Usage: %s [options] kdf_name\n"},
29 OPT_SECTION("General"),
30 {"help", OPT_HELP, '-', "Display this summary"},
31 {"kdfopt", OPT_KDFOPT, 's', "KDF algorithm control parameters in n:v form"},
32 {OPT_MORE_STR, 1, '-', "See 'Supported Controls' in the EVP_KDF_ docs\n"},
33 {"keylen", OPT_KEYLEN, 's', "The size of the output derived key"},
35 OPT_SECTION("Output"),
36 {"out", OPT_OUT, '>', "Output to filename rather than stdout"},
37 {"binary", OPT_BIN, '-',
38 "Output in binary format (default is hexadecimal)"},
43 {"kdf_name", 0, 0, "Name of the KDF algorithm"},
47 int kdf_main(int argc, char **argv)
49 int ret = 1, out_bin = 0;
51 STACK_OF(OPENSSL_STRING) *opts = NULL;
52 char *prog, *hexout = NULL;
53 const char *outfile = NULL;
54 unsigned char *dkm_bytes = NULL;
58 EVP_KDF_CTX *ctx = NULL;
60 prog = opt_init(argc, argv, kdf_options);
61 while ((o = opt_next()) != OPT_EOF) {
65 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
68 opt_help(kdf_options);
75 dkm_len = (size_t)atoi(opt_arg());
82 opts = sk_OPENSSL_STRING_new_null();
83 if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg()))
92 argc = opt_num_rest();
96 BIO_printf(bio_err, "Invalid number of extra arguments\n");
100 if ((kdf = EVP_KDF_fetch(NULL, argv[0], NULL)) == NULL) {
101 BIO_printf(bio_err, "Invalid KDF name %s\n", argv[0]);
105 ctx = EVP_KDF_CTX_new(kdf);
112 app_params_new_from_opts(opts, EVP_KDF_settable_ctx_params(kdf));
117 if (!EVP_KDF_CTX_set_params(ctx, params)) {
118 BIO_printf(bio_err, "KDF parameter error\n");
119 ERR_print_errors(bio_err);
122 app_params_free(params);
127 out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT);
132 BIO_printf(bio_err, "Invalid derived key length.\n");
135 dkm_bytes = app_malloc(dkm_len, "out buffer");
136 if (dkm_bytes == NULL)
139 if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len)) {
140 BIO_printf(bio_err, "EVP_KDF_derive failed\n");
145 BIO_write(out, dkm_bytes, dkm_len);
147 hexout = OPENSSL_buf2hexstr(dkm_bytes, dkm_len);
148 if (hexout == NULL) {
149 BIO_printf(bio_err, "Memory allocation failure\n");
152 BIO_printf(out, "%s\n\n", hexout);
158 ERR_print_errors(bio_err);
159 OPENSSL_clear_free(dkm_bytes, dkm_len);
160 sk_OPENSSL_STRING_free(opts);
162 EVP_KDF_CTX_free(ctx);
164 OPENSSL_free(hexout);