2012-09-03 119 views
3

我最近想通過使用BSD套接字來建立自己的客戶端 - 服務器系統。在經過一段時間之後,我想包含SSL來加密數據傳輸。我跟着this教程和代碼編譯罰款和Xcode(加鏈接標誌:-lssl -lcrypto),但我不斷收到EXC_BAD_ACCESS所有的時間,一旦程序到達SSL_CTX_use_certificate_file()電話。您可以在下面看到使用的代碼。SSL_CTX_use_certificate_file失敗EXC_BAD_ACCESS

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

#include <openssl/bio.h> 
#include <openssl/ssl.h> 
#include <openssl/err.h> 

int main(int argc, const char * argv[]) 
{ 
    SSL_METHOD *method = NULL; 
    SSL_CTX *ctx = NULL; 
    OpenSSL_add_all_algorithms(); 
    SSL_load_error_strings(); 
    method = SSLv2_server_method(); 
    ctx = SSL_CTX_new(method); 

    SSL_CTX_use_certificate_file(ctx, "/Users/steve/certificate.pem", SSL_FILETYPE_PEM); 
    SSL_CTX_use_PrivateKey_file(ctx, "/Users/steve/key.pem", SSL_FILETYPE_PEM); 

    printf("Hello, World!\n"); 
    return EXIT_SUCCESS; 
} 

如果程序在指定的路徑找不到證書,它不會崩潰,但我當然不會有任何SSL加密。證書本身可能有問題嗎?我簡單地使用以下命令生成一個與openssl:

# generate the key 
$ openssl genrsa -out key.pem 1024 

# generate request 
$ openssl req -new -key key.pem -out request.pem 
# fill in all the stuff ... 

# generate certificate 
$ openssl x509 -req -days 30 -in request.pem -signkey key.pem -out certificate.pem 

任何想法?

更新:其實有一些警告顯示了Mac OS X的部署目標編譯時設置爲10.7或更高版本,因爲這一切的SSL東西顯示爲過時。是否有任何推薦的替代方法來保護使用SSL的套接字?

+0

你的程序編譯OK(你有一些警告)? – TOC

+0

將OS X部署目標設置爲10.6或更低時沒有任何警告,因爲所有這些SSL東西都在10.7或更高版本中顯示爲棄用。是否有任何推薦的替代方法來保護使用SSL的套接字? – steverab

回答

4

的問題是,你需要調用SSL_library_init,請參閱修改裏面的代碼(這也是一個很好的做法,總是從我們稱之爲:-)功能處理錯誤:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <openssl/bio.h> 
#include <openssl/ssl.h> 
#include <openssl/err.h> 

int main(int argc, const char * argv[]) 
{ 
    //SSL_METHOD *method = NULL; 
    SSL_CTX *ctx = NULL; 
    OpenSSL_add_all_algorithms(); 
    SSL_load_error_strings(); 
    //method = SSLv2_server_method(); 
    //ctx = SSL_CTX_new(method); 

    /* Without this line you got an error when calling SSL_CTX_new */ 
    SSL_library_init(); 
    ctx = SSL_CTX_new(SSLv2_server_method()); 
    if(!ctx) 
    { 
     fprintf (stderr, "SSL_CTX_new ERROR\n"); 
     ERR_print_errors_fp(stderr); 
     return EXIT_FAILURE; 
    } 

    if (!SSL_CTX_use_certificate_file(ctx, "/Users/steve/certificate.pem", SSL_FILETYPE_PEM)) 
    { 
     fprintf (stderr, "SSL_CTX_use_certificate_file ERROR\n"); 
     ERR_print_errors_fp(stderr); 

     return EXIT_FAILURE; 
    } 
    SSL_CTX_use_PrivateKey_file(ctx, "/Users/steve/key.pem", SSL_FILETYPE_PEM); 

    printf("Hello, World!\n"); 
    return EXIT_SUCCESS; 
} 
+0

Aww,thx快速回答! – steverab

+0

@steverab:不客氣。謝謝。 – TOC