使用openssl C进行AES(aes-cbc-128,aes-cbc-192,aes-cbc-256)加密/解密

20

我只想使用OpenSSL测试AES的这三种模式:128、192和256位密钥长度,但我的解密文本与输入不同,我不知道为什么。此外,当我传递一个巨大的输入长度(比如说1024字节)时,我的程序会显示core dumped... 我的输入始终是相同的,但现在并不重要。以下是代码:

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

int main(int argc, char **argv)
{
    int i;
    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];
    memset(aes_key, 0, sizeof(aes_key));
    if (!RAND_bytes(aes_key, keylength))
    {
        exit(-1);
    }
    aes_key[keylength-1] = '\0';

    int inputslength;
    printf("Give an input's length:\n");
    scanf("%d", &inputslength);

    /* generate input with a given length */
    unsigned char aes_input[inputslength+1];
    memset(aes_input, '0', sizeof(aes_input));
    aes_input[inputslength] = '\0';

    /*printf("original:\t");
    for(i=0; i<inputslength; i++)
    {
        printf("%c ", aes_input[i]);
    }
    printf("\n");*/

    /* init vector */
    unsigned char iv[AES_BLOCK_SIZE];
    if (!RAND_bytes(iv, AES_BLOCK_SIZE))
    {
        exit(-1);
    }

    //printf("AES_BLOCK_SIZE = %d\n", AES_BLOCK_SIZE); // aes block size is 16 bytes = 128 bits
    AES_KEY enc_key, dec_key;
    unsigned char enc_out[AES_BLOCK_SIZE];
    unsigned char dec_out[AES_BLOCK_SIZE];

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

    AES_set_decrypt_key(aes_key, keylength, &dec_key);
    AES_decrypt(enc_out, dec_out, &dec_key);

    printf("original:\t");
    for(i=0;*(aes_input+i)!=0x00;i++)
        printf("%X ",*(aes_input+i));
    printf("\nencrypted:\t");

    for(i=0;*(enc_out+i)!=0x00;i++)
        printf("%X ",*(enc_out+i));

    printf("\ndecrypted:\t");
    for(i=0;*(dec_out+i)!=0x00;i++)
        printf("%X ",*(dec_out+i));
    printf("\n");

    /*printf("\n\noriginal:\t");
    for(i=0; i<inputslength; i++)
    {
        printf("%x ", dec_out[i]);
    }
    printf("\n");*/


    return 0;
}

编辑:

当我将输出大小更改为inputslength而不是AES_BLOCK_SIZE时,我得到了结果:

Give a key length [only 128 or 192 or 256!]:
128
Give an input's length:
5
original:       30 30 30 30 30 
encrypted:      94 56 50 7E 19 B2 1C CE 20 23 4A E7 10 AF DB E3 30 30 30 30 30 
decrypted:      E1 5F F4 3D E8 8D 91 19 CD 3E 22 1E AF 1C 8F 5A 94 56 50 7E 19 B2 1C CE 20 23 4A E7 10 AF DB E3 30 30 30 30 30

那么输出大小和iv的大小是否有问题呢?它们应该具有什么大小(对于AES-CBC-128,AES-CBC-192,AES-CBC-256)?


2
附注:您的AES密钥无需以空字符结束。它只是一堆随机字节;仅此而已。没有任何关于空字符的内容,因此aes_key[keylength-1] = '\0'是毫无意义的(除了它总是将您的密钥的最后一个字节(恰好比所需的大8倍)设置为零。) - WhozCraig
@WhozCraig:谢谢,很高兴知道这个。那主要问题呢?你有什么想法吗? - ivy
1
很多。加密和解密的缓冲区大小远远不够大,你需要一个通用的十六进制打印函数,而不是试图将这些东西视为字符数据。这是二进制的。现在正在形成正式答案,但开始在那里寻找。 - WhozCraig
1
你不应该使用 AES_encrypt 和相关函数,而应该使用 EVP_* 函数。请参考 OpenSSL wiki 上的 EVP Symmetric Encryption and Decryption。事实上,你应该使用认证加密,因为它提供了*机密性和真实性两个方面的保护。请参考 OpenSSL wiki 上的 EVP Authenticated Encryption and Decryption - jww
2个回答

29

看一下你代码的修改版,注意以下几点:

  1. 添加了 hex_print 函数(小改动)
  2. 对密钥缓冲区进行了适当的大小调整(中等难度)。
  3. 对输出加密缓冲区进行了适当的大小调整(必须是块大小的倍数,如果原始源缓冲区是完整的块大小的倍数,则仍需要一个完整的填充块(参见 PKCS 5 填充方式获取更多信息)。
  4. 加密和解密使用相同的 IV。
  5. 最后,尽管看起来有些奇怪,但 AES_cbc_encrypt() 被用于 加密和解密(请查看调用中的最后一个参数)。

源代码

#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;
}

测试输出

Give a key length [only 128 or 192 or 256!]:
128
Give an input's length:
10
original:   58 58 58 58 58 58 58 58 58 58 
encrypt:    A9 66 C5 24 A4 02 AB 96 08 65 F7 22 A5 FB BE 26 
decrypt:    58 58 58 58 58 58 58 58 58 58 

第二次测试输出

Give a key length [only 128 or 192 or 256!]:
128
Give an input's length:
10
original:   58 58 58 58 58 58 58 58 58 58 
encrypt:    C2 47 6D B1 A1 68 29 53 55 74 C5 CC 3F 27 0A 3F 
decrypt:    58 58 58 58 58 58 58 58 58 58 

我真诚地希望这能帮到您。

抱歉打扰您了,您是正确的,现在一切都很好 :) - ivy
我认为这段代码有问题。我的测试用例是:keylen=128,inputlen=100。你应该再次测试它。 - g10guang
如果您能描述一下您认为它应该做什么,它实际上正在做什么以及它们之间的区别,我会很感兴趣知道您为什么认为它是错误的。但事实上它并没有错。它正好做了我想要的事情:生成一个随机密钥、一个随机IV、加密一个由“X”字符填充的常量数据块、解密相同的数据,并演示原始、加密和解密数据(其中原始和解密的数据应该是相同的,而且它们确实是相同的),使用十六进制转储进行输出。也许它并不是您认为的那样,这可能就是产生分歧的地方。 - WhozCraig

3

@WhozCraig:非常感谢你的帮助!这为我解释了很多问题!但还有一个问题。我将静态数组改变为动态数组。当我这样做时,出现了一些错误。但只有在输入量很大时才会发生错误,看看valgrind输出:http://pastie.org/private/bzofrrtgrlzr0doyb3g。只有当我传递大量输入时才会出错,当我传递小尺寸(像你的例子中,10)时,一切都正常。其他所有东西都运作得很完美。

#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)
{
    size_t inputslength = 0;
    printf("Give an input's length:\n");
    scanf("%lu", &inputslength);

    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 = (unsigned char*)malloc(sizeof(unsigned char) * (keylength/8));
    memset(aes_key, 0, keylength/8);
    RAND_bytes(aes_key, keylength/8);

    //  generate input with a given length
    unsigned char *aes_input = (unsigned char*)malloc(sizeof(unsigned char) * (inputslength));
    memset(aes_input, 'X', sizeof(aes_input));

    // init vectors
    unsigned char *iv_enc = (unsigned char*)malloc(sizeof(unsigned char) * (AES_BLOCK_SIZE));
    unsigned char *iv_dec = (unsigned char*)malloc(sizeof(unsigned char) * (AES_BLOCK_SIZE));
    // iv_dec == iv_enc
    RAND_bytes(iv_enc, AES_BLOCK_SIZE);
    memcpy(iv_dec, iv_enc, AES_BLOCK_SIZE);

    // buffers for encryption and decryption
    const size_t length = (((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE);
    unsigned char *enc_out = (unsigned char*)malloc(sizeof(unsigned char) * (length));
    unsigned char *dec_out = (unsigned char*)malloc(sizeof(unsigned char) * (inputslength));

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

    AES_set_decrypt_key(aes_key, keylength, &decKey);
    AES_cbc_encrypt(enc_out, dec_out, length, &decKey, 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));

    free(aes_key);
    aes_key = NULL;
    free(aes_input);
    aes_input = NULL;
    free(iv_enc);
    iv_enc = NULL;
    free(iv_dec);
    iv_dec = NULL;
    free(enc_out);
    enc_out = NULL;
    free(dec_out);
    dec_out = NULL;

    return 0;
}

编辑:

好的,我之前发布的代码有问题,这里是一个新的代码,即使输入很大也可以完美地工作。再次感谢你的帮助!:)

#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 = (unsigned char*)malloc(sizeof(unsigned char) * (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 = (unsigned char*)malloc(sizeof(unsigned char) *inputslength);
    memset(aes_input, 'X', inputslength);

    /* init vector */
    unsigned char *iv_enc = (unsigned char*)malloc(sizeof(unsigned char) *AES_BLOCK_SIZE), *iv_dec = (unsigned char*)malloc(sizeof(unsigned char) *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 = (unsigned char*)malloc(sizeof(unsigned char) *encslength);
    unsigned char *dec_out = (unsigned char*)malloc(sizeof(unsigned char) *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, inputslength);

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

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

    // free memory here

    return 0;
}

6
请再看一遍。使用指针时,sizeof()的意义与使用固定或可变数组时完全不同。它成为一个指针的大小,而不是为其分配的数据的大小。所有的大小都应该是变量; 不是 sizeof(something)。修复这个问题,我敢打赌你最终的问题会解决。 (附注:在常规C编程中,不要转换malloc()。它可能会导致非常微妙的问题,特别是对于可移植性。C ++需要它,但是首先,在C ++中不应该使用malloc()。) = P - WhozCraig
1
非常感谢您!这是一个可工作的示例:http://pastie.org/private/dtvmftozmru02webkzzq。 我使用了malloc,因为我的gcc告诉我要这么做 - 我记得malloc返回void类型,对吧? 当我用C ++编写代码时,我会使用newdelete,我知道在C ++中不应该使用malloc ;) - ivy
2
在C编程中,将malloc()强制转换可能存在潜在的问题。显然,在C++中是必需的,但正如你所说,你使用newdelete。在该网站上查找“casting malloc [c]”。这是一个相当有争议的问题。除此之外,非常高兴你已经运行起来了。 - WhozCraig
感谢您的实现! - Dano
1
@Puffin 这是不正确的。必须留出多达一个完整填充块的空间。这就是PKCS#5填充的工作方式。如果您没有考虑到这种情况,那么任何“有效”的方法都只是因为要加密的明文不是 AES块大小(16字节)的精确倍数,并且因此在该情况最终发生时会成为一颗定时炸弹。请参见此处的PKCS5/7填充,特别是描述遇到精确块大小倍数时会发生什么的段落。 - WhozCraig
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接