When I try and decode the sodium algorithm $plaintext and $plaintext echo out empty. The encoding portion is working and inserting into my db.


encode using sodium

$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
$encrypted_result = sodium_crypto_secretbox($_POST[testpublish], $nonce, $key );
$encodedpublish = base64_encode( $nonce . $encrypted_result );

$nonce1 = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
$encrypted_result2 = sodium_crypto_secretbox($_POST[testAPI], $nonce1, $key );
$encodedapi = base64_encode( $nonce1 . $encrypted_result2 );

decode using sodium

$key1 = sodium_crypto_secretbox_keygen();
$decoded3 = base64_decode($row['testpublish']); //$encodedpublish is equal to $row[testpublish]
$nonce3 = mb_substr($decoded3, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$encrypted_result3 = mb_substr($decoded3, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plaintext = sodium_crypto_secretbox_open($encrypted_result3, $nonce3, $key1);
echo $plaintext;

$key2 = sodium_crypto_secretbox_keygen();
$decoded4 = base64_decode($row['testAPI']); //$encodedapi is equal to $row[testAPI]
$nonce4 = mb_substr($decoded4, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$encrypted_result4 = mb_substr($decoded4, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plaintext2 = sodium_crypto_secretbox_open($encrypted_result4, $nonce4, $key2);
echo $plaintext2;

I know nothing about that extension, but my first guess is that when decrypting you would need to use the same key that was used to encrypt it?

    Wasn't the sodium extension wrapped in to the PSL in 7-something and deprecated as an extension? As I recall it's a slightly different version between the extension and the native implementation but unless you're integrating with a legacy 5.x application you shouldn't see a difference.

    maxxd
    If you mean transferring the extension from PECL to the standard bundle, that happened in 7.2.

    I'd say NogDog has the right idea: $key1 and $key2 both need to be equal to $key or nothing would work.

      6 days later

      crawdidly sodium_crypto_secretbox_keygen

      Agree with the others that you are just generating new keys every time these functions run. According to the docs, sodium_crypto_secretbox_keygen generates a random key:

      Generate random key for sodium_crypto_secretbox

      Your code, as written, is basically just generating a new key/password every time you run that function. You would need to generate a key once, and store it somewhere so that you can use it to decode whatever data you previously encrypted with that key. NOTE that random byte sequences don't necessarily behave well as strings and you'd probably be wise to use base64 encoding or perhaps some bin2hex type of fn (e.g., sodium_bin2hex) on the key before trying to write it to a file or database record.

        Write a Reply...