Skip to content

Instantly share code, notes, and snippets.

@crispy-computing-machine
Created December 16, 2023 15:24
Show Gist options
  • Save crispy-computing-machine/4c78e240e32677d8d8ddc21b4e2f9d75 to your computer and use it in GitHub Desktop.
Save crispy-computing-machine/4c78e240e32677d8d8ddc21b4e2f9d75 to your computer and use it in GitHub Desktop.
PHP Socket Transfer
<?php
class SocketTransfer {
private $sock;
private $client;
private $publicKey;
private $privateKey;
private $verbose;
public function __construct($host, $port, $publicKeyPath, $privateKeyPath, $verbose = false) {
$this->publicKey = file_get_contents($publicKeyPath);
$this->privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or $this->logError("Could not create socket");
socket_bind($this->sock, $host, $port) or $this->logError("Could not bind to socket");
socket_listen($this->sock) or $this->logError("Could not set up socket listener");
$this->verbose = $verbose;
}
public function logError($message) {
error_log($message);
if ($this->verbose) {
echo $message . "\n";
}
exit(1);
}
public function sendFile($filePath) {
$fileData = file_get_contents($filePath);
$symmetricKey = openssl_random_pseudo_bytes(32);
if (!openssl_public_encrypt($symmetricKey, $encryptedSymmetricKey, $this->publicKey)) {
$this->logError('Failed to encrypt symmetric key');
}
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encryptedData = openssl_encrypt($fileData, 'aes-256-cbc', $symmetricKey, 0, $iv);
$toSend = $iv . $encryptedSymmetricKey . $encryptedData;
for ($i = 0; $i < strlen($toSend); $i += 1024) {
$chunk = substr($toSend, $i, 1024);
if (@socket_write($this->client, $chunk, strlen($chunk)) === false) {
$this->logError('Failed to send data: ' . socket_strerror(socket_last_error()));
}
}
}
public function receiveFile($outputPath) {
$received = "";
while ($chunk = @socket_read($this->client, 1024)) {
$received .= $chunk;
}
$iv = substr($received, 0, 16);
$encryptedSymmetricKey = substr($received, 16, 256);
$encryptedData = substr($received, 272);
if (!openssl_private_decrypt($encryptedSymmetricKey, $symmetricKey, $this->privateKey)) {
$this->logError("Failed to decrypt symmetric key");
}
$decryptedData = openssl_decrypt($encryptedData, 'aes-256-cbc', $symmetricKey, 0, $iv);
if (file_put_contents($outputPath, $decryptedData) === false) {
$this->logError("Failed to write file");
}
}
public function acceptConnection() {
$this->client = socket_accept($this->sock) or $this->logError("Could not accept connection");
}
public function closeConnection() {
socket_close($this->client);
}
public function __destruct() {
socket_close($this->sock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment