解密时在AES_encrypt函数中指定输入字符串长度

时间:2014-07-28 07:32:58

标签: c encryption openssl aes

我试图执行以下问题中给出的答案 - AES (aes-cbc-128, aes-cbc-192, aes-cbc-256) encryption/decryption with openssl C

我不妨在这里发布代码 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/rand.h>

// a simple hex-print routine. could be modified to print 16 bytes-per-line
static void hex_print(const void* pv, size_t len)
{
    const unsigned char * p = (const unsigned char*)pv;
    if (NULL == pv)
        printf("NULL");
    else
    {
        size_t i = 0;
        for (; i<len;++i)
            printf("%02X ", *p++);
    }
    printf("\n");
}

// main entrypoint
int main(int argc, char **argv)
{
    int keylength;
    printf("Give a key length [only 128 or 192 or 256!]:\n");
    scanf("%d", &keylength);

    /* generate a key with a given length */
    unsigned char aes_key[keylength/8];
    memset(aes_key, 0, keylength/8);
    if (!RAND_bytes(aes_key, keylength/8))
        exit(-1);

    size_t inputslength = 0;
    printf("Give an input's length:\n");
    scanf("%lu", &inputslength);

    /* generate input with a given length */
    unsigned char aes_input[inputslength];
    memset(aes_input, 'X', inputslength);

    /* init vector */
    unsigned char iv_enc[AES_BLOCK_SIZE], iv_dec[AES_BLOCK_SIZE];
    RAND_bytes(iv_enc, AES_BLOCK_SIZE);
    memcpy(iv_dec, iv_enc, AES_BLOCK_SIZE);

    // buffers for encryption and decryption
    const size_t encslength = ((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
    unsigned char enc_out[encslength];
    unsigned char dec_out[inputslength];
    memset(enc_out, 0, sizeof(enc_out));
    memset(dec_out, 0, sizeof(dec_out));

    // so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
    AES_KEY enc_key, dec_key;
    AES_set_encrypt_key(aes_key, keylength, &enc_key);
    AES_cbc_encrypt(aes_input, enc_out, inputslength, &enc_key, iv_enc, AES_ENCRYPT);

    AES_set_decrypt_key(aes_key, keylength, &dec_key);
    AES_cbc_encrypt(enc_out, dec_out, encslength, &dec_key, iv_dec, AES_DECRYPT);

    printf("original:\t");
    hex_print(aes_input, sizeof(aes_input));

    printf("encrypt:\t");
    hex_print(enc_out, sizeof(enc_out));

    printf("decrypt:\t");
    hex_print(dec_out, sizeof(dec_out));

    return 0;
}

这样运行正常,但我想加密一次字符串然后稍后解密,所以我手边没有inputslength。因此,我将无法计算encslength

如何在不知道已加密的实际字符串的情况下获取encslength

1 个答案:

答案 0 :(得分:1)

由于活动不多,我会将评论转为答案: 你不需要&#34;计算&#34; encslength:它是您获得的加密字符串的长度。 如果您存储字符串以供以后解密,您就知道它的大小。

只有在加密并且必须准备输出缓冲区时才需要计算:AES处理具有预定义大小的块:如果输入字符串的长度不是AES_BLOCK_SIZE的倍数,则输入将被填充(你会得到更大的输出)。 无论如何,您获得的输出字符串的大小必须是AES_BLOCK_SIZE的倍数。该字符串将被解密为一个字符串,其长度应小于或等于您的加密消息。