#include "test_common.h"

CK_RV test_crypto();
CK_RV test_kuznyechik_ctr(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_CTR, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
                "\n======== Mechanism CKM_KUZNYECHIK_CTR not supported ===========\n");
    }
    else
    {
        fprintf(stderr,
                "\n==================== CKM_KUZNYECHIK_CTR test ==================\n");
        rc = test_kuznyechik_ctr(hSession, hSession2);
        if (rc != CKR_OK)
        {
            fprintf(stderr,
                    "ERROR CKM_KUZNYECHIK_CTR failed, rc = 0x%lx\n", rc);
        }
        else
        {
            fprintf(stderr, "CKM_KUZNYECHIK_CTR 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_ctr(CK_SESSION_HANDLE sess, CK_SESSION_HANDLE sess2)
{
    CK_RV rc = CKR_OK;
    CK_ULONG               len, state_len, dummy_len = 0;
    CK_BYTE                value[1024], value2[1024];
    CK_BYTE                *state;
    CK_BYTE                data2[256];
    CK_OBJECT_HANDLE       keyh           = CK_INVALID_HANDLE;
    CK_MECHANISM           mechanism_desc = { CKM_KUZNYECHIK_CTR, NULL, 0 };
    CK_MECHANISM_PTR       mechanism      = &mechanism_desc;

    static CK_BBOOL        ltrue    = CK_TRUE;
//    static CK_BBOOL        lfalse   = CK_FALSE;
    static CK_OBJECT_CLASS oclass   = CKO_SECRET_KEY;
    static CK_KEY_TYPE     key_type = CKK_KUZNYECHIK;

    /* тестовые значения мастер-ключа */
    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
    };
    // По стандарту, IV для CTR должна иметь длину,
    // равную половине длины блока.
    static unsigned char kGost14CtrSV[] =
    {
        0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xce, 0xf0,
    };

    /* значение открытого текста */
    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 kGost14CtrC[] =
    {
        0xf1, 0x95, 0xd8, 0xbe, 0xc1, 0x0e, 0xd1, 0xdb,
        0xd5, 0x7b, 0x5f, 0xa2, 0x40, 0xbd, 0xa1, 0xb8,
        0x85, 0xee, 0xe7, 0x33, 0xf6, 0xa1, 0x3e, 0x5d,
        0xf3, 0x3c, 0xe4, 0xb3, 0x3c, 0x45, 0xde, 0xe4,
        0xa5, 0xea, 0xe8, 0x8b, 0xe6, 0x35, 0x6e, 0xd3,
        0xd5, 0xe8, 0x77, 0xf1, 0x35, 0x64, 0xa3, 0xa5,
        0xcb, 0x91, 0xfa, 0xb1, 0xf2, 0x0c, 0xba, 0xb6,
        0xd1, 0xc6, 0xd1, 0x58, 0x20, 0xbd, 0xba, 0x73
    };

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

    mechanism->pParameter     = kGost14CtrSV;
    mechanism->ulParameterLen = sizeof(kGost14CtrSV);

    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);
        return rc;
    }
    rc = funcs->C_EncryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptInit failed: 0x%lx\n", rc);
        return rc;
    }
    len = 11;
    rc  = funcs->C_EncryptUpdate(sess, kGost14PlainText, len,
                                 value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    len = sizeof(kGost14PlainText) - 11;
    rc  = funcs->C_EncryptUpdate(sess, kGost14PlainText + 11, len,
                                 value + 11, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    rc = funcs->C_EncryptFinal(sess, value + sizeof(kGost14PlainText), &dummy_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptFinal failed: 0x%lx\n", rc);
        return rc;
    }

    len = sizeof(kGost14PlainText);
    CHECK(value, len, kGost14CtrC);

    rc = funcs->C_DecryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptInit failed: 0x%lx\n", rc);
        return rc;
    }
	len = 17;
    rc = funcs->C_DecryptUpdate(sess, value, len, value2, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
	len = sizeof(kGost14PlainText) - 17;
    rc = funcs->C_DecryptUpdate(sess, value + 17, len,
                                value2 + 17, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    rc = funcs->C_DecryptFinal(sess,
                               value2 + sizeof(kGost14PlainText), &dummy_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptFinal failed: 0x%lx\n", rc);
        return rc;
    }
    len = sizeof(kGost14PlainText);

    CHECK(value2, len, kGost14PlainText);

    printf("Two Sessions With Get/SetOperationState\n");

    printf("Random Data\n");
    rc = funcs->C_GenerateRandom(sess, data2, sizeof(data2));
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GenerateRandom failed: 0x%lx\n", rc);
        goto end;
    }

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

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

    // Save session operation state
    state_len = 0;
    rc        = funcs->C_GetOperationState(sess, NULL, &state_len);
    state     = malloc(state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    rc = funcs->C_GetOperationState(sess, state, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }

    // Restore saved operation state to other session
    rc = funcs->C_SetOperationState(sess2, state, state_len,
                                    keyh, CK_INVALID_HANDLE);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    memcpy(value2, value, sizeof(value));

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

    free(state);
    state_len = 0;
    rc        = funcs->C_GetOperationState(sess, NULL, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    state = 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(sess, state, state_len,
                                    keyh, CK_INVALID_HANDLE);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_SetOperationState failed: 0x%lx\n", rc);
        goto end;
    }

    // Continue operations in first session
    len = sizeof(value) - 191;
    rc  = funcs->C_EncryptUpdate(sess,
                                 data2 + 191, len, value + 191, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        goto end;
    }

    // Continue restored operations in second session
    len = sizeof(value2) - 191;
    rc  = funcs->C_EncryptUpdate(sess2,
                                 data2 + 191, len, value2 + 191, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        goto end;
    }

    // Finalize operations in first session
    len = sizeof(value) - sizeof(data2);
    rc  = funcs->C_EncryptFinal(sess, value + sizeof(data2), &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptFinal failed: 0x%lx\n", rc);
        goto end;
    }
    memcpy(value2, value, sizeof(value));

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

    // Finalize operations in second session
    len = sizeof(value2) - sizeof(data2);
    rc  = funcs->C_EncryptFinal(sess2, value2 + sizeof(data2), &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptFinal failed: 0x%lx\n", rc);
        goto end;
    }
    // len == 0

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

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

    CHECK(value, len, data2);

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

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

    // len == 0
    len = sizeof(data2);
    CHECK(value, len, data2);

    rc = funcs->C_DecryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptInit failed: 0x%lx\n", rc);
        goto end;
    }
    free(state);
    state_len = 0;
    rc        = funcs->C_GetOperationState(sess, NULL, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    state = 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;
    }
	len = 191;
    rc = funcs->C_DecryptUpdate(sess, value2, len, value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptUpdate failed: 0x%lx\n", rc);
        goto end;
    }
    free(state);
    state_len = 0;
    rc        = funcs->C_GetOperationState(sess, NULL, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    state = 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;
    }
	len = sizeof(value2) - 191;
    rc = funcs->C_DecryptUpdate(sess,
                                value2 + 191, len, value + 191, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptUpdate failed: 0x%lx\n", rc);
        goto end;
    }
    free(state);
    state_len = 0;
    rc        = funcs->C_GetOperationState(sess, NULL, &state_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_GetOperationState failed: 0x%lx\n", rc);
        goto end;
    }
    state = 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_DecryptFinal(sess, value + sizeof(value2), &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptFinal failed: 0x%lx\n", rc);
        goto end;
    }
    free(state);

    // len == 0
    len = sizeof(data2);
    CHECK(value, len, data2);

    printf("SUCCESS\n");
    rc = CKR_OK;

 end:
    if (keyh != CK_INVALID_HANDLE)
    {
        rc = funcs->C_DestroyObject(sess, keyh);
        if (rc != CKR_OK)
        {
            fprintf(stderr, "C_DestroyObject error, code 0x%lx\n", rc);
            return rc;
        }
    }
    return rc;
}
