2016-06-12 102 views
2

當我寫的代碼SHA_CTX詞shashSHA1_Final(哈希,&詞shash),我有段錯誤的錯誤,或者在其他情況下,我有255返回值我不理解爲什麼發生。這是一個簡單的例子。SHA1 OpenSSL的分段錯誤

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <openssl/sha.h> 
#include <openssl/bn.h> 
#include <openssl/ec.h> 
#include <openssl/obj_mac.h> 

int main() { 

    BIGNUM *x=BN_new(); 
    BIGNUM *y=BN_new(); 
    BIGNUM *n=BN_new(); 
    BIGNUM *e=BN_new(); 

    EC_POINT *P; 

    BN_CTX *ctx;//Buffer 

    const EC_POINT *G; //Generator Point 

    unsigned char hash[SHA_DIGEST_LENGTH]; 

    SHA_CTX shash; 
    SHA1_Init(&shash); 
    SHA1_Update(&shash, "abc", 3); 
    SHA1_Final(hash, &shash); 

    const EC_GROUP *curve = EC_GROUP_new_by_curve_name(NID_secp224r1); 

    P=EC_POINT_new(curve); 

    G=EC_GROUP_get0_generator(curve); 

    EC_GROUP_get_order(curve,n,ctx); 

    BN_rand_range(e,n); 

    EC_POINT_mul(curve,P,e,NULL,NULL,ctx); 

    if (!EC_POINT_is_on_curve(curve,P,ctx)) return -1; 
    if (!EC_POINT_get_affine_coordinates_GFp(curve, P, x, y, ctx)) return -1; 


    for(int i=0;i<SHA_DIGEST_LENGTH;i++) 
    { 
     printf("%02x",hash[i]); 
    } 


    return 0; 
} 
+0

如果我將來自SHA_CTX的代碼評論到SHA1_Final,那麼這個代碼工作。 – JLo

+0

使用更高版本的OpenSSL(如1.0.2和1.1.0)的建議方法是EVP界面。另請參閱OpenSSL wiki上的[EVP Message Digests](http://wiki.openssl.org/index.php/EVP_Message_Digests)。 – jww

回答

3

可以添加標記-Wall以在程序編譯時啓用每個警告。其中一個警告提示問題的由來:

main4.c:36:23: warning: ‘ctx’ is used uninitialized in this function [-Wuninitialized]

事實上,指針ctx的價值沒有被初始化。因此,ctx可以指向任何地方,這導致未定義的行爲,如分段錯誤。

您可以添加以下行嗎?

BN_CTX *ctx=BN_CTX_new();//Buffer 

它似乎解決了分段故障。我編譯gcc main.c -o main -I /usr/local/ssl/include -L /usr/local/ssl/lib -lssl -lcrypto -ldl -Wall -std=c99

+0

感謝您的支持@francis。小好奇心:爲什麼選擇C99標準而不是C89或C11?再次感謝。 – JLo

+0

不客氣!我使用了c99,因爲我的編譯器默認運行c89。因此,我得到了以下錯誤:''for'循環初始聲明只允許在C99模式下。因此,我切換到c99。當然,c11本來可以用來代替。 – francis

+0

非常感謝@francis。太好了! – JLo