Files
cell/examples/seif_server.js
John Alanbrook f4ea552271
Some checks failed
Build and Deploy / build-macos (push) Failing after 5s
Build and Deploy / build-windows (CLANG64) (push) Has been cancelled
Build and Deploy / package-dist (push) Has been cancelled
Build and Deploy / deploy-itch (push) Has been cancelled
Build and Deploy / deploy-gitea (push) Has been cancelled
Build and Deploy / build-linux (push) Has been cancelled
initial try at seif handshake example
2025-05-25 00:07:20 -05:00

85 lines
2.6 KiB
JavaScript

// Seif Handshake Server Example
// Implements the Seif Protocol handshake as described in the documentation
var crypto = use('crypto');
var json = use('json');
var io = use('io');
// Server's key pair
var server_keys = crypto.keypair();
console.log("Server public key:", server_keys.public);
console.log("Server private key:", server_keys.private);
// Store connected clients
var clients = {};
$_.portal(e => {
// Verify the handshake message format
if (!e.seif || !e.handshake || !e.payload) {
send(e, {error:"Invalid Seif handshake format"});
return;
}
if (e.seif !== 1) {
send(e, {error:"Unsupported Seif protocol version:", e.seif});
return;
}
try {
// Decrypt the handshake key with server's private key
var handshake_key_encrypted = e.handshake;
var handshake_key_hex = crypto.decrypt_pk(server_keys.private, handshake_key_encrypted);
// Convert ArrayBuffer to hex string
var handshake_key_bytes = new Uint8Array(handshake_key_hex);
var handshake_key = '';
for (var i = 0; i < handshake_key_bytes.length; i++) {
var hex = handshake_key_bytes[i].toString(16);
handshake_key += (hex.length === 1 ? '0' : '') + hex;
}
console.log("Decrypted handshake key:", handshake_key);
// Decrypt the payload (client's public key) with handshake key
var client_public_encrypted = e.payload;
var client_public_buffer = crypto.decrypt(handshake_key, client_public_encrypted);
// Convert decrypted buffer to string
var client_public_bytes = new Uint8Array(client_public_buffer);
var client_public = '';
for (var i = 0; i < client_public_bytes.length; i++) {
client_public += String.fromCharCode(client_public_bytes[i]);
}
console.log("Client's public key:", client_public);
// Generate session key
var session_key = crypto.keypair();
console.log("Generated session key:", session_key.public);
// Create response encrypted with handshake key
var response = {
session: crypto.encrypt_pk(client_public, session_key.public)
};
var response_encrypted = crypto.encrypt(handshake_key, json.encode(response));
// Send encrypted response
send(e, response_encrypted);
console.log("Handshake complete with client:", client_public);
} catch (err) {
send(e, {error:err})
}
}, 5678);
// Handle messages from connected clients
$_.receiver(e => {
if (e.type === 'encrypted_message') {
console.log("Received encrypted message");
// In a real implementation, decrypt with session key and process
}
});
console.log("Seif server listening on port 5678");