顯然目前對此沒有太多支援或文件。
根據此處和其他地方相同的 safeEncrypt 實作,我更新它以使其對我有效(我正在執行 libsodium 1.0.8)。
我將這些方法新增至一個工具類別。
<?php
$message = '我的極機密資訊';
$secret_key = Util::generateSecretKey();
$encrypted = Util::encrypt($message, $secret_key, 64);
$decrypted = Util::decrypt($encrypted, $secret_key, 64);
print $decrypted;
class Util
{
public static function generateSecretKey()
{
return sodium_crypto_secretbox_keygen();
}
public static function encrypt($message, $secret_key, $block_size = 1)
{
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$padded_message = sodium_pad($message, $block_size <= 512 ? $block_size : 512);
$cipher = base64_encode($nonce . sodium_crypto_secretbox($padded_message, $nonce, $secret_key));
sodium_memzero($message);
sodium_memzero($secret_key);
return $cipher;
}
public static function decrypt($encrypted, $secret_key, $block_size = 1)
{
$decoded = base64_decode($encrypted);
if ($decoded === false) {
throw new \Exception('編碼失敗');
}
if (!defined('CRYPTO_SECRETBOX_MACBYTES')) define('CRYPTO_SECRETBOX_MACBYTES', 16);
if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + CRYPTO_SECRETBOX_MACBYTES)) {
throw new \Exception('訊息被截斷');
}
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$decrypted_padded_message = sodium_crypto_secretbox_open($ciphertext, $nonce, $secret_key);
$message = sodium_unpad($decrypted_padded_message, $block_size <= 512 ? $block_size : 512);
if ($message === false) {
throw new \Exception('訊息在傳輸過程中遭到竄改');
}
sodium_memzero($ciphertext);
sodium_memzero($secret_key);
return $message;
}
}
?>