widgets Libsodium Php 7.2 Examples


Quick info:

Libsodium is modern cryptography technology.

Requirements:

  • Php version should greater than 7.2

Lets start with Libsodium examples:

Store and Veritfy Passwords With Libsodium

sodium_crypto_pwhash_str function:

  • This function get a formatted password hash (for storage)
  • Parameters: string $passwd, int $opslimit, int $memlimit
  • Return: String

sodium_crypto_pwhash_str_verify:

  • Verify a password against a hash
  • Parameters: string $hash, string $passwd
  • Return: Bool

Example:

$password = 'iHaveGoodPass';
$storePassword = sodium_crypto_pwhash_str($password, SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE);

sodium_crypto_pwhash_str_verify($storePassword, $password);

// Let's check stored hash
print_r($storePassword); // $argon2id$v=19$m=65536,t=2,p=1$J0+Q1YfNg0Hqzt8MSSMsXA$vHq/WYrz2tKJS5XIBiZF7xFcr+N6V3J/ncFJiNPi4uY

if(sodium_crypto_pwhash_str_verify($storePassword, $password)) {
echo "Password is correct";
// Continue code like... Auth::login($user, true);
} else {
echo "Password incorrect!";
// Continue code like... redirect()->guest(route('login'));
}

Encrypt and Decrypt String on the Same Machine

sodium_crypto_secretbox & sodium_crypto_secretbox_open functions can be use for encrypt and decrypt on same machine.

sodium_crypto_secretbox:

  • Authenticated secret-key encryption (encrypt)
  • Xsals20 + Poly1305
  • Params: String $plaintext, string $nonce, string $key
  • Return: String

sodium_crypto_secretbox_open:

  • Authenticated secret-key encryption (decrypt)
  • Xsals20 + Poly1305
  • Params:  string $ciphertext, string $nonce, string $key
  • Return: string

Example:

$key = random_bytes(32);
$message = 'I love you';

// Lets start encrypt
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encrypted_text = sodium_crypto_secretbox($message, $nonce, $key);

// Lets decrypt
$decrypted_text = sodium_crypto_secretbox_open($encrypted_text, $nonce, $key);

print_r($decrypted_text);

Encrypt and Decrypt String

sodium_crypto_box_seal & sodium_crypto_box_seal_open functions can be use for encrypt and decrypt.

sodium_crypto_box_keypair: Generate an X25519 keypair for use with the sodium_crypto_box API

sodium_crypto_box_publickey:  Get an X25519 public key from an X25519 keypair.

sodium_crypto_box_seal:

  • Anonymous public-key encryption (encrypt)
  • X25519 + Xsalsa20 + Poly1305 + BLAKE2b
  • Params: String $message, string $publickey
  • Return: string
sodium_crypto_box_seal_open:
Anonymous public-key encryption (decrypt)
X25519 + Xsalsa20 + Poly1305 + BLAKE2b

Params: String $encrypted, String $keypair
Return: string

Example:

$keypair = sodium_crypto_box_keypair();
$public_key = sodium_crypto_box_publickey($keypair);

$message=  'Contain good text';
$encrypted_text = sodium_crypto_box_seal($message, $public_key);
$decrypted_text = sodium_crypto_box_seal_open($encrypted_text, $keypair);

echo $decrypted_text;