Libsodiumとは?
PHP7.2に追加されたモダーンな暗号処理ライブラリです。実際使う時のサンプルコードをまとめてみました。
Password Hash
$password = 'secret password';
$hash = sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);
echo $hash . PHP_EOL;
if (sodium_crypto_pwhash_str_verify($hash, $password)) {
sodium_memzero($password);
echo 'valid password' . PHP_EOL;
if (sodium_crypto_pwhash_str_needs_rehash($hash,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE)) {
echo 'save new password hash' . PHP_EOL;
}
} else {
sodium_memzero($password);
echo 'invalid password!' . PHP_EOL;
}
Generic Hash
$hash = sodium_bin2hex(sodium_crypto_generichash('message'));
echo $hash . PHP_EOL;
$key = random_bytes(SODIUM_CRYPTO_SHORTHASH_KEYBYTES);
$hash = sodium_bin2hex(sodium_crypto_shorthash('message', $key));
echo $hash . PHP_EOL;
Secret Key
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'secret message';
$cipher_text = sodium_bin2hex(sodium_crypto_secretbox($message, $nonce, $key));
sodium_memzero($message);
echo $cipher_text . PHP_EOL;
$plain_text = sodium_crypto_secretbox_open(sodium_hex2bin($cipher_text), $nonce, $key);
echo $plain_text . PHP_EOL;
Public Key
$key_pair = sodium_crypto_box_keypair();
$public_key = sodium_crypto_box_publickey($key_pair);
$message = 'secret message';
$cipher_text = sodium_bin2hex(sodium_crypto_box_seal($message, $public_key));
sodium_memzero($message);
echo $cipher_text . PHP_EOL;
$plain_text = sodium_crypto_box_seal_open(sodium_hex2bin($cipher_text), $key_pair);
echo $plain_text . PHP_EOL;