2014-12-03 59 views
1

我正在嘗試編寫一個小程序在CBC模式下使用OpenSSL和AES加密某些內容。 這裏是我的代碼:Segfault from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0

#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 ...但是,所有參數似乎初始化,我試圖打印他們的價值觀,我沒有得到任何問題?

所以我不真的搞錯我做錯了,有人可以幫我嗎?非常感謝你:)

+0

分割故障這麼多的理由,沒有調用堆棧顯示?首先,你需要調試你的程序,看看它在哪條線上崩潰...... – neo 2014-12-03 10:37:02

+0

嗯,我只是做了它,它似乎是'AES_cbc_encrypt(aes_input,enc_out,15,&enc_key,iv AES_ENCRYPT)'這一行,這使得我的程序崩潰。我將修改我的帖子以表明它 – Raoul722 2014-12-03 10:39:34

+0

您需要進一步瞭解該功能。 – neo 2014-12-03 10:41:54

回答

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

+0

謝謝你的回答。那麼這意味着我的測試是無用的,對嗎?但我不知道如何正確測試......無論如何,我不認爲這是我的段錯誤的來源 – Raoul722 2014-12-03 10:44:18

+1

您的段錯誤的來源可能是'const uint64_t encslength =((sizeof(aes_input)/ sizeof(aes_input [ 0])...'因爲'aes_input'是一個指針(不是一個數組) – 2014-12-03 10:47:52

+0

那麼我在我的代碼中用'100'替換了'encslength',我仍然在'AES_cbc_encrypt(aes_input,enc_out,15 ,&enc_key,iv AES_ENCRYPT)'。但是非常感謝您的幫助 – Raoul722 2014-12-03 10:54:18