PHP 中最简单的双向加密
重要提示:
在继续之前,强调本文至关重要旨在提供对未经身份验证的加密的简化理解。为了实现强大的数据保护,请始终考虑使用行业标准的经过身份验证的加密库或 bcrypt/argon2 进行密码存储。
本机加密方法
如果使用 PHP 5.4 或更高版本,请考虑使用 openssl_* 函数用于密码操作。它们通过本机支持提供强大的加密功能。
简单的加密和解密
OpenSSL 的 openssl_encrypt() 和 openssl_decrypt() 函数提供了一种可访问的方法来加密和解密数据。推荐的加密算法是 AES-CTR 的 128、192 或 256 位变体。
注意:由于 mcrypt 已弃用和潜在的安全风险,请避免使用 mcrypt。
简单加密/解密包装器
简化加密和解密解密过程中,您可以使用以下包装类:
class UnsafeCrypto { // Encryption method (CTR mode) const METHOD = 'aes-256-ctr'; /** * Encrypts data using the specified key. * * @param string $message Plaintext message * @param string $key Encryption key * @param bool $encode Whether to encode the result * * @return string Ciphertext */ public static function encrypt($message, $key, $encode = false) { // Generate random IV $ivSize = openssl_cipher_iv_length(self::METHOD); $iv = openssl_random_pseudo_bytes($ivSize); // Encrypt using OpenSSL $ciphertext = openssl_encrypt($message, self::METHOD, $key, OPENSSL_RAW_DATA, $iv); // Concatenate IV and ciphertext if ($encode) { return base64_encode($iv . $ciphertext); } return $iv . $ciphertext; } /** * Decrypts data using the specified key. * * @param string $message Ciphertext * @param string $key Encryption key * @param bool $encoded Whether the message is encoded * * @return string Decrypted message */ public static function decrypt($message, $key, $encoded = false) { if ($encoded) { $message = base64_decode($message, true); if ($message === false) { throw new Exception('Encryption failure'); } } // Extract IV and ciphertext $ivSize = openssl_cipher_iv_length(self::METHOD); $iv = substr($message, 0, $ivSize); $ciphertext = substr($message, $ivSize); // Decrypt using OpenSSL $plaintext = openssl_decrypt($ciphertext, self::METHOD, $key, OPENSSL_RAW_DATA, $iv); return $plaintext; } }
身份验证加密
上述方法仅提供加密,使数据容易被篡改。为了解决这个问题,请实施经过身份验证的加密方案:
class SaferCrypto extends UnsafeCrypto { // MAC algorithm const HASH_ALGO = 'sha256'; /** * Encrypts and authenticates data using the specified key. * * @param string $message Plaintext message * @param string $key Encryption key * @param bool $encode Whether to encode the result * * @return string Encrypted and authenticated data */ public static function encrypt($message, $key, $encode = false) { // Split key into encryption and authentication keys list($encKey, $authKey) = self::splitKeys($key); // Encrypt using UnsafeCrypto::encrypt $ciphertext = parent::encrypt($message, $encKey); // Calculate MAC $mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true); // Concatenate MAC and ciphertext if ($encode) { return base64_encode($mac . $ciphertext); } return $mac . $ciphertext; } /** * Decrypts and authenticates data using the specified key. * * @param string $message Encrypted and authenticated data * @param string $key Encryption key * @param bool $encoded Whether the message is encoded * * @throws Exception * * @return string Decrypted message */ public static function decrypt($message, $key, $encoded = false) { // Split key list($encKey, $authKey) = self::splitKeys($key); // Decode message if necessary if ($encoded) { $message = base64_decode($message, true); if ($message === false) { throw new Exception('Encryption failure'); } } // Extract MAC and ciphertext $hs = strlen(hash(self::HASH_ALGO, '', true), '8bit'); $mac = substr($message, 0, $hs); $ciphertext = substr($message, $hs); // Calculate expected MAC $expectedMac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true); // Verify MAC if (!self::hashEquals($mac, $expectedMac)) { throw new Exception('Encryption failure'); } // Decrypt message using UnsafeCrypto::decrypt $plaintext = parent::decrypt($ciphertext, $encKey); return $plaintext; } /** * Splits a key into two separate keys for encryption and authentication. * * @param string $masterKey Master key * * @return string[] Array of encryption and authentication keys */ protected static function splitKeys($masterKey) { return [ hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true), hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true) ]; } /** * Compares two strings without leaking timing information * (PHP 7+). * * @param string $a * @param string $b * * @return bool */ 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); } }
请记住,为了强大的安全性,请考虑使用信誉良好的加密库。
以上是如何使用 OpenSSL 在 PHP 中实现简单的双向加密?的详细内容。更多信息请关注PHP中文网其他相关文章!

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,数据库imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)优化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

依赖性注射inphpisadesignpatternthatenhancesFlexibility,可检验性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

PHP性能优化可以通过以下步骤实现:1)在脚本顶部使用require_once或include_once减少文件加载次数;2)使用预处理语句和批处理减少数据库查询次数;3)配置OPcache进行opcode缓存;4)启用并配置PHP-FPM优化进程管理;5)使用CDN分发静态资源;6)使用Xdebug或Blackfire进行代码性能分析;7)选择高效的数据结构如数组;8)编写模块化代码以优化执行。

opcodecachingsimplovesphperforvesphpermance bycachingCompiledCode,reducingServerLoadAndResponSetimes.1)itstorescompiledphpcodeinmemory,bypassingparsingparsingparsingandcompiling.2)useopcachebachebachebachebachebachebachebysettingparametersinphametersinphp.ini,likeememeryconmorysmorysmeryplement.33)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。