찾다
백엔드 개발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() 기능은 데이터를 암호화하고 복호화하는 접근 가능한 방법을 제공합니다. 권장되는 암호화 알고리즘은 128, 192 또는 256비트 변형의 AES-CTR입니다.

주의: 지원 중단 및 잠재적인 보안 위험으로 인해 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 09, 2025 am 12:14 AM

phpisusedforendingemailsduetoitsintegrationwithsermailservices 및 externalsmtpproviders, 1) setupyourphpenvironmentwitheberverandphp, temailfuncpp를 보장합니다

PHP를 통해 이메일을 보내는 방법 : 예 및 코드PHP를 통해 이메일을 보내는 방법 : 예 및 코드May 09, 2025 am 12:13 AM

이메일을 보내는 가장 좋은 방법은 Phpmailer 라이브러리를 사용하는 것입니다. 1) Mail () 함수를 사용하는 것은 간단하지만 신뢰할 수 없으므로 이메일이 스팸으로 입력되거나 배송 할 수 없습니다. 2) Phpmailer는 더 나은 제어 및 신뢰성을 제공하며 HTML 메일, 첨부 파일 및 SMTP 인증을 지원합니다. 3) SMTP 설정이 올바르게 구성되었는지 확인하고 (예 : STARTTLS 또는 SSL/TLS) 암호화가 보안을 향상시키는 데 사용됩니다. 4) 많은 양의 이메일의 경우 메일 대기열 시스템을 사용하여 성능을 최적화하십시오.

고급 PHP 이메일 : 사용자 정의 헤더 및 기능고급 PHP 이메일 : 사용자 정의 헤더 및 기능May 09, 2025 am 12:13 AM

CustomHeadersAndAdAncedFeaturesInpHeAmailEnhanceFectionality.1) 1) CustomHeadersAdDmetAdataFortrackingand Categorization.2) htmlemailsallowformattingandinteractivity.3) attachmentSentUsingLibraries likePhpMailer.4) smtpauthenticimprpr

PHP & SMTP와 함께 이메일 보내기 안내서PHP & SMTP와 함께 이메일 보내기 안내서May 09, 2025 am 12:06 AM

PHP 및 SMTP를 사용하여 메일을 보내는 것은 PHPMailer 라이브러리를 통해 달성 할 수 있습니다. 1) phpmailer 설치 및 구성, 2) SMTP 서버 세부 정보 설정, 3) 이메일 컨텐츠 정의, 4) 이메일 보내기 및 손잡이 오류. 이 방법을 사용하여 이메일의 신뢰성과 보안을 보장하십시오.

PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?May 08, 2025 am 12:21 AM

TheBesteptroachForendingeMailsInphPisusingThephPmailerlibraryDuetoitsReliability, featurerichness 및 reaseofuse.phpmailersupportssmtp, proversDetailErrorHandling, supportSattachments, andenhancessecurity.foroptimalu

PHP의 종속성 주입을위한 모범 사례PHP의 종속성 주입을위한 모범 사례May 08, 2025 am 12:21 AM

의존성 주입 (DI)을 사용하는 이유는 코드의 느슨한 커플 링, 테스트 가능성 및 유지 관리 가능성을 촉진하기 때문입니다. 1) 생성자를 사용하여 종속성을 주입하고, 2) 서비스 로케이터 사용을 피하고, 3) 종속성 주입 컨테이너를 사용하여 종속성을 관리하고, 4) 주입 종속성을 통한 테스트 가능성을 향상 시키십시오.

PHP 성능 튜닝 팁 및 요령PHP 성능 튜닝 팁 및 요령May 08, 2025 am 12:20 AM

phpperformancetuningiscrucialbecauseitenhancesspeedandefficies, thearevitalforwebapplications.1) cachingsdatabaseloadandimprovesResponsetimes.2) 최적화 된 databasequerieseiesecessarycolumnsingpeedsupedsupeveval.

PHP 이메일 보안 : 이메일 보내기 모범 사례PHP 이메일 보안 : 이메일 보내기 모범 사례May 08, 2025 am 12:16 AM

theBestPracticesForendingEmailsSecurelyPinphPinclude : 1) usingecureconfigurations와 whithsmtpandstarttlSencryption, 2) 검증 및 inputSpreverventInseMeStacks, 3) 암호화에 대한 암호화와 비도시를 확인합니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.