I need some advice about the best way to encrypt data for transmission across sockets using PHP.
I am currently developing a distributed application wherein a centralized computer (call it a Manager) must communicate via socket with dozens of client computers. I am required to make sure these socket communications are encrypted for security. I am required to use sockets for latency reasons.
I know that PHP has the mcrypt libraries. This page has some sample code:
<?php
// Designate string to be encrypted
$string = "Applied Cryptography, by Bruce Schneier, is
a wonderful cryptography reference.";
// Encryption/decryption key
$key = "Four score and twenty years ago";
// Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_128;
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
MCRYPT_MODE_ECB), MCRYPT_RAND);
// Output original string
print "Original string: $string <p>";
// Encrypt $string
$encrypted_string = mcrypt_encrypt($cipher_alg, $key,
$string, MCRYPT_MODE_CBC, $iv);
// Convert to hexadecimal and output to browser
print "Encrypted string: ".bin2hex($encrypted_string)."<p>";
$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
$encrypted_string, MCRYPT_MODE_CBC, $iv);
print "Decrypted string: $decrypted_string";
?>
The problem with using mcrypt is that both Manager and client must know the $key and the $iv. I have no idea what an initialization vector is, BTW. Obviously, I can't just communicate these values over the socket because then security would be totally compromised. Communicating them ahead of time in a config file also seems like a bad idea. It would seem like I need an SSL-like connection protocol.
Rather than reinventing the wheel, I was imagining that each client, when initializing a connection, might request some $key and $iv value from the central Manager over an encrypted SSL connection using cURL. I could then rely on cURL to negotiate a secure connection and then share some randomly generated $key safely.
Questions:
1) Is this process secure (i.e., request $key via SSL, use mCrypt and $key to encrypt/decrypt all communications) ?
2) Is mCrypt the best way to go in terms of speed performance?
3) Might there be some easy way to implement a handshake for exchange of public keys?
4) Does some code library already exist to accomplish secure connections via socket?
Any help would be much appreciated.