2016-11-25 4 views
0

Я хочу, чтобы создать зашифрованный чат-сервер с помощью OpenSSL в C так, взял код из: http://simplestcodings.blogspot.in/2010/08/secure-server-client-using-openssl-in-c.htmlКак создать чат-сервер с использованием OpenSSL в с

Я хочу, чтобы преобразовать этот код параллельного сервера чата, но как может Я делаю это?

, когда я пытаюсь соединить клиента с сервером, это просто показывает:

на стороне сервера:

Connection: 127.0.0.1:34902 
No certificates. 
Client msg: "Hello???" 

на стороне клиента:

Connected with AES256-GCM-SHA384 encryption 
Server certificates: 
Subject: /C=IN/ST=UK/L=DDN/O=UPES/OU=IT/CN=KAVIN/[email protected] 
Issuer: /C=IN/ST=UK/L=DDN/O=UPES/OU=IT/CN=KAVIN/[email protected] 
Received: "<html><body><pre>Hello???</pre></body></html> 

" 

Я хочу сделать зашифрованный чат между клиентом и сервером?

server.c

#include <stdio.h> 
#include <errno.h> 
#include <unistd.h> 
#include <malloc.h> 
#include <string.h> 
#include <sys/socket.h> 
#include <resolv.h> 
#include <netdb.h> 
#include <openssl/ssl.h> 
#include <openssl/err.h> 

#define FAIL -1 

int OpenConnection(const char *hostname, int port) 
{ int sd; 
    struct hostent *host; 
    struct sockaddr_in addr; 

    if ((host = gethostbyname(hostname)) == NULL) 
    { 
     perror(hostname); 
     abort(); 
    } 
    sd = socket(PF_INET, SOCK_STREAM, 0); 
    bzero(&addr, sizeof(addr)); 
    addr.sin_family = AF_INET; 
    addr.sin_port = htons(port); 
    addr.sin_addr.s_addr = *(long*)(host->h_addr); 
    if (connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0) 
    { 
     close(sd); 
     perror(hostname); 
     abort(); 
    } 
    return sd; 
} 

SSL_CTX* InitCTX(void) 
{ SSL_METHOD *method; 
    SSL_CTX *ctx; 

    OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */ 
    SSL_load_error_strings(); /* Bring in and register error messages */ 
    method = TLSv1_2_client_method(); /* Create new client-method instance */ 
    ctx = SSL_CTX_new(method); /* Create new context */ 
    if (ctx == NULL) 
    { 
     ERR_print_errors_fp(stderr); 
     abort(); 
    } 
    return ctx; 
} 

void ShowCerts(SSL* ssl) 
{ X509 *cert; 
    char *line; 

    cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */ 
    if (cert != NULL) 
    { 
     printf("Server certificates:\n"); 
     line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); 
     printf("Subject: %s\n", line); 
     free(line);  /* free the malloc'ed string */ 
     line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); 
     printf("Issuer: %s\n", line); 
     free(line);  /* free the malloc'ed string */ 
     X509_free(cert);  /* free the malloc'ed certificate copy */ 
    } 
    else 
     printf("Info: No client certificates configured.\n"); 
} 

