/*
* Copyright 2018-2019 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2018-2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/fips.h>
#include "crypto/fips.h"
#include <openssl/evp.h>
#include <openssl/kdf.h>
#ifdef OPENSSL_FIPS
int FIPS_selftest_pbkdf2(void)
{
int ret = 0;
EVP_KDF_CTX *kctx;
unsigned char out[32];
if ((kctx = EVP_KDF_CTX_new_id(EVP_KDF_PBKDF2)) == NULL) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_PASS, "password", (size_t)8) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_SALT, "salt", (size_t)4) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_ITER, 2) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_MD, EVP_sha256()) <= 0) {
goto err;
}
if (EVP_KDF_derive(kctx, out, sizeof(out)) <= 0) {
goto err;
}
{
const unsigned char expected[sizeof(out)] = {
0xae, 0x4d, 0x0c, 0x95, 0xaf, 0x6b, 0x46, 0xd3,
0x2d, 0x0a, 0xdf, 0xf9, 0x28, 0xf0, 0x6d, 0xd0,
0x2a, 0x30, 0x3f, 0x8e, 0xf3, 0xc2, 0x51, 0xdf,
0xd6, 0xe2, 0xd8, 0x5a, 0x95, 0x47, 0x4c, 0x43
};
if (memcmp(out, expected, sizeof(expected))) {
goto err;
}
}
ret = 1;
err:
if (!ret)
FIPSerr(FIPS_F_FIPS_SELFTEST_PBKDF2, FIPS_R_SELFTEST_FAILED);
EVP_KDF_CTX_free(kctx);
return ret;
}
/* Test vector from RFC 8009 (AES Encryption with HMAC-SHA2 for Kerberos
* 5) appendix A. */
int FIPS_selftest_kbkdf(void)
{
int ret = 0;
EVP_KDF_CTX *kctx;
char *label = "prf", *prf_input = "test";
static unsigned char input_key[] = {
0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28,
0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C,
};
static unsigned char output[] = {
0x9D, 0x18, 0x86, 0x16, 0xF6, 0x38, 0x52, 0xFE,
0x86, 0x91, 0x5B, 0xB8, 0x40, 0xB4, 0xA8, 0x86,
0xFF, 0x3E, 0x6B, 0xB0, 0xF8, 0x19, 0xB4, 0x9B,
0x89, 0x33, 0x93, 0xD3, 0x93, 0x85, 0x42, 0x95,
};
unsigned char result[sizeof(output)] = { 0 };
if ((kctx = EVP_KDF_CTX_new_id(EVP_KDF_KB)) == NULL) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_KB_MAC_TYPE, EVP_KDF_KB_MAC_TYPE_HMAC) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_MD, EVP_sha256()) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_KEY, input_key, sizeof(input_key)) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_SALT, label, strlen(label)) <= 0) {
goto err;
}
if (EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_SET_KB_INFO, prf_input, strlen(prf_input)) <= 0) {
goto err;
}
ret = EVP_KDF_derive(kctx, result, sizeof(result)) > 0
&& memcmp(result, output, sizeof(output)) == 0;
err:
if (!ret)
FIPSerr(FIPS_F_FIPS_SELFTEST_KBKDF, FIPS_R_SELFTEST_FAILED);
EVP_KDF_CTX_free(kctx);
return ret;
}
int FIPS_selftest_kdf(void)
{
return FIPS_selftest_pbkdf2() && FIPS_selftest_kbkdf();
}
#endif