【问题标题】:Simplest two-way encryption using PHP使用 PHP 的最简单的双向加密
【发布时间】:2012-03-04 22:46:04
【问题描述】:

在常见的 PHP 安装中进行双向加密的最简单方法是什么?

我需要能够使用字符串密钥加密数据,并在另一端使用相同的密钥解密。

安全性不像代码的可移植性那么重要,所以我希望能够使事情尽可能简单。目前,我正在使用 RC4 实现,但如果我能找到本机支持的东西,我想我可以节省很多不必要的代码。

【问题讨论】:

  • 对于通用加密,请使用 defuse/php-encryption/ 而不是自己滚动。
  • 手远离github.com/defuse/php-encryption - 它比 mcrypt 慢几个数量级。
  • @Scott 沿着“这可能不会成为瓶颈”的思路思考是给我们带来了很多糟糕的软件。
  • 如果您真的要加密/解密大量数据,以至于花费的毫秒数使您的应用程序陷入困境,那么硬着头皮切换到 libsodium。 Sodium::crypto_secretbox()Sodium::crypto_secretbox_open() 既安全又高效。

标签: php security encryption cryptography encryption-symmetric


【解决方案1】:

使用 openssl_encrypt() 加密 openssl_encrypt 函数提供了一种安全且简单的方法来加密您的数据。

在下面的脚本中,我们使用 AES128 加密方法,但您可以根据要加密的内容考虑其他类型的加密方法。

<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);

$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

echo $encrypted_message;
?>

这里是使用的变量的解释:

message_to_encrypt :要加密的数据 secret_key :这是您的加密“密码”。一定不要选择太容易的东西,注意不要与其他人分享你的密钥 方法:加密的方法。这里我们选择了AES128。 iv_length 和 iv :使用字节准备加密 encrypted_message : 包含您的加密消息的变量

使用 openssl_decrypt() 解密 现在您加密了您的数据,您可能需要对其进行解密,以便重新使用您首先包含在变量中的消息。为此,我们将使用函数 openssl_decrypt()。

<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

$decrypted_message = openssl_decrypt($encrypted_message, $method, $secret_key, 0, $iv);

echo $decrypted_message;
?>

openssl_decrypt() 提出的解密方法与 openssl_encrypt() 相近。

唯一的区别是,您需要添加已加密的消息作为 openssl_decrypt() 的第一个参数,而不是添加 $message_to_encrypt。

注意:需要保存密钥和iv才能解密。

【讨论】:

  • 除非我没看错,否则我觉得值得一提的是秘钥和iv需要保存,以后要解密。直到我意识到阅读此链接php.net/manual/en/function.openssl-encrypt.php#example-903
  • 同意 gstlouis,我不得不撤回我的赞成票,因为发布的代码没有考虑到这一点。然而,它是 90% 的基础,不会将课堂废话混入其中。
【解决方案2】:

重要提示此答案仅对 PHP 5 有效,在 PHP 7 中使用内置加密函数。

这是一个简单但足够安全的实现:

  • CBC 模式下的 AES-256 加密
  • PBKDF2 使用明文密码创建加密密钥
  • HMAC 对加密消息进行身份验证。

代码和示例在这里:https://stackoverflow.com/a/19445173/1387163

【讨论】:

  • 我不是密码学专家,但直接从密码中派生密钥似乎是个糟糕的主意。彩虹桌 + 弱密码,您的安全感一去不复返了。您的链接也指向 mcrypt 函数,自 PHP 7.1 起已弃用
  • @Alph.Dev 你是对的,上面的答案只对 PHP 5 有效
【解决方案3】:

PHP 7.2 完全脱离了Mcrypt,加密现在基于可维护的Libsodium 库。

你所有的加密需求基本上都可以通过Libsodium库解决。

// On Alice's computer:
$msg = 'This comes from Alice.';
$signed_msg = sodium_crypto_sign($msg, $secret_sign_key);


// On Bob's computer:
$original_msg = sodium_crypto_sign_open($signed_msg, $alice_sign_publickey);
if ($original_msg === false) {
    throw new Exception('Invalid signature');
} else {
    echo $original_msg; // Displays "This comes from Alice."
}

Libsodium 文档:https://github.com/paragonie/pecl-libsodium-doc

【讨论】:

  • crypto_sign API 确实加密消息 - 这将需要 crypto_aead_*_encrypt 函数之一。
【解决方案4】:

重要提示:除非您有一个非常特定的用例do not encrypt passwords,否则请改用密码哈希算法。当有人说他们在服务器端应用程序中加密他们的密码时,他们要么不知情,要么在描述危险的系统设计。 Safely storing passwords 是与加密完全不同的问题。

