Добавление SSL поддерживает к существующему коду TCP & UDP?

  1. члены структуры общедоступны по умолчанию, члены класса являются частными по умолчанию.
  2. наследование По умолчанию для Структуры от другой структуры или класса общедоступно. Наследование по умолчанию для класса от другой структуры или класса является частным.
class A{    
public:    
    int i;      
};

class A2:A{    
};

struct A3:A{    
};


struct abc{    
    int i;
};

struct abc2:abc{    
};

class abc3:abc{
};


int _tmain(int argc, _TCHAR* argv[])
{    
    abc2 objabc;
    objabc.i = 10;

    A3 ob;
    ob.i = 10;

    //A2 obja; //privately inherited
    //obja.i = 10;

    //abc3 obss;
    //obss.i = 10;
}

Это находится на VS2005.

12
задан Wannabe Tycoon 9 July 2009 в 18:16
поделиться

4 ответа

SSL is very complex, so you're going to want to use a library.

There are several options, such as Keyczar, Botan, cryptlib, etc. Each and every one of those libraries (or the libraries suggested by others, such as Boost.Asio or OpenSSL) will have sample code for this.


Answering your second question (how to integrate a library into existing code without causing too much pain): it's going to depend on your current code. If you already have simple functions that call the Winsock or socket methods to send/receive ints, strings, etc. then you just need to rewrite the guts of those functions. And, of course, change the code that sets up the socket to begin with.

On the other hand, if you're calling the Winsock/socket functions directly then you'll probably want to write functions that have similar semantics but send the data encrypted, and replace your Winsock calls with those functions.

However, you may want to consider switching to something like Google Protocol Buffers or Apache Thrift (a.k.a. Facebook Thrift). Google's Protocol Buffers documentation says, "Prior to protocol buffers, there was a format for requests and responses that used hand marshalling/unmarshalling of requests and responses, and that supported a number of versions of the protocol. This resulted in some very ugly code. ..."

You're currently in the hand marshalling/unmarshalling phase. It can work, and in fact a project I work on does use this method. But it is a lot nicer to leave that to a library; especially a library that has already given some thought to updating the software in the future.

If you go this route you'll set up your network connections with an SSL library, and then you'll push your Thrift/Protocol Buffer data over those connections. That's it. It does involve extensive refactoring, but you'll end up with less code to maintain. When we introduced Protocol Buffers into the codebase of that project I mentioned, we were able to get rid of about 300 lines of marshalling/demarshalling code.

11
ответ дан 2 December 2019 в 07:22
поделиться

Я рекомендую использовать GnuTLS как на стороне клиента, так и на стороне сервера, только для TCP-соединения. Забудьте пока о данных UDP. В документации GnuTLS есть пример кода для написания и клиентов, и серверов. Пожалуйста, поймите, что по крайней мере на стороне сервера (обычно ответчик TCP) должен быть сертификат; клиентская сторона может работать с анонимной идентификацией (хотя есть даже пример без сертификата сервера, использующий только обмен ключами DH, что допускает атаки типа «злоумышленник посередине»).

В общем, вполне вероятно, что вы будете должны понимать принципы SSL, независимо от того, какую библиотеку вы используете. Альтернативы библиотеке - OpenSSL (как для Unix, так и для Windows) и SChannel (только для Windows).

4
ответ дан 2 December 2019 в 07:22
поделиться

Пробовали ли вы поддержку SSL в Boost.Asio или ACE ? Оба используют OpenSSL под капотом и предоставляют аналогичные абстракции для TCP, UDP и SSL. Образец кода доступен как в дистрибутивах Boost.Asio, так и в ACE.

Возможно, вам нужно помнить, что SSL ориентирован на записи, а не на потоки (как TCP, так и UDP). Это может повлиять на то, как вы мультиплексируете события, поскольку вы должны, например, прочитать полную запись SSL, прежде чем вы сможете вызвать операцию чтения как завершенную.

2
ответ дан 2 December 2019 в 07:22
поделиться

Чтобы помочь справиться с этим без каких-либо изменений в приложении, вы можете взглянуть на проект stunnel ( http://www.stunnel.org/ ). Я не думаю, что он будет обрабатывать UDP за вас.

2
ответ дан 2 December 2019 в 07:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: