php-crypto
php-crypto copied to clipboard
Streams and filters
Streams
The new crypto stream API is a wrapper for OpenSSL BIO methods (BIO_s_*
). Currently just BIO_s_file
is wrapped by crypto.file://
stream.
Additional BIO filters can be added in stream context. The supported options are following:
-
cipher
=> array - Cipher filter (BIO_f_cipher
). The array can contain following fields:-
action
=> string (encrypt
|decrypt
) - whether to encrypt or decrypt data -
algorithm
=> string - algorithm name -
mode
=> string|int - cipher mode (optional - if not set, then it must be part of algorithm name) -
key_size
=> string|int - key size for the algorithm (optional - if not set, then it must be part of algorithm name) -
key
=> string - key string -
iv
=> string - initial vector string -
tag
=> string - authentication tag (optional and only for auth modes and actiondecrypt
) -
aad
=> string - additional application data (optional only for auth modes)
-
-
hash
=> string - hash name string (sha256, md5...) - Add hash (md) filter (BIO_f_md
) -
base64
=> string (encode
|decode
) | array - Add base64 filter (BIO_f_base64
). If the value is an array, then following options are allowed:-
action
=> string -encode
|decode
- whether to encode or decode data -
new_lines
=> bool - whether to encode the data all on one line or expect the data to be all on one line (optional - default false which means that new line are added - e.g. PEM)
-
Example
The following how to quickly encrypt file to the variable
$opts = array(
'cipher'=>array(
'action'=>"encrypt",
'algorithm'=> 'AES',
'mode' => Crypto\Cipher::MODE_GCM,
'key_size' => 256,
'kye' => $key,
'iv' => $iv,
'aad' => $aad,
)
);
$context = stream_context_create($opts);
$encrypted_file_data = file_get_contents('crypto.file:///home/jakub/file.txt', false, $context);
Future addition
The API can be significantly extended. New streams like crypto.connection, crypto.fd, crypto.socket could be added. There also are some filters that could be considered for addition (mainly ssl for connection).
Filters
There are filters that can be used for existing php streams.
-
crypto.encrypt
- encryption filter that accepts creation params that are almost the same as an array for cipher stream context option (exceptaction
field) -
crypto.decrypt
- decryption filter that accepts the same params ascrypto.encrypt
This should work similar way as the current mcrypt filters
Authentication
The resulted authentication tag after encryption can be found in the stream meta (wrapperdata
) using stream_get_meta_data
function. The name could be X-AuthenticationTag: tag
Just basic crypto.file://
stream and checking context params is implemented at the moment