了解情况。设计安全系统。

PHP 中的可移植数据加密

如果您使用PHP 5.4 or newer 并且不想自己编写加密模块,我建议您使用an existing library that provides authenticated encryption。我链接的库仅依赖于 PHP 提供的内容,并且正在接受少数安全研究人员的定期审查。 (包括我自己。)

如果您的可移植性目标不妨碍需要 PECL 扩展,则强烈推荐使用 libsodium,而不是您或我可以用 PHP 编写的任何内容。

更新 (2016-06-12):您现在可以使用 sodium_compat 并使用相同的加密 libsodium 提供,而无需安装 PECL 扩展。

如果您想尝试密码学工程,请继续阅读。


首先,你应该花时间学习the dangers of unauthenticated encryptionthe Cryptographic Doom Principle

  • 加密数据仍可能被恶意用户篡改。
  • 对加密数据进行身份验证可防止篡改。
  • 对未加密数据进行身份验证并不能防止篡改。

加解密

PHP 中的加密实际上很简单(一旦您决定如何加密您的信息,我们将使用openssl_encrypt()openssl_decrypt()。请咨询openssl_get_cipher_methods() 以获取系统支持的方法列表. 最好的选择是AES in CTR mode

  • aes-128-ctr
  • aes-192-ctr
  • aes-256-ctr

目前没有理由相信AES key size 是一个需要担心的重大问题(由于 256 位模式下的键调度错误,可能不是越大越好)。

注意:我们没有使用mcrypt,因为它是abandonware,并且有可能影响安全的unpatched bugs。由于这些原因,我鼓励其他 PHP 开发人员也避免使用它。

使用 OpenSSL 的简单加密/解密包装器

class UnsafeCrypto
{
    const METHOD = 'aes-256-ctr';

    /**
     * Encrypts (but does not authenticate) a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded 
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = openssl_random_pseudo_bytes($nonceSize);

        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        // Now let's pack the IV and the ciphertext together
        // Naively, we can just concatenate
        if ($encode) {
            return base64_encode($nonce.$ciphertext);
        }
        return $nonce.$ciphertext;
    }

    /**
     * Decrypts (but does not verify) a message
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }

        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = mb_substr($message, 0, $nonceSize, '8bit');
        $ciphertext = mb_substr($message, $nonceSize, null, '8bit');

        $plaintext = openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        return $plaintext;
    }
}

使用示例

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = UnsafeCrypto::encrypt($message, $key);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key);

var_dump($encrypted, $decrypted);

演示https://3v4l.org/jl7qR


上述简单的加密库仍然不能安全使用。我们需要authenticate ciphertexts and verify them before we decrypt

注意:默认情况下,UnsafeCrypto::encrypt() 将返回原始二进制字符串。如果您需要以二进制安全格式(base64 编码)存储它,可以这样调用它:

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = UnsafeCrypto::encrypt($message, $key, true);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key, true);

var_dump($encrypted, $decrypted);

演示http://3v4l.org/f5K93

简单的身份验证包装器

class SaferCrypto extends UnsafeCrypto
{
    const HASH_ALGO = 'sha256';

    /**
     * Encrypts then MACs a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded string
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);

        // Pass to UnsafeCrypto::encrypt
        $ciphertext = parent::encrypt($message, $encKey);

        // Calculate a MAC of the IV and ciphertext
        $mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);

        if ($encode) {
            return base64_encode($mac.$ciphertext);
        }
        // Prepend MAC to the ciphertext and return to caller
        return $mac.$ciphertext;
    }

    /**
     * Decrypts a message (after verifying integrity)
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string (raw binary)
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }

        // Hash Size -- in case HASH_ALGO is changed
        $hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
        $mac = mb_substr($message, 0, $hs, '8bit');

        $ciphertext = mb_substr($message, $hs, null, '8bit');

        $calculated = hash_hmac(
            self::HASH_ALGO,
            $ciphertext,
            $authKey,
            true
        );

        if (!self::hashEquals($mac, $calculated)) {
            throw new Exception('Encryption failure');
        }

        // Pass to UnsafeCrypto::decrypt
        $plaintext = parent::decrypt($ciphertext, $encKey);

        return $plaintext;
    }

    /**
     * Splits a key into two separate keys; one for encryption
     * and the other for authenticaiton
     * 
     * @param string $masterKey (raw binary)
     * @return array (two raw binary strings)
     */
    protected static function splitKeys($masterKey)
    {
        // You really want to implement HKDF here instead!
        return [
            hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
            hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
        ];
    }

    /**
     * Compare two strings without leaking timing information
     * 
     * @param string $a
     * @param string $b
     * @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
     * @return boolean
     */
    protected static function hashEquals($a, $b)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($a, $b);
        }
        $nonce = openssl_random_pseudo_bytes(32);
        return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
    }
}