int main(int count, char *strings[]) 
{ SSL_CTX *ctx; 
    int server; 
    SSL *ssl; 
    char buf[1024]; 
    int bytes; 
    char *hostname, *portnum; 

    if (count != 3) 
    { 
     printf("usage: %s <hostname> <portnum>\n", strings[0]); 
     exit(0); 
    } 
    SSL_library_init(); 
    hostname=strings[1]; 
    portnum=strings[2]; 

    ctx = InitCTX(); 
    server = OpenConnection(hostname, atoi(portnum)); 
    ssl = SSL_new(ctx);  /* create new SSL connection state */ 
    SSL_set_fd(ssl, server); /* attach the socket descriptor */ 
    if (SSL_connect(ssl) == FAIL) /* perform the connection */ 
     ERR_print_errors_fp(stderr); 
    else 

    { char *msg = "Hello???"; 

     printf("Connected with %s encryption\n", SSL_get_cipher(ssl)); 
     ShowCerts(ssl); 
     /* get any certs */ 
    while(1){ 
     SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */ 
     bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */ 
     buf[bytes] = 0; 
     printf("Received: \"%s\"\n", buf); 
     SSL_free(ssl);  /* release connection state */ 

} 
    close(server);   /* close socket */ 
    SSL_CTX_free(ctx);  /* release context */ 

    return 0; 
} 

Client.c

#include <stdio.h> 
#include <errno.h> 
#include <unistd.h> 
#include <malloc.h> 
#include <string.h> 
#include <sys/socket.h> 
#include <resolv.h> 
#include <netdb.h> 
#include <openssl/ssl.h> 
#include <openssl/err.h> 

#define FAIL -1 

int OpenConnection(const char *hostname, int port) 
{ int sd; 
    struct hostent *host; 
    struct sockaddr_in addr; 

    if ((host = gethostbyname(hostname)) == NULL) 
    { 
     perror(hostname); 
     abort(); 
    } 
    sd = socket(PF_INET, SOCK_STREAM, 0); 
    bzero(&addr, sizeof(addr)); 
    addr.sin_family = AF_INET; 
    addr.sin_port = htons(port); 
    addr.sin_addr.s_addr = *(long*)(host->h_addr); 
    if (connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0) 
    { 
     close(sd); 
     perror(hostname); 
     abort(); 
    } 
    return sd; 
} 

SSL_CTX* InitCTX(void) 
{ SSL_METHOD *method; 
    SSL_CTX *ctx; 

    OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */ 
    SSL_load_error_strings(); /* Bring in and register error messages */ 
    method = TLSv1_2_client_method(); /* Create new client-method instance */ 
    ctx = SSL_CTX_new(method); /* Create new context */ 
    if (ctx == NULL) 
    { 
     ERR_print_errors_fp(stderr); 
     abort(); 
    } 
    return ctx; 
} 

void ShowCerts(SSL* ssl) 
{ X509 *cert; 
    char *line; 

    cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */ 
    if (cert != NULL) 
    { 
     printf("Server certificates:\n"); 
     line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); 
     printf("Subject: %s\n", line); 
     free(line);  /* free the malloc'ed string */ 
     line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); 
     printf("Issuer: %s\n", line); 
     free(line);  /* free the malloc'ed string */ 
     X509_free(cert);  /* free the malloc'ed certificate copy */ 
    } 
    else 
     printf("Info: No client certificates configured.\n"); 
} 

int main(int count, char *strings[]) 
{ SSL_CTX *ctx; 
    int server; 
    SSL *ssl; 
    char buf[1024]; 
    int bytes; 
    char *hostname, *portnum; 

    if (count != 3) 
    { 
     printf("usage: %s <hostname> <portnum>\n", strings[0]); 
     exit(0); 
    } 
    SSL_library_init(); 
    hostname=strings[1]; 
    portnum=strings[2]; 

    ctx = InitCTX(); 
    server = OpenConnection(hostname, atoi(portnum)); 
    ssl = SSL_new(ctx);  /* create new SSL connection state */ 
    SSL_set_fd(ssl, server); /* attach the socket descriptor */ 
    if (SSL_connect(ssl) == FAIL) /* perform the connection */ 
     ERR_print_errors_fp(stderr); 
    else 

    { char *msg = "Hello???"; 

     printf("Connected with %s encryption\n", SSL_get_cipher(ssl)); 
     ShowCerts(ssl); 
     /* get any certs */ 
    while(1){ 
     SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */ 
     bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */ 
     buf[bytes] = 0; 
     printf("Received: \"%s\"\n", buf); 
     SSL_free(ssl);  /* release connection state */ 

} 
    close(server);   /* close socket */ 
    SSL_CTX_free(ctx);  /* release context */ 

    return 0; 
} 

Пожалуйста Комментарий изменения в коде для преобразования этого кода в зашифрованной сервер чата

ответ

2

Как вы уже используете функциональные возможности SSL , ваша программа чата фактически обеспечена. Но с вашего поста, похоже, вы хотите улучшить безопасное соединение. Для реализации шифрования и дешифрования, вы можете попробовать,

// Шифрование

AES_KEY encKey; 
AES_set_encrypt_key(key, 128, &encKey); 
AES_encrypt(text, out, &encKey); 

// дешифрование

AES_KEY decKey; 
AES_set_decrypt_key(key,128,&decKey); 
AES_decrypt(out, text, &decKey); 

Примечание: key должны быть общими

+0

На самом деле я хочу, чтобы отправлять и получать сообщений между cilent и сервером, чтобы он работал как зашифрованное приложение для перехвата. Поскольку в вышеприведенном коде im im не удалось отправить и получить сообщение s это просто говорит («привет») – kavin

+2

Логика заключается в том, чтобы зашифровать сообщение «привет», а затем отправить зашифрованное сообщение. Теперь с другой стороны с использованием общего ключа, расшифруйте сообщение. Если произойдет мошенничество/человек в средних атаках, тогда будет отправлено зашифрованное сообщение. Невозможно расшифровать сообщение без общего ключа. Это функции для шифрования и дешифрования. Вы можете использовать его в своем коде. –

+0

Возникает вопрос: как будут делиться ключи между этими двумя устройствами и как будет аутентифицироваться устройство/лицо. – zaph

Смежные вопросы