搜尋
首頁後端開發php教程如何使用 OpenSSL 在 PHP 中實作簡單的雙向加密?

How Can I Implement Simple Two-Way Encryption in PHP Using OpenSSL?

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

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

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

PHP電子郵件安全性:發送電子郵件的最佳實踐PHP電子郵件安全性:發送電子郵件的最佳實踐May 08, 2025 am 12:16 AM

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

您如何優化PHP應用程序的性能?您如何優化PHP應用程序的性能?May 08, 2025 am 12:08 AM

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,數據庫imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)優化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

PHP中的依賴注入是什麼?PHP中的依賴注入是什麼?May 07, 2025 pm 03:09 PM

依賴性注射inphpisadesignpatternthatenhancesFlexibility,可檢驗性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

最佳PHP性能優化技術最佳PHP性能優化技術May 07, 2025 pm 03:05 PM

PHP性能優化可以通過以下步驟實現:1)在腳本頂部使用require_once或include_once減少文件加載次數;2)使用預處理語句和批處理減少數據庫查詢次數;3)配置OPcache進行opcode緩存;4)啟用並配置PHP-FPM優化進程管理;5)使用CDN分發靜態資源;6)使用Xdebug或Blackfire進行代碼性能分析;7)選擇高效的數據結構如數組;8)編寫模塊化代碼以優化執行。

PHP性能優化:使用OpCode緩存PHP性能優化:使用OpCode緩存May 07, 2025 pm 02:49 PM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。