I have a PHP code that uses the RSA encryption via libsodium (sodium_compat) library.
My script is as below:
//https://packagist.org/packages/paragonie/sodium_compat
//composer require paragonie/sodium_compat
require_once "/path/to/sodium_compat/autoload.php";
$privateKey = "HJu4JU0biDAewq0asdfgtDKXlQZZzmVy2chL0x74yhgr";
$publicKey = "874dmkuhiDAewq0asdfgtDKXlQZZzmVy2chL0x74yhgr";
$message = "HJu4JU0biDAewq0hgbvfcdsXlQZZzmVy2chL0x74yhgr";
$encryption_keypair = \Sodium\crypto_box_keypair_from_secretkey_and_publickey(base64_decode($privateKey), base64_decode($publicKey));
try {
$decodedMessage = \Sodium\crypto_box_seal_open(base64_decode($message), $encryption_keypair);
echo $decodedMessage;
} catch (Exception $e) {
echo $e->getMessage();
}
The script above shows how I decrypt an encrypted message from an already generated key pair.
I would like to do the same decryption with the same keys in Javascript side to avoid overloading the server, I found this library which is supposed to be the same libsodium
The doc shows how to decrypt as below:
let key = sodium.from_hex('724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed');
function encrypt_and_prepend_nonce(message) {
let nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
return nonce.concat(sodium.crypto_secretbox_easy(message, nonce, key));
}
function decrypt_after_extracting_nonce(nonce_and_ciphertext) {
if (nonce_and_ciphertext.length < sodium.crypto_secretbox_NONCEBYTES + sodium.crypto_secretbox_MACBYTES) {
throw "Short message";
}
let nonce = nonce_and_ciphertext.slice(0, sodium.crypto_secretbox_NONCEBYTES),
ciphertext = nonce_and_ciphertext.slice(sodium.crypto_secretbox_NONCEBYTES);
return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
}
I don't understand how I can make the decryption compatible in PHP and Js, they are refering to a nonce to create with the key in Js but in PHP the same library does not provide that. Any help please?
Thanks