- random_bytes: documentation ( source)
<?php
// Some example variables:
$alice_ecdh_secret =
"\x69\xf2\x08\x41\x2d\x8d\xd5\xdb\x9d\x0c\x6d\x18\x51\x2e\x86\xf0" .
"\xec\x75\x66\x5a\xb8\x41\x37\x2d\x57\xb0\x42\xb2\x7e\xf8\x9d\x8c";
$bob_ecdh_public =
"\xe8\x98\x0c\x86\xe0\x32\xf1\xeb\x29\x75\x05\x2e\x8d\x65\xbd\xdd" .
"\x15\xc3\xb5\x96\x41\x17\x4e\xc9\x67\x8a\x53\x78\x9d\x92\xc7\x54";
$message_keypair = sodium_crypto_box_keypair_from_secretkey_and_publickey(
$alice_ecdh_secret,
$bob_ecdh_public
);
$plaintext = "This is a secret message for your eyes only.";
$nonce = random_bytes(24);
// And now for the actual public-key encryption step:
$ciphertext = sodium_crypto_box($plaintext, $nonce, $message_keypair);
//To decrypt a message:
$received = sodium_crypto_box_open(
$ciphertext,
$nonce,
$message_keypair
);
echo $received;