locked
Why AES-128 block cipher on Windows using crypto library requires twice the block size in output buffer? RRS feed

  • Question

  • Hi,

    when encrypting using CALG_AES_128, the output buffer requires twice the block size of input?

    My requirement is  the output buffer size should be same as input block size.How to achieve this?

    Below I have given my code

    BYTE pbBuffer[] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34
        , 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    BYTE iv[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x0A
        , 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
    HCRYPTPROV hProvider;
    HCRYPTKEY hKey;

    struct KEYBLOB {
        BLOBHEADER bh;
        DWORD dwKeyLen;
        BYTE bytes[16];
    }blob;

    blob.bh.bType = PLAINTEXTKEYBLOB;
    blob.bh.reserved = 0;
    blob.bh.bVersion = CUR_BLOB_VERSION;
    blob.bh.aiKeyAlg = CALG_AES_128;
    blob.dwKeyLen = 16;
    memcpy(blob.bytes, pbBuffer, 16);


    if (!CryptAcquireContext(&hProvider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
        printf("CryptAcquireContext Error\n");
        return FALSE;
    }

    if (!CryptImportKey(hProvider, (BYTE*)&blob, sizeof(KEYBLOB), NULL, CRYPT_NO_SALT, &hKey)){
        printf("CryptImportKey Error\n");
        CryptReleaseContext(hProvider, 0);
        return FALSE;
    }

    DWORD mode = CRYPT_MODE_ECB;
    CryptSetKeyParam( hKey, KP_MODE, (BYTE*)&mode, 0 );


        // Encrypt the data
        if( !CryptEncrypt( hKey, 0, TRUE, 0, Data, pDataLen, *pDataLen))
    {
    DWORD dwResult = GetLastError();
            return false;
    }


    • Edited by sgrm123 Wednesday, February 10, 2016 12:30 PM
    Wednesday, February 10, 2016 12:29 PM

Answers

All replies

  • On 2/10/2016 7:29 AM, sgrm123 wrote:

    when encrypting using CALG_AES_128, the output buffer requires twice the block size of input?

    To be precise, the output can be up to one block size larger than input, due to padding. If you encrypt exactly one block's worth of data, then yes, the output would be two blocks, thus double the size.

    My requirement is  the output buffer size should be same as input block size.How to achieve this?

    Change the requirement, or use a stream cypher instead of a block cypher.

    Wednesday, February 10, 2016 2:35 PM
  • How to do stream cypher with AES?
    Thursday, February 11, 2016 6:17 AM
  • use CFB mode or other stream cyper mode
    Thursday, February 11, 2016 9:48 AM
    • Proposed as answer by Hart Wang Friday, February 26, 2016 7:14 AM
    • Marked as answer by Hart Wang Monday, February 29, 2016 6:56 AM
    Wednesday, February 24, 2016 10:47 AM