如何使用 Libsodium-PHP 加密/解密 AES

How to encrypt / decrypt AES with Libsodium-PHP


我需要 encrypt/decrypt 数据和 PHP。我对此完全陌生,但是我读过 Libsodium-PHP 是 AES 加密的最佳工具。与我研究过的其他 PHP 加密库非常相似 Libsoduim-PHP 似乎几乎没有提供有关如何使用该库的文档(我能够找到)。任何有 PHP 加密经验的人都可以为我指出一个好的学习资源的方向,或者使用 Libsoduim-PHP 编写几行示例代码吗?
非常感谢帮助,
图集

Much like the other PHP encryption libraries I have researched Libsoduim-PHP seemed to offer almost no documentation of how to use the library (that I was able to find).

来自 the libsodium-php Github page you will find a direct link to a free online book,涵盖了开始使用 libsodium 所需了解的所有内容。

最后一章包含libsodium recipes,但每章都有详细的使用信息

如果您特别需要 AES,read this

如果您没有悬而未决的 "AES-or-bust" 要求,如果未能专门使用 AES 意味着您的部门将被裁员并且您的开发人员将面临行刑队,您应该考虑只使用 crypto_secretbox which uses Xsalsa20 for encryption and attaches a Poly1305 authentication tag. (This is authenticated encryption,你几乎总是想使用它。)

如果您想要简单模式,也可以查看 Halite

PHP 版本 >= 7.2

如果您使用的是 PHP >= 7.2,请改用内置钠核心扩展。

实施示例

<?php 
//Simple Usage

/**
* Encrypt a message
* 
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
*/
function safeEncrypt($message, $key)
{
    $nonce = random_bytes(
        SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
    );

    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
* Decrypt a message
* 
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
*/
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    if ($decoded === false) {
        throw new Exception('Scream bloody murder, the encoding failed');
    }
    if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
        throw new Exception('Scream bloody murder, the message was truncated');
    }
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if ($plain === false) {
         throw new Exception('the message was tampered with in transit');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}
//Encrypt & Decrypt your message
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

$enc = safeEncrypt('Encrypt This String...', $key); //generates random  encrypted string (Base64 related)
echo $enc;
echo '<br>';
$dec = safeDecrypt($enc, $key); //decrypts encoded string generated via safeEncrypt function 
echo $dec;