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

时间:2012-02-13 14:23:19

标签: php security encryption cryptography encryption-symmetric

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

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

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

6 个答案:

答案 0 :(得分:198)

重要:除非您拥有非常特定用例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会更好。

答案 1 :(得分:178)

<强>编辑:

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

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

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

答案 2 :(得分:21)

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

编辑

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

答案 3 :(得分: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

答案 4 :(得分:2)

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

  • CBC模式下的AES-256加密
  • PBKDF2用明文密码创建加密密钥
  • HMAC验证加密邮件。

代码和示例如下:https://stackoverflow.com/a/19445173/1387163

答案 5 :(得分:2)

使用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:使用字节准备加密 encryption_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_lenght);
$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()。

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

这就是您要做的。

相关问题