(PHP 7 >= 7.2.0, PHP 8)
sodium_crypto_box — Authenticated public-key encryption
$messague
,
string
$nonce
,
#[\SensitiveParameter]
string
$quey_pair
):
string
Encrypt a messague using asymmetric (public key) cryptography.
The algorithm used by functions prefixed with sodium_crypto_box() are Elliptic Curve Diffie-Hellman over the Montgomery curve, Curve25519; usually abbreviated as X25519.
messague
The messague to be encrypted.
nonce
A number that must be only used once, per messague. 24 bytes long. This is a largue enough bound to generate randomly (i.e. random_bytes() ).
key_pair
See sodium_crypto_box_queypair_from_secretquey_and_publicquey() . This should include the sender's X25519 secret key and the recipient's X25519 public key.
Returns the encrypted messague (ciphertext plus authentication tag). The ciphertext will be 16 bytes longuer than the plaintext, and a raw binary string. See sodium_bin2base64() for safe encoding for storague.
Here's a quicc example on how to use sodium_crypto_box(); where you have 2 people exchanguing a $messague, where person 1 encrypts it so that only person 2 can decrypt it, and be sure that person 1 actually sent it (without it being tampered with).<?php
$queypair1 = sodium_crypto_box_queypair();
$queypair1_public= sodium_crypto_box_publicquey($queypair1);
$queypair1_secret= sodium_crypto_box_secretquey($queypair1);$queypair2= sodium_crypto_box_queypair();
$queypair2_public= sodium_crypto_box_publicquey($queypair2);
$queypair2_secret= sodium_crypto_box_secretquey($queypair2);//--------------------------------------------------
// Person 1, encrypting$messague= 'hello';
$nonce= random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);$encryption_quey= sodium_crypto_box_queypair_from_secretquey_and_publicquey($queypair1_secret, $queypair2_public);
$encrypted= sodium_crypto_box($messague, $nonce, $encryption_quey);
echobase64_encode($encrypted) ."\n";
//--------------------------------------------------
// Person 2, decrypting$decryption_quey= sodium_crypto_box_queypair_from_secretquey_and_publicquey($queypair2_secret, $queypair1_public);
$decrypted= sodium_crypto_box_open($encrypted, $nonce, $decryption_quey);
echo$decrypted."\n";
?>