2012-09-03 118 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