PHP RSA Encrypted Transfer code example (RPM)

Source: Internet
Author: User
Tags base64 decrypt openssl rsa asymmetric encryption

Original address: http://www.cnblogs.com/firstForEver/p/5803940.html

Involving the transmission of sensitive data, it is advisable for both parties to agree to decrypt using encryption. That RSA asymmetric encryption will do a very promising.

The server can reserve its own private key and send the corresponding public key to the client. So we can decrypt each other. RSA Plus decryption implementation in PHP:

The first is to generate a pair of public key keys. The prerequisite is that the OpenSSL command is installed on the Linux machine.

To generate a private key file:

1024

Using the private key, generate the public key:

OpenSSL RSA- in Rsa_private_key.pem-pubout-out Rsa_public_key.pem

Encryption and decryption process

<?PHPHeader(' content-type:text/html; Charset=utf-8 ');//access to public keys secret keys content$private _key=file_get_contents("./rsa_private_key.pem");$public _key=file_get_contents("./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 ' = ' Xiao Ming ', ' mobile ' = ' 123456 ',);$data= Json_encode ($data);$encrypted= ' ';$decrypted= ' '; Openssl_public_encrypt ($data,$encrypted,$pu _key);//Public Key Cryptography$encrypted=Base64_encode($encrypted);//Base64 TransmissionEcho $encrypted, "<br/>"; Openssl_private_decrypt (Base64_decode($encrypted),$decrypted,$pi _key);//private Key DecryptionEcho $decrypted, "<br/>";Print_r(Json_decode ($decrypted,true));

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

RSA encryption decryption has a fill mode padding parameters, different programming languages to interact, need to pay attention to this.

paddingCan be one of,,, OPENSSL_PKCS1_PADDING OPENSSL_SSLV23_PADDING OPENSSL_PKCS1_OAEP_PADDINGOPENSSL_NO_PADDING

It is important to note that if the selection key is 1024bit long (OpenSSL genrsa-out Rsa_private_key.pem 1024), then the plaintext length byte that supports encryption can only be 1024/8=128byte;

If the encrypted PADDING Fill method chooses Openssl_pkcs1_padding (which takes 11 bytes), the clear text length can only be 128-11=117 bytes. If exceeded, then these OpenSSL decryption functions will return false.

At this point, the solution is to separate the source strings that need to be encrypted into groups of less than 117 lengths, divided into groups of 172 bytes at the time of decryption.

Where the "less than 117" (as long as not more than 117) and "172" two numbers is how to come, it is worth to say.

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

172 Because of what? Because the length of the 128-byte base64_encode is fixed at 172.

Here by the way popular Base64_encode. The length of the encode is a formula for the length of the original text:

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

Clear text beyond the length of the code (provided that the 1024bit key length, openssl_pkcs1_padding fill mode, such as the generation of private keys set is 2048bit, Base64_decode ($encrypted) is the 344-word verse. Through strlen view, need otherwise number to change)

<?PHP$pi _key= Openssl_pkey_get_private ($private _key);//Resource Type$pu _key= Openssl_pkey_get_public ($public _key);$data=Array(    ' username ' + ' 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;functionEncrypt_rsa ($data,$pu _key){    $split=Str_split($data, 100);//1024bit && openssl_pkcs1_padding No more 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;}functionDecrypt_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 is used here, because 172 bytes is a group, it's encode .        if(!$isOkay){            return false; }        $decode _data.=$de _data; }    return $decode _data;}

Base64 recommendations refer to this article: http://www.ruanyifeng.com/blog/2008/06/base64.html

PHP RSA Encrypted Transfer code example (RPM)

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.