#include "test_common.h"

CK_RV test_crypto();
CK_RV test_kuznyechik_cfb(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 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 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_CFB, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
                "\n======== Mechanism CKM_KUZNYECHIK_CFB not supported ===========\n");
    }
    else
    {
        fprintf(stderr,
                "\n==================== CKM_KUZNYECHIK_CFB test ==================\n");
        rc = test_kuznyechik_cfb(hSession, hSession2);
        if (rc != CKR_OK)
        {
            fprintf(stderr,
                    "ERROR CKM_KUZNYECHIK_CFB failed, rc = 0x%lx\n", rc);
            return rc;
        }
        else
        {
            fprintf(stderr, "CKM_KUZNYECHIK_CFB 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 1 success\n");
    }
    if ((ret = funcs->C_CloseSession(hSession2)) != CKR_OK)
    {
        fprintf(stderr,
                "Error: C_CloseSession failed with 0x%lx\n", ret);
        rc = ret;
    }
    else
    {
        fprintf(stderr, "C_CloseSession 2 success\n");
    }

 out:
    return rc;
}

CK_RV test_kuznyechik_cfb(CK_SESSION_HANDLE sess, CK_SESSION_HANDLE sess2)
{
    CK_RV rc = CKR_OK;
    CK_ULONG               len, state_len, dummy_len = 0;
    CK_OBJECT_HANDLE       keyh = CK_INVALID_HANDLE;
    CK_BYTE                *state;
    CK_MECHANISM           mechanism_desc = { CKM_KUZNYECHIK_CFB, 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
    };
    static unsigned char kGost14CfbSV[] =
    {
        0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xce, 0xf0,
        0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf0, 0x01, 0x12,
        0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, 0x90,
        0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19
    };

    /* значение открытого текста */
    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 kGost14CfbC[] =
    {
        0x81, 0x80, 0x0a, 0x59, 0xb1, 0x84, 0x2b, 0x24,
        0xff, 0x1f, 0x79, 0x5e, 0x89, 0x7a, 0xbd, 0x95,
        0xed, 0x5b, 0x47, 0xa7, 0x04, 0x8c, 0xfa, 0xb4,
        0x8f, 0xb5, 0x21, 0x36, 0x9d, 0x93, 0x26, 0xbf,
        0x79, 0xf2, 0xa8, 0xeb, 0x5c, 0xc6, 0x8d, 0x38,
        0x84, 0x2d, 0x26, 0x4e, 0x97, 0xa2, 0x38, 0xb5,
        0x4f, 0xfe, 0xbe, 0xcd, 0x4e, 0x92, 0x2d, 0xe6,
        0xc7, 0x5b, 0xd9, 0xdd, 0x44, 0xfb, 0xf4, 0xd1
    };

    CK_BYTE             value[1024], value2[1024];
    CK_BYTE             buf[256];
    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)       },
    };
    CK_BYTE             data2[256];

    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;
    }
    printf("Encrypt\n");
    mechanism->pParameter     = kGost14CfbSV;
    mechanism->ulParameterLen = sizeof(kGost14CfbSV);
    rc                        = funcs->C_EncryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptInit failed: 0x%lx\n", rc);
        return rc;
    }
    // FIXME: Попытка задать данные, длина которых не кратна размеру блока,
    // приводит к ошибке в последнем неполном блоке.
    len = sizeof(kGost14PlainText);
    rc  = funcs->C_EncryptUpdate(sess, kGost14PlainText, len,
                                 value, &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, kGost14CfbC);
    printf("Encrypt OK\n");

    printf("Decrypt\n");
    mechanism->pParameter     = kGost14CfbSV;
    mechanism->ulParameterLen = sizeof(kGost14CfbSV);
    rc                        = funcs->C_DecryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptInit failed: 0x%lx\n", rc);
        return rc;
    }
    // Нельзя указывать для входных и выходных данных
    // один и тот же буфер.
    rc = funcs->C_DecryptUpdate(sess, value, len, buf, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    rc = funcs->C_DecryptFinal(sess,
                               buf + sizeof(kGost14PlainText), &dummy_len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_DecryptFinal failed: 0x%lx\n", rc);
        return rc;
    }
    len = sizeof(kGost14PlainText);

    CHECK(buf, len, kGost14PlainText);
    printf("Decrypt OK\n");

    printf("Encrypt parts\n");
    mechanism->pParameter     = kGost14CfbSV;
    mechanism->ulParameterLen = sizeof(kGost14CfbSV);
    rc                        = funcs->C_EncryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptInit failed: 0x%lx\n", rc);
        return rc;
    }
    len = 5;
    rc  = funcs->C_EncryptUpdate(sess, kGost14PlainText, len,
                                 value, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    if (memcmp(value, kGost14CfbC, len) != 0)
    {
        fprintf(stderr, "Invalid ciphertext\n");
        return CKR_FUNCTION_FAILED;
    }
    printf("Encrypt part 1 OK\n");

    len = sizeof(kGost14PlainText) - 5;
    rc  = funcs->C_EncryptUpdate(sess, kGost14PlainText + 5, len,
                                 value + 5, &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, kGost14CfbC);
    printf("Encrypt part 2 OK\n");

    printf("Decrypt parts\n");
    mechanism->pParameter     = kGost14CfbSV;
    mechanism->ulParameterLen = sizeof(kGost14CfbSV);
    rc                        = funcs->C_DecryptInit(sess, mechanism, keyh);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptInit failed: 0x%lx\n", rc);
        return rc;
    }
    len = 17;
    rc  = funcs->C_DecryptUpdate(sess, value, len,
                                 buf, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        return rc;
    }
    if (memcmp(buf, kGost14PlainText, len) != 0)
    {
        fprintf(stderr, "Invalid decrypted text\n");
        return CKR_FUNCTION_FAILED;
    }
    printf("Decrypt part 1 OK\n");

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

    len = sizeof(kGost14PlainText);
    CHECK(buf, len, kGost14PlainText);
    printf("Decrypt part 2 OK\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;
    }

    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(data2) - 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(data2) - 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(data2) - 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;
    }
    rc = funcs->C_DecryptUpdate(sess, value2, 191, 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(data2) - 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;
}
