CryptEncrypt返回ERROR_MORE_DATA

时间:2015-11-10 08:58:10

标签: c winapi encryption wincrypt

我正在尝试使用wincrypt api来实现AES加密/解密。我已经编写了这段代码,但它并没有起作用。 CryptEncrypt会返回FALSEGetLastError() == 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);
    }
}

无论我在pdwDataLen中指定了什么值,它始终会返回FALSE并在pdwDataLen中增加值0x10

我做错了什么?

0 个答案:

没有答案