openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_encrypt锟斤拷锟斤拷锟斤拷锟斤拷

说锟斤拷

openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] ) : string

锟斤拷指锟斤拷锟侥凤拷式锟斤拷 key 锟斤拷锟斤拷锟斤拷锟捷o拷锟斤拷锟斤拷原始锟斤拷 base64 锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷锟斤拷

锟斤拷锟斤拷

data

锟斤拷锟斤拷锟杰碉拷锟斤拷锟斤拷锟斤拷息锟斤拷锟捷★拷

method

锟斤拷锟斤拷学锟斤拷式锟斤拷openssl_get_cipher_methods() 锟缴伙拷取锟斤拷效锟斤拷锟诫方式锟叫憋拷

key

key锟斤拷

options

options 锟斤拷锟斤拷锟铰憋拷堑陌锟轿伙拷锟� OPENSSL_RAW_DATA 锟斤拷 OPENSSL_ZERO_PADDING锟斤拷

iv

锟斤拷 NULL 锟侥筹拷始锟斤拷锟斤拷锟斤拷锟斤拷

tag

使锟斤拷 AEAD 锟斤拷锟斤拷模式锟斤拷GCM 锟斤拷 CCM锟斤拷时锟斤拷锟斤拷锟矫碉拷锟斤拷证锟斤拷签锟斤拷

aad

锟斤拷锟接碉拷锟斤拷证锟斤拷锟捷★拷

tag_length

锟斤拷证 tag 锟侥筹拷锟饺★拷GCM 模式时锟斤拷锟斤拷锟侥凤拷围锟斤拷 4 锟斤拷 16锟斤拷

锟斤拷锟斤拷值

锟缴癸拷时锟斤拷锟截硷拷锟杰猴拷锟斤拷址锟斤拷锟斤拷锟� 锟斤拷锟斤拷锟斤拷失锟斤拷时锟斤拷锟斤拷 FALSE锟斤拷

锟斤拷锟斤拷锟届常

method 锟斤拷锟斤拷未知锟姐法时锟斤拷锟斤拷锟斤拷 E_WARNING 锟斤拷锟斤拷拇锟斤拷锟�

iv 锟斤拷锟斤拷锟斤拷址锟斤拷锟绞憋拷锟斤拷锟� E_WARNING 锟斤拷锟斤拷拇锟斤拷锟�

锟斤拷锟斤拷锟斤拷志

锟芥本 说锟斤拷
5.3.3 锟斤拷锟斤拷 iv 锟斤拷锟斤拷锟斤拷
5.4.0 raw_output 锟侥碉拷 options锟斤拷
7.1.0 锟斤拷锟斤拷锟斤拷 tag锟斤拷aad锟斤拷tag_length 锟斤拷锟斤拷

锟斤拷锟斤拷

Example #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($cipheropenssl_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";
}
?>

Example #2 PHP 5.6+ 锟斤拷 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($c0$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))//PHP 5.6+ timing attack safe comparison
{
    echo 
$original_plaintext."\n";
}
?>

锟轿硷拷