PHP RSA Encrypted Transport code sample

Source: Internet
Author: User
Tags base64 openssl openssl rsa asymmetric encryption
PHP RSA Encrypted Transport code sample


When it comes to transmission of sensitive data, it is best for both parties to use cryptographic decryption. RSA Asymmetric encryption is a promising one.


The server can keep its private key and send it to the client's corresponding public key. So that we can decrypt each other. RSA encryption and decryption implementation in PHP:


First, you generate a pair of public key private keys. The prerequisite is that the OpenSSL command is installed on the Linux machine.


Generate private Key file:


OpenSSL genrsa-out Rsa_private_key.pem 1024
The public key is generated using the private key:


OpenSSL rsa-in rsa_private_key.pem-pubout-out Rsa_public_key.pem



Creates a pair of keys. PHP Code:


Copy Code
<?php
Ini_set (' error_reporting ',-1);
Ini_set (' Display_errors ',-1);


Header (' content-type:text/html; Charset=utf-8 ');




# OpenSSL Genrsa-out Rsa_private_key.pem 1024
# OpenSSL rsa-in rsa_private_key.pem-pubout-out Rsa_public_key.pem




$private _key = file_get_contents ("/home/users/xx/test/rsa_private_key.pem");
$public _key = file_get_contents ("/home/users/xx/test/rsa_public_key.pem");


$pi _key = openssl_pkey_get_private ($private _key);/Available return resource ID
$pu _key = openssl_pkey_get_public ($public _key);




Encrypt data
$data = Array (
' id ' => ' 1234567890 ',
' Name ' => ' Xiaoming ',
' Mobile ' => ' 123456 ',
);
$data = Json_encode ($data);




$encrypted = ';
$decrypted = ';


Openssl_public_encrypt ($data, $encrypted, $pu _key);/Public key encryption
$encrypted = Base64_encode ($encrypted);//Base64 transmission
Echo $encrypted, "<br/>";




Openssl_private_decrypt (Base64_decode ($encrypted), $decrypted, $pi _key);//private key decryption
Echo $decrypted, "<br/>";




Print_r (Json_decode ($decrypted, true));
Copy Code



Public Key Cryptography (OPENSSL_PUBLIC_ENCRYPT), private key decryption (Openssl_private_decrypt). Private key Encryption (OPENSSL_PRIVATE_ENCRYPT), public key decryption (Openssl_public_decrypt). is a truth, the code is similar.


RSA encryption decryption has a fill mode padding parameters, the interaction between different programming languages, you need to pay attention to this.


Padding can be one of openssl_pkcs1_padding, openssl_sslv23_padding, openssl_pkcs1_oaep_padding,openssl_no_padding





It is noteworthy that if the choice of the key is 1024bit long (OpenSSL genrsa-out Rsa_private_key.pem 1024), then the plaintext length bytes that support encryption can only be 1024/8=128byte;


If the encrypted PADDING fill is openssl_pkcs1_padding (which takes up to 11 bytes), the plaintext length can only be 128-11=117 bytes. If it is exceeded, then these OpenSSL and decryption functions return false.





There is a solution, the need to encrypt the source string in less than 117 length divided into groups, at the time of decryption in 172 bytes divided into groups.


It is worth saying that "less than 117" (as long as it is not more than 117) and "172" two numbers come.


Why less than 117 is OK, because the length of the byte after the RSA encrypt is fixed, the key is long 1024bit/8=128byte. So as long as encrypt does not return false, that is, if it is not greater than 117 bytes, then the return of the encrypted is 128byte.


172 because of what. Since the length of the 128-byte base64_encode is fixed at 172.


Here by the way popularize base64_encode. The length of the encode has a formula for calculating the length of the original text:


$len 2 = $len 1%3 >0? (Floor ($len 1/3) *4 + 4): ($len 1*4/3);





PlainText exceeds the length of the code (provided it is 1024bit of key length, openssl_pkcs1_padding padding, or number to change)


Copy Code
<?php




$pi _key = openssl_pkey_get_private ($private _key);//resource type
$pu _key = openssl_pkey_get_public ($public _key);


$data = Array (
' username ' => ' Zhang 31 ',
' Mobile ' => ' 13321995977 ',
' Info ' => ' 14bmitesqd4pywodwmy7rrrvyfpenjjtecljvkb7ikrvxvdkp1xijngkh
2h5syhq5qslpsgyj1m/xkdnginwalvhvd3bokkgkg1bzn7ao5pxt+herqxavwws6
Ga63yvsic8jcodxiuvxjnumqrlaqof6aub/2vwc2t5mdmxlhakea3pwgpvxgliwl
3h7qlyzlrlrbfrurn4cyl4uyaakokkavzly04glle8ycgoc2dzl4eil4l/+x/gaq
Deju/chlrqjbanozy0meovkwhu4bscsdnfm6usqowybewhyy ',
);




$str = Json_encode ($data);




$en = Encrypt_rsa ($str, $pu _key);




$de = Decrypt_rsa ($en, $pi _key);


Echo $de;






function Encrypt_rsa ($data, $pu _key) {
$split = Str_split ($data,)//1024bit && openssl_pkcs1_padding not greater than 117
foreach ($split as $part) {
$isOkay = Openssl_public_encrypt ($part, $en _data, $pu _key);
if (! $isOkay) {
return false;
}
Echo strlen ($en _data), ' <br/> ';
$encode _data. = Base64_encode ($en _data);
}
return $encode _data;
}




function Decrypt_rsa ($data, $pi _key) {
$split = Str_split ($data, 172);//1024bit Fixed 172
foreach ($split as $part) {
$isOkay = Openssl_private_decrypt (Base64_decode ($part), $de _data, $pi _key);//Base64 used here, because 172 bytes is a group, it's encode.
if (! $isOkay) {
return false;
}
$decode _data. = $de _data;
}
return $decode _data;
}

Recently done project research, temporary as a memo. Thank the original author

Https://www.cnblogs.com/firstForEver/p/5803940.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.