Please note that openssl_seal() cannot be used for EC encryption.
Took me literally two hours to find out because the OpenSSL documentation is so bad.openssl_seal
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
openssl_seal
Референца за `function.openssl-seal.php` со подобрена типографија и навигација.
openssl_seal
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
openssl_seal — Запечати (шифрирај) податоци
= NULL
Иницијализира контекст за инкрементално хеширање string
$data,string
&$sealed_data,array
&$encrypted_keys,array
$public_key,string
$cipher_algo,string
&$iv = null): int|false
openssl_seal() печати (шифрира) data користејќи го наведениот cipher_algo со случајно генериран таен клуч. Клучот потоа се шифрира со секој од јавните клучеви во public_key низа, и секој шифриран клучен плик се враќа во encrypted_keys. Ова овозможува запечатените податоци да бидат испратени до повеќе примачи (под услов нивните јавни клучеви да се достапни). Секој примач мора да ги добие и запечатените податоци и клучен плик кој беше шифриран со јавниот клуч на примачот. IV (Иницијализирачки вектор) се генерира, и неговата вредност се враќа во
iv.
Параметри
data-
Податоците за запечатување.
sealed_data-
Запечатените податоци.
encrypted_keys-
Низа од шифрирани клучеви.
public_key-
Низа од OpenSSLAsymmetricKey инстанци кои содржат јавни клучеви.
cipher_algo-
Методот на шифрирање.
Безбедност: стандардниот сет на знациСтандардната вредност за PHP верзии пред 8.0 е (
'RC4') што се смета за несигурно. Силно се препорачува експлицитно да се специфицира сигурен метод за шифрирање. iv-
Иницијализирачкиот вектор за дешифрирање на
data. Тој е задолжителен ако методот за шифрирање бара IV. Ова може да се дознае со повикување на openssl_cipher_iv_length() withcipher_algo.Безбедност: стандардниот сет на знациIV не може да се постави експлицитно. Секоја вредност поставена во него се презапишува со случајно генерирана вредност.
Вратени вредности
Враќа должина на запечатените податоци при успех, или false при грешка. Ако е успешно, запечатените податоци се враќаат во
sealed_data, а клучевите од пликот во
encrypted_keys.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
public_key прифаќа array of
OpenSSLAsymmetricKey инстанци сега; претходно, array of resourceи од тип OpenSSL key
беше прифатено.
|
| 8.0.0 |
cipher_algo веќе не е опционален параметар.
|
| 8.0.0 |
iv сега е null.
|
Примери
Пример #1 openssl_seal() example
<?php
// $data is assumed to contain the data to be sealed
$data = "test";
// fetch public keys
$pk1 = openssl_get_publickey("file://cert1.pem");
$pk2 = openssl_get_publickey("file://cert2.pem");
// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
if (openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2), 'AES256', $iv) > 0) {
// possibly store the $sealed and $iv values and use later in openssl_open
echo "success\n";
}
?>Белешки од корисници 6 белешки
while the default is using RC4, it is possible to use other more secure algorithms. These are specified as the fifth parameter. Also, one needs to add an initialization vector (random bytes). Eg.
<?php
$data = "This is top secret.";
// fetch public keys for our recipients, and ready them
$cert = file_get_contents('./cert.pem');
$pk1 = openssl_get_publickey($cert);
$iv = openssl_random_pseudo_bytes(32);
openssl_seal($data, $sealed, $ekeys, array($pk1), "AES256", $iv);
// free the keys from memory
openssl_free_key($pk1);
echo base64_encode($sealed);
?>"seals (encrypts) data by using RC4 with a randomly generated secret key"
It should be noted that the randomly generated secret key is 128 bits long (openssl: EVP_rc4(void): RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.)Some critical details that are not in the docs, nor widely written about elsewhere.
- The envelope key is a 128-bit RSA key, randomly generated.
- The data is encrypted with (A)RC4 using the envelope key.
- The envelope key is encrypted for transmission with PKCS1 v1.5. It is NOT the OAEP padding variant. PKCS1 v1.5 is even older, and not widely supported anymore.
At least this was true for openssl_seal in PHP 7.2 that we are using.
(Note: In Python you can decrypt this envelope key with the Cryptography package, using padding.PKCS1v15())
The combination of RC4 and PKCS1 v1.5 make this function actually semi-obsolete for security use in my opinion.According to several sources (e.g. crypto101.io or Wikipedia) RC4 is not safe and not supposed to be used anymore.
So, shouldn't openssl_seal use another stream cipher in place of RC4?openssl_seal() can work well when you need to pass data securely to other platforms / languages. What openssl_seal() does is;
1. Generate a random key
2. Encrypt the data symmetrically with RC4 using the random key
3. Encrypt the random key itself with RSA using the public key / certificate
4. Returns the encrypted data and the encrypted key
So to decrypt the steps are simply;
1. Decrypt the key using RSA and your private key
2. Decrypt the data using RC4 and the decrypted key
The trickiest part may be figuring out how handle the private key - BouncyCastle ( http://www.bouncycastle.org/ ) provides a PEMReader for Java and C# while Not Yet commons-ssl ( http://juliusdavies.ca/commons-ssl/ ) has a KeyStoreBuilder to build Java keystores out of a PEM certificate.
A complete example in Java is described at http://blog.local.ch/archive/2007/10/29/openssl-php-to-java.html