/*
 * This file must contain crypto functions of engineering mode sources.
 * Internal functions for use only by engineering mode module.
 */
#include <ctype.h>
#include <em_ta.h>
#include <stdio.h>
#include <string.h>

#include "crypto/em_crypto_cert.h"
#include "qsee_cipher.h"
#include "qsee_ecc.h"
#include "qsee_hash.h"
#include "qsee_heap.h"
#include "qsee_hmac.h"
#include "qsee_kdf.h"
#include "qsee_log.h"

#include "openssl/crypto.h"
#include "openssl/err.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/hmac.h"
#include "openssl/rsa.h"
#include "openssl/x509.h"

int em_get_random(unsigned char *buf, int required_len)
{
	int ret;

	EM_CHECK_NULL(__func__, EM_ERR_EM_GET_RANDOM_QSEE, buf);

	if (required_len < 0) {
		LOGE("%s : Unexpected length(%d)\n", __func__, required_len);
		ret = EM_ERR_EM_GET_RANDOM_QSEE_INVALID_ARG;
		goto out;
	}

	ret = qsee_get_random_bytes(buf, required_len);
	if (ret != EM_SUCCESS) {
		LOGE("%s : Failed to get random from qsee(%d/%d\n", __func__, ret, required_len);
		goto out;
	}

	ret = required_len;

out:
	return ret;
}

int em_crypto_kdf(uint8_t *key, int32_t key_len, uint8_t *iv, uint32_t iv_len)
{

	const char key_label[] = {"EngineeringMode20 AES256 Key Label, MSTG."};
	const char key_context[] = {"EngineeringMode20 AES256 Key Context, MSTG."};
	const char iv_label[] = {"EngineeringMode20 AES256 GCM IV Label, MSTG."};
	const char iv_context[] = {"EngineeringMode20 AES256 GCM IV Context, MSTG."};

	int ret;
	int qret;

	qret = qsee_kdf(NULL, key_len, (void *)key_label, sizeof(key_label), (void *)key_context, sizeof(key_context),
			key, key_len);
	if (qret < 0) {
		LOGE("%s: Failed qsee_kdf for key(%d)\n", __func__, qret);
		ret = EM_ERR_EM_CRYPTO_KDF_QSEE_KEY;
		goto out;
	}

	qret = qsee_kdf(NULL, iv_len, (void *)iv_label, sizeof(iv_label), (void *)iv_context, sizeof(iv_context), iv,
			iv_len);
	if (qret < 0) {
		LOGE("%s: Failed qsee_kdf for iv(%d)\n", __func__, qret);
		ret = EM_ERR_EM_CRYPTO_KDF_QSEE_IV;
		goto out;
	}

	ret = EM_SUCCESS;

out:
	return ret;
}
