php openssl private encrypt

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_private_encrypt — Шифрует данные секретным ключом

Описание

Эта функция используется, например, для подписи данных. Чтобы была уверенность в том, кто именно отправил сообщение.

Список параметров

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Смотрите также

User Contributed Notes 5 notes

Just a little note on [P.Peyremorte]’s note.

«- openssl_private_encrypt can encrypt a maximum of 117 chars at one time.»

By the way, if openssl_private_encrypt fails because of data size you won’t get anything but just false as returned value, the same for openssl_public_decrypt() on decryption.

«- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always «=» (filler)»

— For a 1024 bit key length => encrypted number of raw bytes is always a block of 128 bytes (1024 bits) by RSA design.
— For a 2048 bit key length => encrypted number of raw bytes is always a block of 256 bytes (2048 bits) by RSA design.
. and so on

About base64_encode output length, it depends on what you encode (meaning it depends on the bytes resulting after encryption), but in general the resulting encoded string will be about a 33% bigger (for 128 bytes bout 170 bytes and for 256 bytes about 340 bytes).

I would then generalize a little [P.Peyremorte]’s note by:
// given the variables as constants:

Encrypt using private key, decrypt using public key.

Use this for posting signed messages: Anyone with access to
your public key can read it, but they can’t create one with
your signature.

Here is a over simplified version of using the crypt capabilities for getting started:

// get some text from command line to work with
$tocrypt = trim(fgets(STDIN));

