#include "test_common.h"

CK_RV test_crypto();
CK_RV test_kdf_tree_gost3411_2012_256(CK_SESSION_HANDLE sess);

int main(int argc, char *argv[])
{
    CK_RV rc = CKR_OK;

    rc = test_main(argc, argv);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "test_main failed: 0x%lx\n", rc);
        return rc;
    }
    rc = test_crypto();
    if (rc != CKR_OK)
    {
        fprintf(stderr, "test_crypto failed: 0x%lx\n", rc);
        return rc;
    }
    return CKR_OK;
}

CK_RV test_crypto()
{
    CK_RV             rc, ret;
    CK_SESSION_HANDLE hSession;
    CK_MECHANISM_INFO minfo;


    rc = funcs->C_GetMechanismInfo(SlotId,
                                   CKM_KDF_TREE_GOSTR3411_2012_256, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
            "\n======== Mechanism CKM_KDF_TREE_GOSTR3411_2012_256 "
            "not supported ===========\n");
		goto out;
    }
    rc = funcs->C_GetMechanismInfo(SlotId,
                                   CKM_EXTRACT_KEY_FROM_KEY, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
            "\n======== Mechanism CKM_EXTRACT_KEY_FROM_KEY "
            "not supported ===========\n");
		goto out;
    }

    fprintf(stderr,
        "\n==== CKM_KDF_TREE_GOSTR3411_2012_256 and CKM_EXTRACT_KEY_FROM_KEY "
        "test ====\n");
	rc = funcs->C_OpenSession(SlotId,
                          CKF_RW_SESSION | CKF_SERIAL_SESSION,
                          NULL_PTR, NULL_PTR, &hSession);
	if (rc != CKR_OK)
	{
		fprintf(stderr,
            "ERROR call to C_OpenSession failed, rc = 0x%lx\n", rc);
		goto out;
	}
	fprintf(stderr, "C_OpenSession success\n");
    rc = test_kdf_tree_gost3411_2012_256(hSession);
	if (rc != CKR_OK)
    {
        fprintf(stderr,
            "ERROR CKM_KDF_TREE_GOSTR3411_2012_256 and CKM_EXTRACT_KEY_FROM_KEY test failed, "
            "rc = 0x%lx\n", rc);
    }
    else
    {
        fprintf(stderr,
            "CKM_KDF_TREE_GOSTR3411_2012_256 and CKM_EXTRACT_KEY_FROM_KEY test passed.\n");
    }
	if ((ret = funcs->C_CloseSession(hSession)) != CKR_OK)
	{
		fprintf(stderr,
			"Error: C_CloseSession failed with 0x%lx\n", ret);
		rc = ret;
	}
	else
	{
		fprintf(stderr, "C_CloseSession success\n");
	}

 out:
    return rc;
}

