| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
/** |
| 3 |
* This file is part of libnvme. |
| 4 |
* Copyright (c) 2025 SUSE LLC. |
| 5 |
* |
| 6 |
* Authors: Daniel Wagner <[email protected]> |
| 7 |
*/ |
| 8 |
|
| 9 |
#include <openssl/core_names.h> |
| 10 |
#include <openssl/evp.h> |
| 11 |
#include <openssl/hmac.h> |
| 12 |
#include <openssl/kdf.h> |
| 13 |
#include <openssl/params.h> |
| 14 |
#include <stdio.h> |
| 15 |
#include <string.h> |
| 16 |
|
| 17 |
#define SHA256_LEN 32 |
| 18 |
|
| 19 |
static EVP_PKEY_CTX *setup_ctx(void) |
| 20 |
{ |
| 21 |
EVP_PKEY_CTX *ctx = NULL; |
| 22 |
const char *salt = "salt"; |
| 23 |
const char *key = "key"; |
| 24 |
|
| 25 |
ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL); |
| 26 |
if (!ctx) |
| 27 |
return NULL; |
| 28 |
if (EVP_PKEY_derive_init(ctx) <= 0) |
| 29 |
goto free_ctx; |
| 30 |
if (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) <= 0) |
| 31 |
goto free_ctx; |
| 32 |
if (EVP_PKEY_CTX_set1_hkdf_salt(ctx, |
| 33 |
(unsigned char *)salt, strlen(salt)) <= 0) |
| 34 |
goto free_ctx; |
| 35 |
if (EVP_PKEY_CTX_set1_hkdf_key(ctx, |
| 36 |
(unsigned char *)key, strlen(key)) <= 0) |
| 37 |
goto free_ctx; |
| 38 |
|
| 39 |
return ctx; |
| 40 |
|
| 41 |
free_ctx: |
| 42 |
EVP_PKEY_CTX_free(ctx); |
| 43 |
return NULL; |
| 44 |
} |
| 45 |
|
| 46 |
int main(void) |
| 47 |
{ |
| 48 |
unsigned char out[SHA256_LEN], out2[SHA256_LEN]; |
| 49 |
size_t len = sizeof(out); |
| 50 |
const char *a = "a"; |
| 51 |
const char *b = "b"; |
| 52 |
EVP_PKEY_CTX *ctx; |
| 53 |
|
| 54 |
/* out = A + B */ |
| 55 |
ctx = setup_ctx(); |
| 56 |
if (!ctx) |
| 57 |
return 1; |
| 58 |
if (EVP_PKEY_CTX_add1_hkdf_info(ctx, |
| 59 |
(unsigned char *)a, strlen(a)) <= 0) |
| 60 |
goto free_ctx; |
| 61 |
if (EVP_PKEY_CTX_add1_hkdf_info(ctx, |
| 62 |
(unsigned char *)b, strlen(b)) <= 0) |
| 63 |
goto free_ctx; |
| 64 |
if (EVP_PKEY_derive(ctx, out, &len) <= 0) |
| 65 |
goto free_ctx; |
| 66 |
EVP_PKEY_CTX_free(ctx); |
| 67 |
|
| 68 |
/* out = B */ |
| 69 |
ctx = setup_ctx(); |
| 70 |
if (!ctx) |
| 71 |
return 1; |
| 72 |
if (EVP_PKEY_CTX_add1_hkdf_info(ctx, |
| 73 |
(unsigned char *)b, strlen(b)) <= 0) |
| 74 |
goto free_ctx; |
| 75 |
if (EVP_PKEY_derive(ctx, out2, &len) <= 0) |
| 76 |
goto free_ctx; |
| 77 |
EVP_PKEY_CTX_free(ctx); |
| 78 |
|
| 79 |
printf("EVP_PKEY_CTX_add1_hkdf_info behavior: "); |
| 80 |
if (!memcmp(out, out2, len)) { |
| 81 |
printf("set\n"); |
| 82 |
return 1; |
| 83 |
} |
| 84 |
|
| 85 |
printf("add\n"); |
| 86 |
return 0; |
| 87 |
|
| 88 |
free_ctx: |
| 89 |
EVP_PKEY_CTX_free(ctx); |
| 90 |
return 1; |
| 91 |
} |