PHP8 openssl_encrypt

2024-03-12 12:00 更新

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

openssl_encrypt — 加密數(shù)據(jù)

說明

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

以指定的方式和 key 加密數(shù)據(jù),返回原始或 base64 編碼后的字符串。

參數(shù) ?

data

待加密的明文信息數(shù)據(jù)。

cipher_algo

密碼學(xué)方式。openssl_get_cipher_methods() 可獲取有效密碼方式列表。

passphrase

口令(passphrase)。 若 passphrase 比預(yù)期長度短,將靜默用 NUL 填充; 若比預(yù)期長度更長,將靜默截斷。

options

options 是以下標(biāo)記的按位或: OPENSSL_RAW_DATA 、 OPENSSL_ZERO_PADDING。

iv

非 NULL 的初始化向量。

tag

使用 AEAD 密碼模式(GCM 或 CCM)時傳引用的驗證標(biāo)簽。

aad

附加的驗證數(shù)據(jù)。

tag_length

驗證 tag 的長度。GCM 模式時,它的范圍是 4 到 16。

返回值 ?

成功時返回加密后的字符串, 或者在失敗時返回 false。

錯誤/異常 ?

cipher_algo 傳入未知算法時,產(chǎn)生 E_WARNING 級別的錯誤。

iv 傳入空字符串時產(chǎn)生 E_WARNING 級別的錯誤。

更新日志 ?

版本說明
7.1.0增加了 tag、aad、tag_length 參數(shù)

示例 ?

示例 #1 PHP 7.1 之前的 GCM 模式的 AES 認(rèn)證加密示例

<?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 5.6+ 的 AES 認(rèn)證加密例子

<?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";
}
?>

參見 ?

  • openssl_decrypt() - 解密數(shù)據(jù)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號