使用示例

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = SaferCrypto::encrypt($message, $key);
$decrypted = SaferCrypto::decrypt($encrypted, $key);

var_dump($encrypted, $decrypted);

演示raw binarybase64-encoded


如果有人希望在生产环境中使用这个SaferCrypto 库,或者您自己实现相同的概念,我强烈建议您在这样做之前联系your resident cryptographers 以获得第二意见。他们会告诉你我可能没有意识到的错误。

使用a reputable cryptography library 会更好。

【讨论】:

  • 所以,我只是想让 UnsafeCrypto 首先工作。加密进行得很好,但是每次我运行解密时,我都会得到“假”作为响应。我使用相同的密钥进行解密,并在编码和解码上传递 true。有,我假设在示例中是 typeo,我想知道这是否是我的问题的来源。你能解释一下 $mac 变量的来源吗?它应该只是 $iv 吗?
  • @EugenRieck OpenSSL 密码实现可能是唯一不糟糕的部分,它是在普通 PHP 中利用 AES-NI 的唯一方法。如果您安装在 OpenBSD 上,PHP 将针对 LibreSSL 进行编译,而 PHP 代码不会注意到差异。 Libsodium > OpenSSL 任何一天。另外,don't use libmcrypt您会建议 PHP 开发人员使用什么来代替 OpenSSL?
  • Neither 5.2 nor 5.3 are supported anymore。相反,您应该考虑更新到 supported version of PHP,例如 5.6。
  • 我只是为了演示您需要二进制字符串,而不是人类可读的字符串,作为您的密钥
【解决方案5】:

mcrypt_encrypt()mcrypt_decrypt() 与相应的参数一起使用。非常简单直接,而且您使用经过实战考验的加密包。

编辑

在得到这个答案 5 年零 4 个月后,mcrypt 扩展现在正处于弃用过程中,并最终从 PHP 中删除。

【讨论】:

  • 经过实战测试,超过 8 年未更新?
  • 嗯,mcrypt 在 PHP7 中并没有被弃用——这对我来说已经足够好了。并非所有代码都具有 OpenSSL 糟糕的质量,并且每隔几天就需要修补一次。
  • mcrypt 不仅在支持方面很糟糕。它也没有实现最佳实践,如符合 PKCS#7 的填充、经过身份验证的加密。它不支持 SHA-3 或任何其他新算法,因为没有人维护它,从而剥夺了您的升级路径。此外,它曾经接受部分键、执行零填充等操作。它正在逐步从 PHP 中删除是有充分理由的。
  • 在 PHP 7.1 中,所有 mcrypt_* 函数都会引发 E_DEPRECATED 通知。在 PHP 7.1+1(无论是 7.2 还是 8.0)中,mcrypt 扩展将从核心移出到 PECL 中,真的想要安装它的人如果可以安装 PHP,仍然可以这样做PECL 的扩展。
【解决方案6】:

已编辑:

你真的应该使用openssl_encrypt() & openssl_decrypt()

正如Scott 所说,Mcrypt 不是一个好主意,因为它自 2007 年以来就没有更新过。

甚至还有一个 RFC 可以从 PHP 中删除 Mcrypt - https://wiki.php.net/rfc/mcrypt-viking-funeral

【讨论】:

  • @EugenRieck 是的,这就是重点。 Mcrypt 不接收补丁。一旦发现任何漏洞,无论大小,OpenSSL 都会立即收到补丁。
  • 这样高票数的答案会更好,在答案中也提供最简单的例子。无论如何,谢谢。
  • 伙计们,仅供参考 => MCRYPT 已弃用。封顶,所以每个人都应该知道不要使用它,因为它给我们带来了无数问题。如果我没记错的话,它自 PHP 7.1 起已弃用。
  • 自 PHP 7 起,mcrypt 函数已从 php 代码库中移除。因此,当使用最新版本的 php(应该是标准的)时,您将无法再使用此已弃用的功能。
  • 您还应该提到 Mcrypt 自 PHP 7.1.0 起已贬值,并从 PHP 7.2.0 起删除。
猜你喜欢
  • 2013-05-04
  • 2011-04-15
  • 1970-01-01
  • 2011-04-23
  • 2023-03-08
  • 2012-03-15
  • 2011-04-06
  • 2014-06-28
  • 2017-12-20
相关资源
最近更新 更多