3

Trying to follow the examples here, but it gives me

Fatal error: Uncaught Error: Call to undefined function sodium_randombytes_buf()

On top of that, the key pairs seems to be generating weird strings like:

kÿòjƒFDú{î—4]F◊î¸˜ßˆu…®_•A∞+.

Is that normal?

Here's my code

<?php

// send
$message = 'Hi, this is Alice';
$alice_to_bob_kp = sodium_crypto_box_keypair_from_secretkey_and_publickey(
    file_get_contents('./keys/sec-user-1_box_key.txt'),
    file_get_contents('./keys/pub-user-2_box_key.txt')
);
$nonce = sodium_randombytes_buf(SODIUM_CRYPTO_BOX_NONCEBYTES);
$ciphertext = sodium_crypto_box(
    $message,
    $nonce,
    $alice_to_bob_kp
);




// receive
$bob_to_alice_kp = sodium_crypto_box_keypair_from_secretkey_and_publickey(
    // $bob_box_secretkey,
    // $alice_box_publickey
    file_get_contents('./keys/sec-user-2_box_key.txt'),
    file_get_contents('./keys/pub-user-1_box_key.txt')
);
$nonce = sodium_randombytes_buf(SODIUM_CRYPTO_BOX_NONCEBYTES);
$plaintext = sodium_crypto_box_open(
    $ciphertext,
    $nonce,
    $bob_to_alice_kp
);
if ($plaintext === false) {
    die("Malformed message or invalid MAC");
}
die($plaintext);
AFwcxx
  • 467
  • 1
  • 4
  • 15

1 Answers1

1

There is no such function as sodium_randombytes_buf() the code in the example uses \Sodium\randombytes_buf().

Edit:

From the bug history: "The sodium_randombytes_* symbols have been removed a while back, as PHP now provide similar functions without this extension"

Bug #74896 sodium's .h defines some functions without .c implementation

mracer164
  • 44
  • 8
  • They've used the prefix `sodium_*` instead of namespace in the newer version – AFwcxx Sep 14 '17 at 10:00
  • You'll need to provide your code to reviev then. – mracer164 Sep 14 '17 at 10:01
  • ok. updated the question content – AFwcxx Sep 14 '17 at 10:10
  • Take a look at my edited answer. – mracer164 Sep 14 '17 at 10:22
  • so instead can use `random_bytes()` php built in function? what about the weird `kÿòjƒFDú{î—4]F◊î¸˜ßˆu…®_•A∞+` string generated from the key pairs? – AFwcxx Sep 14 '17 at 10:38
  • Well... it is an encrypted keypair so by definition it should look like garbage. – mracer164 Sep 14 '17 at 10:47
  • Keys are binary data. They are not passwords.`crypto_box_keypair()` (as well as all the `keypair()` and `keygen()` functions) generate binary blobs that are not supposed to be printable. – Frank Denis Sep 14 '17 at 10:47
  • thanks for the clarification. it works when I use the same `$nonce` value for send and receive. Does that mean in all communication, the recipient must receive the decrypted message and the nonce in order to read the message? – AFwcxx Sep 14 '17 at 10:58
  • The nonce is indeed required along with the encrypted message. That nonce doesn’t have to be secret. – Frank Denis Sep 15 '17 at 22:30