#include "test_common.h"

CK_RV test_crypto();
CK_RV test_magma_cfb_errors(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_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 = funcs->C_GetMechanismInfo(SlotId, CKM_MAGMA_CFB, &minfo);
    if (rc != CKR_OK)
    {
        fprintf(stderr,
                "\n======== Mechanism CKM_MAGMA_CFB not supported ===========\n");
    }
    else
    {
        fprintf(stderr,
                "\n==================== CKM_MAGMA_CFB errors test ==================\n");
        rc = test_magma_cfb_errors(hSession);
        if (rc != CKR_OK)
        {
            fprintf(stderr,
                    "ERROR CKM_MAGMA_CFB errors test failed, rc = 0x%lx\n", rc);
            return rc;
        }
        else
        {
            fprintf(stderr, "CKM_MAGMA_CFB errors 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_magma_cfb_errors(CK_SESSION_HANDLE sess)
{
    CK_RV                  rc = CKR_OK;
    CK_ULONG               len;
    CK_BYTE                value[1024];
    CK_OBJECT_HANDLE       keyh = CK_INVALID_HANDLE;
    CK_MECHANISM           mechanism_desc = { CKM_MAGMA_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_GOST28147;	// Тоже работает
    static CK_KEY_TYPE     key_type = CKK_MAGMA;

    static CK_BYTE         key[] = {
        0xc3, 0x73, 0x0c, 0x5c, 0xbc, 0xca, 0xcf, 0x91,
        0x5a, 0xc2, 0x92, 0x67, 0x6f, 0x21, 0xe8, 0xbd,
        0x4e, 0xf7, 0x53, 0x31, 0xd9, 0x40, 0x5e, 0x5f,
        0x1a, 0x61, 0xdc, 0x31, 0x30, 0xa6, 0x50, 0x11,
    };
    static CK_BYTE         data[] = {
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    //par_cipher_Z (TC 26 Z)
//    static CK_BYTE      oid6[] = {
//        0x06, 0x09, 0x2a, 0x85, 0x03, 0x07, 0x01, 0x02, 0x05, 0x01, 0x01
//    };
    static CK_BYTE      et6[] = {
		0xe1, 0xfa, 0x24, 0xd5, 0x79, 0x0f, 0xb6, 0x4a,
		0xde, 0xb0, 0x1d, 0xec, 0x2d, 0xd5, 0x28, 0x8a,
    };

    static CK_ATTRIBUTE key_template[] = {
        { CKA_CLASS,           &oclass,   sizeof(oclass)   },
        { CKA_KEY_TYPE,        &key_type, sizeof(key_type) },
//        { CKA_GOST28147PARAMS, oid6,      sizeof(oid6)     },
        { CKA_ENCRYPT,         &ltrue,    sizeof(CK_BBOOL) },
        { CKA_DECRYPT,         &ltrue,    sizeof(CK_BBOOL) },
        { CKA_VALUE,           key,       sizeof(key)      }
    };
    static CK_BYTE      ivec[8] = { 1, 0, 0, 0, 0, 0, 0, 0 };

    printf("Zero Data\n");
    printf("Param Set Z\n");
    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("Testing returned error codes\n");
	printf("Try to call C_Encrypt without C_EncryptInit\n");
    len = sizeof(data);
    rc  = funcs->C_Encrypt(sess, data, len, value, &len);
	if (rc != CKR_OPERATION_NOT_INITIALIZED) {
		fprintf(stderr, "Can't call C_Encrypt without C_EncryptInit\n");
		rc = CKR_FUNCTION_FAILED;
		goto end;
	} else {
		printf("Uninitialized C_Encrypt returned CKR_OPERATION_NOT_INITIALIZED - it's OK\n");
	}

    mechanism->pParameter     = ivec;
    mechanism->ulParameterLen = sizeof(ivec);
    rc                        = funcs->C_EncryptInit(sess, mechanism, keyh);
    PROCESS_ERROR("C_EncryptInit", rc, end);

	printf("Try to call C_EncryptInit twice\n");
    rc                        = funcs->C_EncryptInit(sess, mechanism, keyh);
	if (rc != CKR_OPERATION_ACTIVE) {
		fprintf(stderr, "Can't call C_EncryptInit while active\n");
		rc = CKR_FUNCTION_FAILED;
		goto end;
	} else {
		printf("Second C_EncryptInit returned CKR_OPERATION_ACTIVE - it's OK\n");
		printf("The encryption context should not be changed\n");
	}

	printf("Try to set too small output buffer to C_Encrypt\n");
    len = sizeof(data)-1;
    rc  = funcs->C_Encrypt(sess, data, sizeof(data), value, &len);
	if (rc != CKR_BUFFER_TOO_SMALL) {
		fprintf(stderr, "Can't set too small output buffer for C_Encrypt\n");
		rc = CKR_FUNCTION_FAILED;
		goto end;
	} else {
		printf("C_Encrypt returned CKR_BUFFER_TOO_SMALL - it's OK\n");
		printf("The encryption context should not be changed\n");
	}

	printf("Try to get output buffer size only\n");
	printf("The encryption context should not be changed\n");
    len = 0;
    rc  = funcs->C_Encrypt(sess, data, sizeof(data), NULL, &len);
    PROCESS_ERROR("C_EncryptInit", rc, end);

	printf("Use correct output buffer and call C_Encrypt once more\n");
    rc  = funcs->C_Encrypt(sess, data, len, value, &len);
    PROCESS_ERROR("C_Encrypt", rc, end);

    CHECK(value, len, et6);

	printf("Try to call yet another C_Encrypt after C_Encrypt\n");
    rc  = funcs->C_Encrypt(sess, data, len, value, &len);
	if (rc != CKR_OPERATION_NOT_INITIALIZED) {
		fprintf(stderr, "Can't call C_Encrypt just after C_Encrypt\n");
		rc = CKR_FUNCTION_FAILED;
		goto end;
	} else {
		printf("Finalized C_Encrypt returned CKR_OPERATION_NOT_INITIALIZED - it's OK\n");
	}

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

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

    len = sizeof(data) - 9;
    rc  = funcs->C_EncryptUpdate(sess, data + 9, len, value + 9, &len);
    if (rc != CKR_OK)
    {
        fprintf(stderr, "C_EncryptUpdate failed: 0x%lx\n", rc);
        goto end;
    }
	// Get final size only with NULL buffer
	printf("Call C_EncryptFinal with NULL buffer to get output size\n");
	printf("The encryption context should not be finalized so far\n");
    len = 0;
    rc  = funcs->C_EncryptFinal(sess, NULL, &len);
    PROCESS_ERROR("C_EncryptFinal", rc, end);
    rc = funcs->C_EncryptFinal(sess, value+sizeof(data), &len);
    PROCESS_ERROR("C_EncryptFinal", rc, end);

    CHECK(value, sizeof(et6), et6);

	printf("Try to call C_EncryptFinal once more\n");
    rc  = funcs->C_EncryptFinal(sess, NULL, &len);
	if (rc == CKR_OPERATION_NOT_INITIALIZED) {
		printf("C_EncryptFinal returned CKR_OPERATION_NOT_INITIALIZED - it's OK\n");
	} else {
		PROCESS_ERROR("C_EncryptFinal", rc, end);
		rc = CKR_FUNCTION_FAILED;
		goto end;
	}

    printf("SUCCESS\n");
    rc = CKR_OK;
 end:
    if (keyh != CK_INVALID_HANDLE)
    {
        funcs->C_DestroyObject(sess, keyh);
    }

    return rc;
}

