openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_encrypt — 데이터 암호화


설명

openssl_encrypt(
    string $data,
    string $cipher_algo,
    string $passphrase,
    int $options = 0,
    string $iv = "",
    string &$tag = null,
    string $aad = "",
    int $tag_length = 16
): string|false
                

주어진 메서드와 키로 주어진 데이터를 암호화하고 raw 또는 base64로 인코딩된 문자열을 반환합니다.


매개변수

data
암호화할 일반 텍스트 메시지 데이터입니다.
cipher_algo
암호 메서드. 사용 가능한 암호 메서드 목록을 보려면 openssl_get_cipher_methods()를 사용하십시오.
passphrase
암호. 암호가 예상보다 짧으면 NUL 문자로 자동으로 채워집니다. 암호가 예상보다 길면 자동으로 잘립니다.
options
optionsOPENSSL_RAW_DATAOPENSSL_ZERO_PADDING 플래그의 비트 분리입니다.
iv
NULL이 아닌 초기화 벡터입니다.
tag
AEAD 암호 모드(GCM 또는 CCM)를 사용할 때 참조로 전달된 인증 태그입니다.
aad
추가 인증 데이터.
tag_length
인증 tag의 길이입니다. GCM 모드의 경우 값은 4에서 16 사이일 수 있습니다.

반환 값

성공하면 암호화된 문자열을 반환하고 실패하면 false를 반환합니다.


오류/예외

알 수 없는 암호 알고리즘이 cipher_algo 매개변수를 통해 전달되면 E_WARNING 수준 오류를 내보냅니다.

iv 매개변수를 통해 빈 값이 전달되면 E_WARNING 수준 오류를 내보냅니다.


변경 로그

버전 설명
7.1.0 tag, aadtag_length 매개변수가 추가되었습니다.

Examples

예제 #1 PHP 7.1+용 GCM 모드의 AES 인증 암호화 예

                  
<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
    //store $cipher, $iv, and $tag for decryption later
    $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
    echo $original_plaintext."\n";
}
?>
                  
                

예제 #2 PHP 7.1 이전의 AES 인증 암호화 예

                  
<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))// timing attack safe comparison
{
    echo $original_plaintext."\n";
}
?>
                  
                

기타