string(887) «——BEGIN RSA PRIVATE KEY——
MIICXAIBAAKBgQCy745x8AqGKlTWBu2Ub80boPaQxo/midZ4LHZ0zbPpiCAfkADN
VYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf8K/mA0LQ00MKBFaFottWt5cC
IaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTvpXRk0u46D6hKiy+TSQIDAQAB
AoGBAJe1jjNCDtoz19vi4doBdIhhT8vt3iHbafBX2lMr+MceeAXqpRNy10+e9op9
uh0G4+vGDialZnYbMBLs6Ngl+nVnzn+cN1MMJ18brgf3biZKzVzK9wmOW4eycWaR
9eLa7/+ns8Cw5GsLJdG+OHR2gXRXU4hzUFdf90UUbP+kuqK1AkEA2X04XznFDNmT
NuhyCixwinlziazJBp/81jjaBhYj3cG0nTF0Gactc/yD0yudbrMqjLBfts+FbG3Z
yFHKrAB/cwJBANKetll3M3aCGsermEK+9hbB8yMihCju6pAwClUNkrAgrm9zU4LP
WkC81RDzXbz+pfIqpopfn34F3+U2iMiOe1MCQCXpTgpLZ631v1Oy8S4U0QlSYnF9
TQ16lfhBsL+e3GGrgnBkTniqS6IMQm5tC+RgFuqvU//p7LgZ7fydRVb2P0ECQFp9
YADuKskmutTAj6lVnCtI5upYgQmJJHQQf8/tBfHwCKHPnbic17zqpGwk80go7Ckw
U98tmDuv0HMNTBVGygsCQALck7VNBRjL9iFzJMFis+alcP1ZC88wOLPvIxYbevUH
c8rZwRqt1aHwaWOoxcVom+tyzRC6gEYoBarmU1bX4No=
——END RSA PRIVATE KEY——
«
string(272) «——BEGIN PUBLIC KEY——
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy745x8AqGKlTWBu2Ub80boPaQ
xo/midZ4LHZ0zbPpiCAfkADNVYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf
8K/mA0LQ00MKBFaFottWt5cCIaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTv
pXRk0u46D6hKiy+TSQIDAQAB
——END PUBLIC KEY——
«
this is a test for crypting
( ¦E@n¥u?7Fëµ¥+-M¼ìk?7¥;t?8[j¼ñrƒ¦ª-TÜ++ßYG?-úö¦>9+k8OJn_?¦x?¦
dó+aév.cå?-ï`,¦?·5u¦p%Z²¤ÜI?û ¼

( ¦E@n¥u?7Fëµ¥+-M¼ìk?7¥;t?8[j¼ñrƒ¦ª-TÜ++ßYG?-úö¦>9+k8OJn_?¦x?¦
dó+aév.cå?-ï`,¦?·5u¦p%Z²¤ÜI?û ¼->this is a test for crypting

this is a test for crypting->hT!¡_
#+£-íßÿo»¢äSs+üSnäÖ-(¦ëIkl[¤¦=?í?Ç+Uy·N,=b=+¦TàmeNo¦A

Источник

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_decrypt — Расшифровка данных с помощью открытого ключа

Описание

Вы можете использовать эту функцию, например, чтобы проверить, было ли сообщение написано владельцем закрытого ключа.

Список параметров

public_key должен содержать соответствующий открытый ключ.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

Смотрите также

User Contributed Notes 3 notes

Just a little note on [P.Peyremorte]’s note in manual’s openssl_private_encrypt.

«- openssl_private_encrypt can encrypt a maximum of 117 chars at one time.»

By the way, if openssl_private_encrypt fails because of data size you won’t get anything but just false as returned value, the same for openssl_public_decrypt() on decryption.

«- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always «=» (filler)»

— For a 1024 bit key length => encrypted number of raw bytes is always a block of 128 bytes (1024 bits) by RSA design.
— For a 2048 bit key length => encrypted number of raw bytes is always a block of 256 bytes (2048 bits) by RSA design.
. and so on

About base64_encode output length, it depends on what you encode (meaning it depends on the bytes resulting after encryption), but in general the resulting encoded string will be about a 33% bigger (for 128 bytes bout 170 bytes and for 256 bytes about 340 bytes).

I would then generalize a little [P.Peyremorte]’s note by:
// given the variables as constants:

Источник

OpenSSL

User Contributed Notes 3 notes

I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You’d be a fool to use normal, ‘synchronous’ or two-way encryption for this, so the whole mcrypt library won’t help.

But, it turns out OpenSSL is extremely easy to use. yet it is so sparsely documented that it seems it would be incredibly hard.

» ;
>
else
<
echo «UNSECURE: This page is being access through an unsecure connection.

// Create the keypair
$res = openssl_pkey_new ();

echo «Private Key:
$privatekey

Public Key:
$publickey

$cleartext = ‘1234 5678 9012 3456’ ;

echo «Clear text:
$cleartext

echo «Crypt text:
$crypttext

echo «Decrypted text:
$decrypted

» ;
?>

Many thanks to other contributors in the docs for making this less painful.

For checking the status of a client certificate using OCSP, you can use this script:

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer’s key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.

In regards to the comment above:

«After generating a key pair with OpenSSL, the public key can be stored in plain text format. I then encrypted the private key itself using regular mcrypt with the human-memorizable key of my choice and converted it to ACSII using base64_encode. Then to get the private key back, I just decrypted it with mcrypt. This way I could store the encrypted private key on the server without worrying about having things stored unencrypted. «

To anyone reading this that might not be all that familiar with public key cryptography; I haven’t the slightest idea what this person is talking about, but I can tell you its an absolutely horrible idea. He might have ended up with something that «looked like a private key» insofar as it was a base64 encoded string, but he did not have a private key. The parameters that make up a public/private key pair are EXTREMELY specific and in the case of RSA rely on very large co-primes plus an even larger moduli. Its not just a base64 encoded string; and just for the record. base64 encoding is not encryption.

One of two things happened; the more likely is the whatever program he needed the certificate for realized there was something wrong with the private key, and ignored it, reverting to either a default key, or null encryption or something. The worse outcome would be if it interpreted whatever was there as legitimate; and encrypted data as if it were a a proper certificate; encrypting this way would likely provide close to zero security and I’m not even sure you could decrypt the data once encrypted. Its not worth giving much thought.

Just please; don’t do this.

You can read about pki certificate structures and attribute frameworks by pasting «T-REC-X.509-201210-I» into your favorite interwebs search widget and following the result to the International Telecommunications Union webpage, or you can refer to the numerous RFCs; 6818, 5820 being good places to start. The Internet Engineering Task Force archives all RFCs, but there are other sources as well. «IETF RFC» should be enough to get you there.

. sorry, the «spam buster» was giving me all kinds of issues.

Источник

openssl_encrypt

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

openssl_encrypt — Encrypts data

Description

Encrypts given data with given method and key, returns a raw or base64 encoded string

Parameters

The plaintext message data to be encrypted.

The passphrase. If the passphrase is shorter than expected, it is silently padded with NUL characters; if the passphrase is longer than expected, it is silently truncated.

A non-NULL Initialization Vector.

The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).

Additional authentication data.

Return Values

Returns the encrypted string on success or false on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown cipher algorithm is passed in via the cipher_algo parameter.

Emits an E_WARNING level error if an empty value is passed in via the iv parameter.

Changelog

Examples

Example #1 AES Authenticated Encryption in GCM mode example for PHP 7.1+

Example #2 AES Authenticated Encryption example prior to PHP 7.1

See Also

User Contributed Notes 24 notes

There’s a lot of confusion plus some false guidance here on the openssl library.

The basic tips are:

aes-256-ctr is arguably the best choice for cipher algorithm as of 2016. This avoids potential security issues (so-called padding oracle attacks) and bloat from algorithms that pad data to a certain block size. aes-256-gcm is preferable, but not usable until the openssl library is enhanced, which is due in PHP 7.1

Use different random data for the initialisation vector each time encryption is made with the same key. mcrypt_create_iv() is one choice for random data. AES uses 16 byte blocks, so you need 16 bytes for the iv.

Join the iv data to the encrypted result and extract the iv data again when decrypting.

Pass OPENSSL_RAW_DATA for the flags and encode the result if necessary after adding in the iv data.

Hash the chosen encryption key (the password parameter) using openssl_digest() with a hash function such as sha256, and use the hashed value for the password parameter.

There’s a simple Cryptor class on GitHub called php-openssl-cryptor that demonstrates encryption/decryption and hashing with openssl, along with how to produce and consume the data in base64 and hex as well as binary. It should lay the foundations for better understanding and making effective use of openssl with PHP.

Hopefully it will help anyone looking to get started with this powerful library.

Many users give up with handilng problem when openssl command line tool cant decrypt php openssl encrypted file which is encrypted with openssl_encrypt function.

For example how beginner is encrypting data:

?>

And then how beginner is trying to decrypt data from command line:

Or even if he/she determinates that openssl_encrypt output was base64 and tries:

Or even if he determinates that base64 encoded file is represented in one line and tries:

Or even if he determinates that IV is needed and adds some string iv as encryption function`s fourth parameter and than adds hex representation of iv as parameter in openssl command line :

All these troubles will have no result in any case.

BECAUSE THE PASSWORD PARAMETER DOCUMENTED HERE IS NOT THE PASSWORD.

It means that the password parameter of the function is not the same string used as [-pass pass:] parameter with openssl cmd tool for file encryption decryption.

And now how to correctly encrypt data with php openssl_encrypt and how to correctly decrypt it from openssl command line tool.

$iv = «1234567812345678» ;
$pass = ‘1234567812345678’ ;
$method = ‘aes-128-cbc’ ;

?>

IV and Key parameteres passed to openssl command line must be in hex representation of string.

The correct command for decrypting is:

As it has no salt has no padding and by setting functions third parameter we have no more base64 encoded file to decode. The command will echo that it works.

if (options & OPENSSL_RAW_DATA) <
outbuf[outlen] = ‘\0’;
RETVAL_STRINGL((char *)outbuf, outlen, 0);
> else <
int base64_str_len;
char *base64_str;

base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
>

So as we can see here, OPENSSL_ZERO_PADDING has a direct impact on the OpenSSL context. EVP_CIPHER_CTX_set_padding() enables or disables padding (enabled by default). So, OPENSSL_ZERO_PADDING disables padding for the context, which means that you will have to manually apply your own padding out to the block size. Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

OPENSSL_RAW_DATA does not affect the OpenSSL context but has an impact on the format of the data returned to the caller. When OPENSSL_RAW_DATA is specified, the returned data is returned as-is. When it is not specified, Base64 encoded data is returned to the caller.

PHP lacks a build-in function to encrypt and decrypt large files. `openssl_encrypt()` can be used to encrypt strings, but loading a huge file into memory is a bad idea.

So we have to write a userland function doing that. This example uses the symmetric AES-128-CBC algorithm to encrypt smaller chunks of a large file and writes them into another file.

To decrypt files that have been encrypted with the above function you can use this function.

Please note that at the time of writing this, there is an important and naive security vulnerability in «Example #2 AES Authenticated Encryption example for PHP 5.6+».

You MUST include the IV when calculating the HMAC. Otherwise, somebody could alter the IV during transport, thereby changing the decrypted message while maintaining HMAC integrity. An absolute disaster.

To fix the example, the HMAC should be calculated like this:

How to migrate from mcrypt to openssl with backward compatibility.

In my case I used Blowfish in ECB mode. The task was to decrypt data with openssl_decrypt, encrypted by mcrypt_encrypt and vice versa. It was obvious for a first sight. But in fact openssl_encrypt and mcrypt_encript give different results in most cases.

Investigating the web I found out that the reason is in different padding methods. And for some reasons openssl_encrypt behave the same strange way with OPENSSL_ZERO_PADDING and OPENSSL_NO_PADDING options: it returns FALSE if encrypted string doesn’t divide to the block size. To solve the problem you have to pad your string with NULs by yourself.

The second question was the key length. Both functions give the same result if the key length is between 16 and 56 bytes. And I managed to find that if your key is shorter than 16 bytes, you just have to repeat it appropriate number of times.

And finally the code follows which works the same way on openssl and mcrypt libraries.

$data = ‘my secret message’ ;
$key = ‘dontsay’ ;

string(32) «SWBMedXJIxuA9FcMOqCqomk0E5nFq6wv»
string(24) «my secret message\000\000\000\000\000\000\000»

Источник

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_encrypt — Encrypts data with public key

Description

This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

Parameters

This will hold the result of the encryption.

Return Values

Returns true on success or false on failure.

Changelog

VersionDescription
8.0.0public_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type OpenSSL key or OpenSSL X.509 was accepted.

See Also

User Contributed Notes 19 notes

We can’t guarantee that RSA will still be trusted for security in 2016, but this is the current best practice for RSA. The rest of the world is moving on to ECDH and EdDSA (e.g. Ed25519).

That said, make sure you are using OPENSSL_PKCS1_OAEP_PADDING or else you’re vulnerable to a chosen-ciphertext attack (Google: «Daniel Bleichenbacher 1998 RSA padding oracle» and you’ll find plenty of material on it.)

The only fix is to use OAEP (preferably with MGF1-SHA256, but this function doesn’t let you specify that detail and defaults to MGF1+SHA1).

Phpseclib offers RSAES-OAEP + MGF1-SHA256 for encryption and RSASS-PSS + MGF1-SHA256 for signatures.

If you don’t want to hassle with these details yourself, check out https://github.com/paragonie/EasyRSA

chsnyder writes that the data is limited to 936 bits in his implementation.

Actually, it has nothing to do with RSA being CPU intensive, RAM or anything of the sort.

Basically when you encrypt something using an RSA key (whether public or private), the encrypted value must be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key, in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.

However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer if the value you’re encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag, in which case you can go up to 1023-1024 bits). With a 2048-bit key it’s 1960 bits instead.

But as chsnyder correctly wrote, the normal application of a public key encryption algorithm is to store a key or a hash of the data you want to respectively encrypt or sign. A hash is typically 128-256 bits (the PHP sha1() function returns a 160 bit hash). And an AES key is 128 to 256 bits. So either of those will comfortably fit inside a single RSA encryption.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *