来自/lib/x86_64-linux-gnu/libcrypto.so.1.0.0的Segfault

时间:2014-12-03 10:31:37

标签: c cryptography openssl segmentation-fault aes

我正在尝试编写一个小程序来在CBC模式下使用OpenSSL和AES加密某些东西。 这是我的代码:

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

// main entrypoint
int main(int argc, char **argv)
{

    unsigned char *aes_key = malloc(32*sizeof(unsigned char));
        printf("Enter a 32 char key\n");
        scanf("%s", aes_key);
        if ((sizeof(aes_key)/sizeof(aes_key[0])) != 8) {
            fprintf(stderr,"you didn't write 32 char\n");
            return -1;
        }


    uint64_t msg = 30849384302932039;

    /* generate input with a given length */
    unsigned char *aes_input = malloc(100*sizeof(unsigned char));
    sprintf(aes_input, "%lu", msg);

    /* init vector */
    unsigned char *iv = (unsigned char*)malloc(sizeof(unsigned char) *AES_BLOCK_SIZE);
    RAND_bytes(iv, AES_BLOCK_SIZE);

    // buffers for encryption and decryption
    unsigned char *enc_out = malloc(sizeof(unsigned char)*16);
    sprintf(enc_out, "%d", 0);

    AES_KEY enc_key, dec_key;
    AES_set_encrypt_key(aes_key, 32, &enc_key);
    AES_cbc_encrypt(aes_input, enc_out, 16, &enc_key, iv, AES_ENCRYPT);

    printf("original:\t + %s\n",aes_input);
    printf("encrypt:\t + %s\n",enc_out);

    return 0;
}

我用gcc -g test.c -lcrypto -o test编译它,但是当我运行它时,我得到一个分段错误,gdb指示我:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a7b9a0 in ?? () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0

在尝试调试之后,我发现第AES_cbc_encrypt(aes_input, enc_out, 15, &enc_key, iv, AES_ENCRYPT);行负责segfaut ......但是,所有参数似乎都已初始化,我试图打印它们的值并且我没有遇到任何问题?

所以我真的不知道我做错了什么,有人能帮助我吗?非常感谢你:))

1 个答案:

答案 0 :(得分:1)

unsigned char *aes_key = malloc(32*sizeof(unsigned char));
...
if ((sizeof(aes_key)/sizeof(aes_key[0])) != 8) {

这不是获得数组的大小(32),而是指向unsigned char的指针的大小。

相同
const uint64_t encslength = ((sizeof(aes_input)/sizeof(aes_input[0]) + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;

看看Question 7.28 of C FAQ