#include "test_common.h"

CK_RV test_crypto();
CK_RV test_extract_key_from_key(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;
    CK_SESSION_HANDLE hSession;
    CK_MECHANISM_INFO minfo;

    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");
		return rc;
    }

	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);
		return rc;
	}
	fprintf(stderr, "C_OpenSession success\n");
    fprintf(stderr,
        "\n======== CKM_EXTRACT_KEY_FROM_KEY test ========\n");
    rc = test_extract_key_from_key(hSession);
	if (rc != CKR_OK)
    {
        fprintf(stderr,
            "ERROR extract_key_from_key test failed, rc = 0x%lx\n", rc);
		goto out;
    }
    else
    {
        fprintf(stderr,
            "CKM_EXTRACT_KEY_FROM_KEY test passed\n");
    }

 out:
	funcs->C_CloseSession(hSession);
    return rc;
}

CK_RV test_extract_key_from_key(CK_SESSION_HANDLE sess)
{
    CK_RV rc = CKR_OK;
    static CK_BYTE                value[256];
    CK_ULONG               len;
	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       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;
	static 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,
		0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 
		0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
		0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 
		0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
		
	};
	static unsigned char shifted_kin[] =
	{
		0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
		0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf1, 0x01,
		0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81,
		0x91, 0xa1, 0xb1, 0xc1, 0xd1, 0xe1, 0xf2, 0x02,
		
	};
    CK_ATTRIBUTE key_template[] = {
        { CKA_VALUE,            kin,                 sizeof(kin) },
        { CKA_CLASS,            &oclass,   sizeof(oclass)   },
        { CKA_KEY_TYPE,         &key_type, sizeof(key_type) },
        { CKA_DERIVE,           &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) },
    };

	printf("Base key:\n");
    print_bytes(kin, sizeof(kin));

    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;
    }


	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, 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 != 32)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kin, 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, 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 != 32)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, kin+32, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract MAC key OK\n");

	printf("Extract key with non-aligned bits\n");
	ulFirstBitNum = 12;
	mechanism_extract->pParameter = &ulFirstBitNum;
	mechanism_extract->ulParameterLen = sizeof(ulFirstBitNum);
    rc                        = funcs->C_DeriveKey(sess, mechanism_extract, 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 != 32)
    {
        fprintf(stderr, "Invalid length: %ld\n", len);
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
    print_bytes(value, len);
    if (memcmp(value, shifted_kin, len) != 0)
    {
        fprintf(stderr, "Invalid value\n");
        rc = CKR_FUNCTION_FAILED;
        goto end;
    }
	printf("Extract key with non-aligned bits OK\n");

    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);
    }

    return rc;
}

