(PHP 5 >= 5.3.0, PHP 7)
openssl_encrypt — ��������
$data
, string $method
, string $key
[, int $options = 0
[, string $iv = ""
[, string &$tag = NULL
[, string $aad = ""
[, int $tag_length = 16
]]]]] ) : string��ָ���ķ�ʽ�� key �������ݣ�����ԭʼ�� base64 �������ַ�����
data�����ܵ�������Ϣ���ݡ�
method����ѧ��ʽ��openssl_get_cipher_methods() �ɻ�ȡ��Ч���뷽ʽ�б�
keykey��
options
options �����±�ǵİ�λ��
OPENSSL_RAW_DATA ��
OPENSSL_ZERO_PADDING��
iv�� NULL �ij�ʼ��������
tagʹ�� AEAD ����ģʽ��GCM �� CCM��ʱ�����õ���֤��ǩ��
aad���ӵ���֤���ݡ�
tag_length
��֤ tag �ij��ȡ�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($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";
}
?>
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($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))//PHP 5.6+ timing attack safe comparison
{
echo $original_plaintext."\n";
}
?>