使用PHP进行最简单的双向加密

use*_*970 211 php security encryption cryptography encryption-symmetric

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

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

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

Sco*_*ski 216

重要提示:除非您有非常特殊的用例,否则请不要加密密码,而是使用密码哈希算法.当有人说他们在服务器端应用程序中加密他们的密码时,他们要么不知情,要么他们描述危险的系统设计.安全存储密码与加密完全不同.

得到通知.设计安全系统.

PHP中的便携式数据加密

如果您使用的是PHP 5.4或更高版本并且不想自己编写加密模块,我建议使用提供经过身份验证的加密的现有库.我链接的库仅依赖于PHP提供的内容,并且由少数安全研究人员定期审查.(包括我自己.)

如果您的可移植性目标不能阻止需要PECL扩展,那么强烈建议使用libsodium,不是使用PHP编写的任何内容.

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

如果您想尝试加密工程,请继续阅读.


首先,您应该花时间了解未经身份验证的加密加密死命原则的危险.

  • 加密数据仍然可能被恶意用户篡改.
  • 验证加密数据可防止篡改.
  • 验证未加密的数据不会阻止篡改.

加密和解密

PHP中的加密实际上很简单(我们将使用openssl_encrypt(),openssl_decrypt()一旦您就如何加密信息做出了一些决定.请openssl_get_cipher_methods()参阅系统支持的方法列表.最佳选择是点击率模式下的AES:

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

目前没有理由相信AES密钥大小是一个需要担心的重要问题(由于256位模式下的密钥调度错误,更大可能不是更好).

注意:我们没有使用,mcrypt因为它是放弃软件,并且有未修补的错误可能会影响安全性.由于这些原因,我鼓励其他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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例

$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);
Run Code Online (Sandbox Code Playgroud)

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


上面简单的加密库仍然不安全使用.在解密之前,我们需要对密文进行身份验证并验证它们.

注意:默认情况下,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);
Run Code Online (Sandbox Code Playgroud)

演示: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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例

$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);
Run Code Online (Sandbox Code Playgroud)

演示:原始二进制,base64编码


如果有人希望SaferCrypto在生产环境中使用此库,或者您自己实现相同的概念,我强烈建议在向您的常驻密码学家提出第二意见之前与您联系.他们能够告诉你我甚至不知道的错误.

使用信誉良好的加密库会更好.

  • 所以,我只是想让UnsafeCrypto先行.加密很好,但每次运行解密时,我都会得到"假"作为响应.我使用相同的密钥进行解密,并在编码和传真上传递true.有,我假设是示例中的一个类型,我想知道这是否是我的问题来自哪里.你能解释一下$ mac变量的来源,它应该只是$ iv吗? (3认同)
  • [不再支持5.2和5.3](https://secure.php.net/eol.php).您应该考虑更新到[支持的PHP版本](https://secure.php.net/supported-versions.php),例如5.6. (2认同)

472*_*084 186

编辑:

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

正如斯科特所说,Mcrypt并不是一个好主意,因为它自2007年以来一直没有更新.

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

  • @EugenRieck是的,这就是重点.Mcrypt没有收到补丁.一旦发现任何漏洞(无论大小),OpenSSL都会收到补丁. (6认同)
  • 对于如此高评价的答案,最好还是提供最简单的例子.不管怎么说,还是要谢谢你. (5认同)

Eug*_*eck 21

使用mcrypt_encrypt()mcrypt_decrypt()使用相应的参数.非常简单直接,您使用经过实战检验的加密包.

编辑

在此答案之后的5年零4个月,mcrypt扩展程序现在处于弃用状态并最终从PHP中删除.

  • 战斗测试并且未更新超过8年? (33认同)
  • mcrypt在支持方面不仅可怕.它也没有实现PKCS#7兼容填充,经过身份验证的加密等最佳实践.它不支持SHA-3或任何其他新算法,因为没有人维护它,抢夺你的升级路径.此外,它曾经接受像部分键,执行零填充等等.有一个很好的理由,它正在逐步从PHP中删除. (3认同)
  • 你被邀请参加葬礼:https://wiki.php.net/rfc/mcrypt-viking-funeral (3认同)
  • 好吧,mcrypt在PHP7中并且没有被弃用-对我来说足够了。并非所有代码都具有OpenSSL的可怕质量,并且需要每隔几天修补一次。 (2认同)
  • 在PHP 7.1中,所有mcrypt_*函数都会引发E_DEPRECATED通知.在PHP 7.1 + 1(无论是7.2还是8.0)中,mcrypt扩展将移出核心并进入PECL,如果他们可以从PECL安装PHP扩展,那么*真正想要安装它的人仍然可以这样做. (2认同)

Hem*_*ela 6

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."
}
Run Code Online (Sandbox Code Playgroud)

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

  • “crypto_sign” API *不*加密消息 - 这将需要“crypto_aead_*_encrypt”函数之一。 (2认同)

har*_*are 6

使用 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;
?>
Run Code Online (Sandbox Code Playgroud)

以下是对所用变量的解释:

message_to_encrypt :您要加密的数据 secret_key :它是您加密的“密码”。确保不要选择太简单的方法,并注意不要与其他人共享您的密钥方法:加密方法。这里我们选择了AES128。iv_length 和 iv :使用 bytes 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;
?>
Run Code Online (Sandbox Code Playgroud)

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

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