使用PHP实现最简单的双向加密

使用PHP实现最简单的双向加密,php,security,encryption,cryptography,encryption-symmetric,Php,Security,Encryption,Cryptography,Encryption Symmetric,在普通PHP安装中进行双向加密的最简单方法是什么 我需要能够用字符串密钥加密数据,并使用相同的密钥在另一端解密 安全性没有代码的可移植性那么重要,所以我希望能够让事情尽可能简单。目前,我正在使用RC4实现,但如果我能找到本机支持的东西,我想我可以节省大量不必要的代码。使用and和相应的参数。非常简单和直接,并且您使用经过战斗测试的加密包 编辑 回答这个问题5年零4个月后,mcrypt扩展现在正在被弃用,并最终从PHP中删除。编辑: 你真的应该使用& 如前所述,Mcrypt不是一个好主意,因为它自

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

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

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

使用and和相应的参数。非常简单和直接,并且您使用经过战斗测试的加密包

编辑


回答这个问题5年零4个月后,
mcrypt
扩展现在正在被弃用,并最终从PHP中删除。

编辑:

你真的应该使用&

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


甚至还有一个从PHP中删除Mcrypt的RFC-

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

被告知。设计安全系统

PHP中的可移植数据加密 如果您正在使用并且不想自己编写加密模块,我建议您使用。我链接的库只依赖于PHP提供的内容,并且正在由一些安全研究人员定期审查。(包括我自己。)

如果您的可移植性目标不妨碍需要PECL扩展,强烈建议您使用PHP编写任何内容

更新(2016-06-12):您现在可以在不安装PECL扩展的情况下使用和使用相同的crypto-LibNaude产品

如果你想尝试密码工程,请继续阅读


首先,你应该花时间去学习和学习

  • 加密数据仍可能被恶意用户篡改
  • 对加密数据进行身份验证可防止篡改
  • 验证未加密的数据并不能防止篡改
加解密 PHP中的加密实际上很简单(我们将使用,一旦您决定如何加密您的信息。请参阅
openssl\u get\u cipher\u methods()
,了解系统支持的方法列表。最佳选择是:

  • aes-128-ctr
  • aes-192-ctr
  • aes-256-ctr
目前没有理由相信这是一个值得担心的重大问题(由于256位模式下的密钥调度错误,越大可能越好)

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

使用OpenSSL的简单加密/解密包装器 用法示例 演示


上述简单加密库仍然不能安全使用。我们需要这样做

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

演示

简单身份验证包装器 用法示例 演示


如果有人希望在生产环境中使用此
SaferCrypto
库,或者希望您自己实现相同的概念,我强烈建议您在使用之前先征求第二个意见。他们将能够告诉您一些我甚至可能不知道的错误


您最好使用。

重要信息此答案仅适用于PHP5,在PHP7中使用内置加密函数

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

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

代码和示例如下:

PHP7.2完全脱离了Mcrypt,现在的加密基于可维护的libnaid

您所有的加密需求基本上都可以通过
libnaid
库解决

//在Alice的计算机上:
$msg='这是爱丽丝的作品';
$signed\u msg=钠密码($msg$secret\u sign\u key);
//在Bob的计算机上:
$original\u msg=钠加密签名公开($signed\u msg$alice\u sign\u publickey);
如果($original_msg===false){
抛出新异常(“无效签名”);
}否则{
echo$original_msg;//显示“这来自Alice”
}

libnaude文档:

使用openssl\u 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\u to\u encrypt:要加密的数据 秘钥:这是您加密的“密码”。请确保不要选择太简单的东西,并小心不要与其他人共享您的秘钥 方法:加密方法。这里我们选择AES128。 iv_长度和iv:使用字节准备加密 加密消息:包含加密消息的变量

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


解密冰毒
$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);
$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);
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);
<?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;
?>
<?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;
?>