/**
 * Copyright (C) 2011 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Mobile Communication Division,
 * Digital Media & Communications Business, Samsung Electronics Co., Ltd.
 *
 * This software and its documentation are confidential and proprietary
 * information of Samsung Electronics Co., Ltd.  No part of the software and
 * documents may be copied, reproduced, transmitted, translated, or reduced to
 * any electronic medium or machine-readable form without the prior written
 * consent of Samsung Electronics.
 *
 * Samsung Electronics makes no representations with respect to the contents,
 * and assumes no responsibility for any errors that might appear in the
 * software and documents. This publication and the contents hereof are subject
 * to change without notice.
 *
 */
#include "tz_hdcp2_crypto.h"

int TZ_Decode_Key(u8 *encoded, u8 *key)
{
    int i = 0;
    u32 outlen = 16;
    u8 prk[16] = { 0 };

    for (i = 0; i < 16; i++)
        prk[i] = (u8) (0x20 + i);

    // 0 [16] lc key
    TZ_AES_ECB_decrypt(prk, 16, encoded, 16, key, &outlen);
    if (outlen != 16)
        return HDCP2_ERR_TRUSTZONE_DECODE_KEY;

    // 538 [320] private key
    outlen = 320;
    TZ_AES_ECB_decrypt(prk, 16, encoded + 538, 320, key + 538, &outlen);
    if (outlen != 320)
        return HDCP2_ERR_TRUSTZONE_DECODE_KEY;

    return HDCP2_OK;
}

int TZ_Verify_Key(u8 *kh, u32 len)
{
    unsigned char lcHash[32] = { 0x0b, 0xed, 0x21, 0x97, 0x2c, 0x16, 0xe8,
            0x11, 0x6e, 0xc2, 0xf8, 0xed, 0xff, 0x53, 0xe4, 0x5b, 0xec, 0xce,
            0x39, 0x9b, 0x84, 0xc0, 0x3e, 0x54, 0x5d, 0x72, 0xb5, 0x2c, 0x59,
            0x73, 0x8f, 0x18 };
    unsigned char lcTestHash[32] = { 0xa6, 0xd8, 0x93, 0x41, 0x33, 0x9b, 0x76,
            0xa5, 0x83, 0x16, 0xe1, 0x24, 0x5c, 0x2e, 0xa2, 0x82, 0x5b,
            0x85, 0x4e, 0xc1, 0x20, 0x92, 0x6e, 0xfc, 0xda, 0x9b, 0x27,
            0x1a, 0x9e, 0x61, 0x74, 0x36 };

    // Verify Key
    if (TEE_MemCompare(kh, lcHash, 32) && TEE_MemCompare(kh, lcTestHash, 32)) {
        return HDCP2_ERR_READ_WRAPPED_KEYBOX1;
    }

    return HDCP2_OK;
}
