/*
 * Licensed to Open Source Radio Access Network(OS-RAN) Alliance and OAI
 * Software Alliance under one or more contributor license agreements. The
 * initial OpenXG series projects are derided from OAI projects, the files from
 * OAI projects are all in compliance with OAI Public License, Version 1.1.
 * codes and files developed from OpenXG projects and from OS-RAN Alliance
 * are all under OS-RAN licenses; you may not use this file except in compliance
 * with the license.  You may get a copy of the license at:
 *	http://www.openxg.org.cn/?falu_69.html
 * For more information about OpenXG, please contact:
 * contact@openxg.org.cn
 */

#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include <nettle/hmac.h>

#include "security_types.h"
#include "secu_defs.h"
#include "dynamic_memory_check.h"

void kdf(
    const uint8_t* key, const unsigned key_len, uint8_t* s,
    const unsigned s_len, uint8_t* out, const unsigned out_len) {
  struct hmac_sha256_ctx* ctx = calloc(1, sizeof(struct hmac_sha256_ctx));
  hmac_sha256_set_key(ctx, key_len, key);
  hmac_sha256_update(ctx, s_len, s);
  hmac_sha256_digest(ctx, out_len, out);
  free_wrapper((void**) &ctx);
}

int derive_keNB(
    const uint8_t* kasme_32, const uint32_t nas_count, uint8_t* keNB) {
  uint8_t s[7] = {0};

  // FC
  s[0] = FC_KENB;
  // P0 = Uplink NAS count
  s[1] = (nas_count & 0xff000000) >> 24;
  s[2] = (nas_count & 0x00ff0000) >> 16;
  s[3] = (nas_count & 0x0000ff00) >> 8;
  s[4] = (nas_count & 0x000000ff);
  // Length of NAS count
  s[5] = 0x00;
  s[6] = 0x04;
  kdf(kasme_32, 32, s, 7, keNB, 32);
  return 0;
}
