#include "test_common.h"

CK_RV test_crypto();
CK_RV test_kuznyechik_mac(CK_SESSION_HANDLE sess, CK_SESSION_HANDLE sess2);

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, hSession2;
    CK_MECHANISM_INFO minfo;

    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 1 failed, rc = 0x%lx\n", rc);
        goto out;
    }
    fprintf(stderr, "C_OpenSession 1 success\n");
    rc = funcs->C_OpenSession(SlotId,
                              CKF_RW_SESSION | CKF_SERIAL_SESSION,
                              NULL_PTR, NULL_PTR, &hSession2);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
                "ERROR call to C_OpenSession 2 failed, rc = 0x%lx\n", rc);
        goto out;
    }
    fprintf(stderr, "C_OpenSession 2 success\n");
/*
        // log in as normal user
        rc = funcs->C_Login(hSession, CKU_USER, user_pin, strlen(user_pin));
        if (rc != CKR_OK) {
                fprintf(stderr, "ERROR call to C_Login failed, rc = 0x%lx\n", rc);
                goto out_close;
        }
        fprintf(stderr, "C_Login success\n");
 */
    rc = funcs->C_GetMechanismInfo(SlotId, CKM_KUZNYECHIK_OMAC, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
                "\n======== Mechanism CKM_KUZNYECHIK_OMAC not supported ===========\n");
    }
    else
    {
        fprintf(stderr,
                "\n==================== CKM_KUZNYECHIK_OMAC test ==================\n");
        rc = test_kuznyechik_mac(hSession, hSession2);
        if (rc != CKR_OK)
        {
            fprintf(stderr,
                    "ERROR CKM_KUZNYECHIK_OMAC failed, rc = 0x%lx\n", rc);
        }
        else
        {
            fprintf(stderr, "CKM_KUZNYECHIK_OMAC test passed.\n");
        }
    }

    if ((ret = funcs->C_CloseSession(hSession)) != CKR_OK)
    {
        fprintf(stderr,
                "Error: C_CloseSession 1 failed with 0x%lx\n", ret);
        rc = ret;
    }
    else
    {
        fprintf(stderr, "C_CloseSession 1 success\n");
    }
    if ((ret = funcs->C_CloseSession(hSession2)) != CKR_OK)
    {
        fprintf(stderr,
                "Error: C_CloseSession 2 failed with 0x%lx\n", ret);
        rc = ret;
    }
    else
    {
        fprintf(stderr, "C_CloseSession 2 success\n");
    }

 out:
    return rc;
}