CK_RV test_kdf_tree_gost3411_2012_256(CK_SESSION_HANDLE sess)
{
    CK_RV rc = CKR_OK;
    static CK_BYTE                value[256];
    CK_ULONG               len;
    CK_MECHANISM           mechanism_desc =
    { CKM_KDF_TREE_GOSTR3411_2012_256, NULL, 0 };
    CK_MECHANISM_PTR       mechanism = &mechanism_desc;
	CK_TC26_KDF_TREE_GOSTR3411_2012_256_PARAMS params;
	CK_ULONG ulFirstBitNum = 0;
	CK_MECHANISM		   mechanism_extract_desc =
	{ CKM_EXTRACT_KEY_FROM_KEY, NULL, 0 };
	CK_MECHANISM_PTR       mechanism_extract = &mechanism_extract_desc;

    CK_OBJECT_HANDLE       keyh         = CK_INVALID_HANDLE;
    CK_OBJECT_HANDLE       kdf_keyh      = CK_INVALID_HANDLE;
    CK_OBJECT_HANDLE       cipher_keyh  = CK_INVALID_HANDLE;
    CK_OBJECT_HANDLE       mac_keyh		= CK_INVALID_HANDLE;
    static CK_OBJECT_CLASS oclass       = CKO_SECRET_KEY;
    static CK_KEY_TYPE     key_type     = CKK_GENERIC_SECRET;
    static CK_KEY_TYPE     cipher_key_type     = CKK_MAGMA;
    static CK_BBOOL        ltrue        = CK_TRUE;
	unsigned char kin[] =
	{
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
		0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
		0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 
		0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
	};

	unsigned char seed[] =
	{
		0xaf, 0x21, 0x43, 0x41, 0x45, 0x65, 0x63, 0x78
	};
	// Данное значение label определено для диверсификации ключа шифрования 
	// при экспорте/импорте закрытого или секретного ключа, порядок которого 
	// описан в п.5.6 документа ТК 26:
	// РЕКОМЕНДАЦИИ ПО СТАНДАРТИЗАЦИИ.
	// ИСПОЛЬЗОВАНИЕ КРИПТОГРАФИЧЕСКИХ АЛГОРИТМОВ, 
	// СОПУТСТВУЮЩИХ ПРИМЕНЕНИЮ СТАНДАРТОВ
	// ГОСТ Р 34.10-2012 И ГОСТ Р 34.11-2012.
	// Утверждены решением заседания технического комитета 
	// по стандартизации «Криптографическая защита информации»
	// (Протокол №13 от 24.04.2014 г.)
	unsigned char label[] = 
	{
		0x26, 0xBD, 0xB8, 0x78,
	};
	// При R=1, L=32 значение KDF TREE совпадает со значением KDF
	unsigned char kdf_32[] =
	{
		0xa1, 0xaa, 0x5f, 0x7d, 0xe4, 0x02, 0xd7, 0xb3, 
		0xd3, 0x23, 0xf2, 0x99, 0x1c, 0x8d, 0x45, 0x34,
		0x01, 0x31, 0x37, 0x01, 0x0a, 0x83, 0x75, 0x4f, 
		0xd0, 0xaf, 0x6d, 0x7c, 0xd4, 0x92, 0x2e, 0xd9
	};

	/*
	Контрольный пример для функции диверсификации KDF_TREE_GOSTR3411_2012_256:
	R = 1
	Длина выхода L:512 бит 
	Ключ Kin:
	00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
	10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
	label:
	26 bd b8 78
	seed:
	af 21 43 41 45 65 63 78
	Значение K1: 
	22 b6 83 78 45 c6 be f6 5e a7 16 72 b2 65 83 10
	86 d3 c7 6a eb e6 da e9 1c ad 51 d8 3f 79 d1 6b
	Значение K2: 
	07 4c 93 30 59 9d 7f 8d 71 2f ca 54 39 2f 4d dd
	e9 37 51 20 6b 35 84 c8 f4 3f 9e 6d c5 15 31 f9
	*/
	// R = 1, L = 64
	unsigned char kdf_64[] = {
		0x22, 0xb6, 0x83, 0x78, 0x45, 0xc6, 0xbe, 0xf6, 
		0x5e, 0xa7, 0x16, 0x72, 0xb2, 0x65, 0x83, 0x10,
		0x86, 0xd3, 0xc7, 0x6a, 0xeb, 0xe6, 0xda, 0xe9, 
		0x1c, 0xad, 0x51, 0xd8, 0x3f, 0x79, 0xd1, 0x6b,
		0x07, 0x4c, 0x93, 0x30, 0x59, 0x9d, 0x7f, 0x8d, 
		0x71, 0x2f, 0xca, 0x54, 0x39, 0x2f, 0x4d, 0xdd,
		0xe9, 0x37, 0x51, 0x20, 0x6b, 0x35, 0x84, 0xc8, 
		0xf4, 0x3f, 0x9e, 0x6d, 0xc5, 0x15, 0x31, 0xf9
	};
	// R = 2, L = 64
	unsigned char kdf_2_64[] = {
		0xb7, 0x4e, 0xea, 0x99, 0x7c, 0x9d, 0xa9, 0x16,
		0x0c, 0xe1, 0xa3, 0x3d, 0xdd, 0xb2, 0xd7, 0x52,
		0x89, 0xfe, 0xe7, 0xd4, 0x79, 0x67, 0x06, 0x87,
		0x85, 0x1d, 0x9c, 0xf9, 0xca, 0x9f, 0xed, 0x32,
		0xdd, 0x5b, 0x85, 0x2e, 0x3f, 0x82, 0x6d, 0xb5,
		0x0e, 0x7c, 0xbe, 0xb0, 0x48, 0xd4, 0x9e, 0x19,
		0xdc, 0xa7, 0x2d, 0x4f, 0x8b, 0x99, 0x49, 0x11,
		0x29, 0xc7, 0x5c, 0xd5, 0x1a, 0x08, 0x62, 0x91
	};

    CK_ATTRIBUTE key_template[] = {
        { CKA_VALUE,            NULL_PTR,                 0 },
        { CKA_CLASS,            &oclass,   sizeof(oclass)   },
        { CKA_KEY_TYPE,         &key_type, sizeof(key_type) },
        { CKA_ENCRYPT,          &ltrue,    sizeof(ltrue)    },
        { CKA_DECRYPT,          &ltrue,    sizeof(ltrue)    }
    };

	CK_ULONG key_len = 64;
    CK_ATTRIBUTE key_derive_template[] = {
        { CKA_CLASS,            &oclass,   sizeof(oclass)   },
        { CKA_KEY_TYPE,         &key_type, sizeof(key_type) },
		{ CKA_VALUE_LEN,        &key_len,  sizeof(key_len)	},
        { CKA_ENCRYPT,          &ltrue,    sizeof(ltrue)    },
        { CKA_DECRYPT,          &ltrue,    sizeof(ltrue)    }
    };
    CK_ATTRIBUTE cipher_key_derive_template[] = {
        { CKA_CLASS,            &oclass,   sizeof(oclass)   },
        { CKA_KEY_TYPE,         &cipher_key_type, sizeof(cipher_key_type) },
        { CKA_ENCRYPT,          &ltrue,    sizeof(ltrue)    },
        { CKA_DECRYPT,          &ltrue,    sizeof(ltrue)    },
        { CKA_SIGN,				&ltrue,    sizeof(ltrue)    },
        { CKA_VERIFY,			&ltrue,    sizeof(ltrue)    }
    };
    CK_ATTRIBUTE value_template[] = {
        { CKA_VALUE, value, sizeof(value) },
    };

    key_template[0].pValue     = kin;
    key_template[0].ulValueLen = sizeof(kin);
    rc                         = funcs->C_CreateObject(sess,
                                                       key_template, sizeof(key_template) / sizeof(CK_ATTRIBUTE),
                                                       &keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_CreateObject failed: 0x%lx\n", rc);
        goto end;
    }

    mechanism->pParameter     = &params;
    mechanism->ulParameterLen = sizeof(params);

	params.pLabel = label;
	params.ulLabelLen = sizeof(label);

	params.pSeed = seed;
	params.ulSeedLen = sizeof(seed);

    printf("KDF1\n");
	params.ulCounterBytes = 1;
    rc                        = funcs->C_DeriveKey(sess, mechanism, keyh,
                                                   key_derive_template,
                                                   sizeof(key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &kdf_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
    rc = funcs->C_GetAttributeValue(sess, kdf_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_64))
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_64, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    printf("KDF1 OK\n");

	printf("Extract cipher key with CKM_EXTRACT_KEY_FROM_KEY\n");
	ulFirstBitNum = 0;
	mechanism_extract->pParameter = &ulFirstBitNum;
	mechanism_extract->ulParameterLen = sizeof(ulFirstBitNum);
    rc                        = funcs->C_DeriveKey(sess, mechanism_extract, kdf_keyh,
                                                   cipher_key_derive_template,
                                                   sizeof(cipher_key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &cipher_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
    rc = funcs->C_GetAttributeValue(sess, cipher_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    if (cipher_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, cipher_keyh);
		cipher_keyh = CK_INVALID_HANDLE;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_64)/2)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_64, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract cipher key OK\n");

	printf("Extract MAC key with CKM_EXTRACT_KEY_FROM_KEY\n");
	ulFirstBitNum = 32*8;
	mechanism_extract->pParameter = &ulFirstBitNum;
	mechanism_extract->ulParameterLen = sizeof(ulFirstBitNum);
    rc                        = funcs->C_DeriveKey(sess, mechanism_extract, kdf_keyh,
                                                   cipher_key_derive_template,
                                                   sizeof(cipher_key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &mac_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
	value_template[0].ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, mac_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    if (mac_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, mac_keyh);
		mac_keyh = CK_INVALID_HANDLE;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_64)/2)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_64+sizeof(kdf_64)/2, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract MAC key OK\n");

    if (kdf_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, kdf_keyh);
		kdf_keyh = CK_INVALID_HANDLE;
    }

    printf("KDF2\n");
	cipher_key_type = CKK_KUZNYECHIK;
	params.ulCounterBytes = 2;
    rc                        = funcs->C_DeriveKey(sess, mechanism, keyh,
                                                   key_derive_template,
                                                   sizeof(key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &kdf_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
	value_template[0].ulValueLen = sizeof(value);
    rc = funcs->C_GetAttributeValue(sess, kdf_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_2_64))
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_2_64, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    printf("KDF2 OK\n");

	printf("Extract cipher key\n");
	ulFirstBitNum = 0;
	mechanism_extract->pParameter = &ulFirstBitNum;
	mechanism_extract->ulParameterLen = sizeof(ulFirstBitNum);
    rc                        = funcs->C_DeriveKey(sess, mechanism_extract, kdf_keyh,
                                                   cipher_key_derive_template,
                                                   sizeof(cipher_key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &cipher_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
	value_template[0].ulValueLen = sizeof(value);
    rc = funcs->C_GetAttributeValue(sess, cipher_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    if (cipher_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, cipher_keyh);
		cipher_keyh = CK_INVALID_HANDLE;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_2_64)/2)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_2_64, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract cipher key OK\n");

	printf("Extract MAC key\n");
	ulFirstBitNum = 32*8;
	mechanism_extract->pParameter = &ulFirstBitNum;
	mechanism_extract->ulParameterLen = sizeof(ulFirstBitNum);
    rc                        = funcs->C_DeriveKey(sess, mechanism_extract, kdf_keyh,
                                                   cipher_key_derive_template,
                                                   sizeof(cipher_key_derive_template) / sizeof(CK_ATTRIBUTE),
                                                   &mac_keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DeriveKey failed: 0x%lx\n", rc);
        goto end;
    }
	value_template[0].ulValueLen = sizeof(value);
    rc = funcs->C_GetAttributeValue(sess, mac_keyh,
                                    value_template,
                                    sizeof(value_template) / sizeof(CK_ATTRIBUTE));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetAttributeValue failed: 0x%lx\n", rc);
        goto end;
    }
    if (mac_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, mac_keyh);
		mac_keyh = CK_INVALID_HANDLE;
    }
    len = value_template[0].ulValueLen;
    if (len != sizeof(kdf_2_64)/2)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kdf_2_64+sizeof(kdf_2_64)/2, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract MAC key OK\n");

    if (kdf_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, kdf_keyh);
		kdf_keyh = CK_INVALID_HANDLE;
    }

    printf("SUCCESS\n");

    rc = CKR_OK;
 end:
    if (keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, keyh);
    }
    if (cipher_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, cipher_keyh);
    }
    if (mac_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, mac_keyh);
    }
    if (kdf_keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, kdf_keyh);
    }

    return rc;
}

