1

I am trying to use wincrypt api to implement AES encryption/decryption. I've written this code, but it doesn't work. CryptEncrypt returns FALSE and GetLastError() == ERROR_MORE_DATA.

typedef struct
{
    BLOBHEADER  hdr;
    DWORD       key_size;
    BYTE        bytes[32];
} AES256_KEY_BLOB;

static uint8_t  g_test_key[32] = {
    0x09, 0xA2, 0x3A, 0x88, 0x90, 0xF2, 0x88, 0x40,
    0x98, 0x47, 0x34, 0x53, 0x80, 0x45, 0x7D, 0xF0, 
    0x82, 0x97, 0x09, 0x23, 0xA7, 0xE8, 0x23, 0xF7,
    0x39, 0x78, 0x73, 0x45, 0x34, 0x9A, 0x97, 0xA2
};

static struct {
    uint8_t test_data[1024];
    size_t  test_data_len;
} g_test_vectors[] = {
    { "hello, world!!!!", 16 }
};

void test()
{
    HCRYPTPROV  h_aes_crypt_provider;
    BOOL        b_stat;

    b_stat = CryptAcquireContext(
        &h_aes_crypt_provider, 0, 0, PROV_RSA_AES, CRYPT_VERIFYCONTEXT
        );

    if (b_stat)
    {
        AES256_KEY_BLOB key_blob;
        HCRYPTKEY       h_key;

        key_blob.hdr.bType    = PLAINTEXTKEYBLOB;
        key_blob.hdr.bVersion = CUR_BLOB_VERSION;
        key_blob.hdr.reserved = 0;
        key_blob.hdr.aiKeyAlg = CALG_AES_256;
        key_blob.key_size     = 32;

        memcpy(&key_blob.bytes, &g_test_key, key_blob.key_size);

        b_stat = CryptImportKey(
            h_aes_crypt_provider,
            (const BYTE*)&key_blob, sizeof(key_blob),
            0, 0, &h_key
            );

        if (b_stat)
        {
            char    test_buf[1024];
            DWORD   test_buf_len = sizeof(test_buf);

            memcpy(
                &test_buf,
                g_test_vectors[0].test_data,
                g_test_vectors[0].test_data_len
                );

            b_stat = CryptEncrypt(
                h_key, 0, TRUE, 0,
                &test_buf, &test_buf_len,
                g_test_vectors[0].test_data_len
                );

            if (b_stat)
            {
                printf("success\n");
            }
            else
            {
                printf("last_err:0x%.8x", GetLastError());
            }

            CryptDestroyKey(h_key);
        }

        CryptReleaseContext(h_aes_crypt_provider, 0);
    }
}

Whatever value I specify in pdwDataLen, it always returns FALSE and increases value in pdwDataLen by 0x10.

what am I doing wrong?

4

0 回答 0