CK_RV test_kuznyechik_mac(CK_SESSION_HANDLE sess, CK_SESSION_HANDLE sess2)
{
    CK_RV                  rc = CKR_OK;
    CK_BYTE                value[128];
    CK_ULONG               len;
    CK_OBJECT_HANDLE       keyh           = CK_INVALID_HANDLE;
    CK_MECHANISM           mechanism_desc = { CKM_KUZNYECHIK_OMAC, NULL, 0 };
    CK_MECHANISM_PTR       mechanism      = &mechanism_desc;

    static CK_OBJECT_CLASS oclass           = CKO_SECRET_KEY;
    static CK_KEY_TYPE     key_type         = CKK_KUZNYECHIK;
    static CK_BBOOL        ltrue            = CK_TRUE;
//    static CK_BBOOL        lfalse           = CK_FALSE;
    static unsigned char   kMasterKeyData[] =
    {
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
        0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
    };
    static unsigned char   kGost14PlainText[] =
    {
        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00,
        0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88,
        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x0a,
        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
        0x99, 0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x0a, 0x00,
        0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
        0xaa, 0xbb, 0xcc, 0xee, 0xff, 0x0a, 0x00, 0x11
    };
    static unsigned char   kGost14ImitS[] =
    {
        0x33, 0x6f, 0x4d, 0x29, 0x60, 0x59, 0xfb, 0xe3,
		0x4d, 0xde, 0xb3, 0x5b, 0x37, 0x74, 0x9c, 0x67
	};
    static CK_ATTRIBUTE    key_template[] = {
        { CKA_VALUE,    kMasterKeyData, sizeof(kMasterKeyData) },
        { CKA_CLASS,    &oclass,        sizeof(oclass)         },
        { CKA_KEY_TYPE, &key_type,      sizeof(key_type)       },
        { CKA_SIGN,     &ltrue,         sizeof(CK_BBOOL)       },
        { CKA_VERIFY,   &ltrue,         sizeof(CK_BBOOL)       },
    };
    CK_BYTE                *state    = NULL;
    CK_ULONG               state_len = 0;
    char                str[4096];

    keyh = CK_INVALID_HANDLE;
    print_bytes_str(kMasterKeyData, sizeof(kMasterKeyData), str);
    fprintf(stderr, "key:\n%s\n", str);

    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;
    }
	// Размер имитовставки не задается при инициализации контекста,
	// поэтому будет принят максимальный - размер блока.
    rc = funcs->C_SignInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignInit failed: 0x%lx\n", rc);
        goto end;
    }

    len = sizeof(value);
    rc  = funcs->C_Sign(sess, kGost14PlainText, sizeof(kGost14PlainText), value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_Sign failed: 0x%lx\n", rc);
        goto end;
    }
    print_bytes_str(kGost14ImitS, sizeof(kGost14ImitS), str);
    fprintf(stderr, "kGost14ImitS MAC:\n%s\n", str);
    print_bytes_str(value, len, str);
    fprintf(stderr, "value MAC:\n%s\n", str);

    CHECK(value, len, kGost14ImitS);

    rc = funcs->C_VerifyInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_VerifyInit failed: 0x%lx\n", rc);
        goto end;
    }

    len = sizeof(value);
    rc  = funcs->C_Verify(sess, kGost14PlainText, sizeof(kGost14PlainText),
                          kGost14ImitS, sizeof(kGost14ImitS));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_Verify failed: 0x%lx\n", rc);
        goto end;
    }
    fprintf(stderr, "C_Verify OK\n");

    len = sizeof(value);
    rc  = funcs->C_SignInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignInit failed: 0x%lx\n", rc);
        goto end;
    }
    rc = funcs->C_SignUpdate(sess, kGost14PlainText, 15);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignUpdate failed: 0x%lx\n", rc);
        goto end;
    }

    rc = funcs->C_GetOperationState(sess, NULL, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    state = (CK_BYTE *) malloc(state_len);
    rc    = funcs->C_GetOperationState(sess, state, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    rc = funcs->C_SetOperationState(sess2, state, state_len,
                                    CK_INVALID_HANDLE, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SetOperationState failed: 0x%lx\n", rc);
        goto end;
    }

    rc = funcs->C_SignUpdate(sess2, kGost14PlainText + 15, sizeof(kGost14PlainText) - 15);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignUpdate failed: 0x%lx\n", rc);
        goto end;
    }

    rc = funcs->C_SignFinal(sess2, value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignFinal failed: 0x%lx\n", rc);
        goto end;
    }

    CHECK(value, len, kGost14ImitS);

    rc = funcs->C_SetOperationState(sess, state, state_len,
                                    CK_INVALID_HANDLE, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SetOperationState failed: 0x%lx\n", rc);
        goto end;
    }

    rc = funcs->C_SignUpdate(sess, kGost14PlainText + 15, sizeof(kGost14PlainText) - 15);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignUpdate failed: 0x%lx\n", rc);
        goto end;
    }

    rc = funcs->C_SignFinal(sess, value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SignFinal failed: 0x%lx\n", rc);
        goto end;
    }

    CHECK(value, len, kGost14ImitS);

    free(state);
    state = NULL;

 end:
    if (keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, keyh);
    }

    return rc;
}
