Php rsa encryption and decryption methods and development interfaces, rsa encryption and decryption

Source: Internet
Author: User

Php rsa encryption and decryption methods and development interfaces, rsa encryption and decryption

Network security is very important, especially to ensure data security. Many programmers who write interfaces directly transmit plaintext data. In my opinion, this is not professional. I advocate that all data through interfaces should be encrypted and decrypted before use.

This article mainly introduces the use of PHP interfaces for data encryption and decryption after RSA encryption and decryption. The example analyzes the PHP custom RSA class encryption and decryption techniques, which is very useful, for more information, see.

Brief Introduction to RSA

The RSA encryption algorithm is the most common asymmetric encryption algorithm, and CFCA cannot leave it in the certificate service. However, many new users do not know much about it. The following is a brief introduction. RSA is the first perfect Public Key algorithm. It can be used for both encryption and digital signature. RSA is named by the first letter of its three inventors Ron Rivest, Adi Shamir, and Leonard Adleman. This algorithm has withstood years of in-depth password analysis, although cryptographic analysts cannot prove or deny the security of RSA, it just shows that the algorithm has a certain credibility and has become the most popular public key algorithm. RSA Security is based on the difficulty of big number decomposition. The public key and private key are functions of a large prime number (100 to 200 digits in decimal number or greater. The difficulty of recovering plaintext from a public key and ciphertext is equivalent to decomposing the product of two large prime numbers (this is a recognized mathematical problem ).

The following are specific classes and instances:

<? Php/*** RSA algorithm class * signature and ciphertext encoding: base64 string/hexadecimal string/binary string stream * Filling Method: PKCS1Padding (encryption and decryption)/NOPadding (decryption) ** Notice: Only accepts a single block. block size is equal to the RSA key size! * If the key length is 1024 bits, the encrypted data size must be less than 128 bytes, And the PKCS1Padding's own 11 bytes. Therefore, the plaintext size must be less than 117 bytes. ** @ author: zhi1__wei * @ version: 1.0.0 * @ date: Latest /06/30 */class RSA {private $ pubKey = null; private $ priKey = null; /*** constructor *** @ param string public key file (passed during signature verification and encryption) * @ param string private key file (passed during signature and decryption) */public function _ construct ($ public_key_file = '', $ private_key_file ='') {if ($ public_key_file) {$ this-> _ getPublicKey ($ publi C_key_file);} if ($ private_key_file) {$ this-> _ getPrivateKey ($ private_key_file );}} // private method/*** custom error handling */private function _ Error ($ msg) {die ('rsa error :'. $ msg ); // TODO}/*** detection fill type * encryption only supports PKCS1_PADDING * decryption supports PKCS1_PADDING and NO_PADDING ** @ param int filling mode * @ param string encryption en/Decryption de *@ return bool */private function _ checkPadding ($ padding, $ type) {if ($ type = 'en') {switch ($ padding) {ca Se OPENSSL_PKCS1_PADDING: $ ret = true; break; default: $ ret = false;} else {switch ($ padding) {case OPENSSL_PKCS1_PADDING: case OPENSSL_NO_PADDING: $ ret = true; break; default: $ ret = false ;}}return $ ret;} private function _ encode ($ data, $ code) {switch (strtolower ($ code) {case 'base64 ': $ data = base64_encode (''. $ data); break; case 'hex': $ data = bin2hex ($ data); break; case 'bin': def Ault:} return $ data;} private function _ decode ($ data, $ code) {switch (strtolower ($ code) {case 'base64 ': $ data = base64_decode ($ data); break; case 'hex': $ data = $ this-> _ hex2bin ($ data); break; case 'bin': default :} return $ data;} private function _ getPublicKey ($ file) {$ key_content = $ this-> _ readFile ($ file); if ($ key_content) {$ this-> pubKey = openssl_get_publickey ($ key_content) ;}} private Function _ getPrivateKey ($ file) {$ key_content = $ this-> _ readFile ($ file); if ($ key_content) {$ this-> priKey = openssl_get_privatekey ($ key_content) ;}} private function _ readFile ($ file) {$ ret = false; if (! File_exists ($ file) {$ this-> _ error ("The file {$ file} is not exists");} else {$ ret = file_get_contents ($ file );} return $ ret;} private function _ hex2bin ($ hex = false) {$ ret = $ hex! = False & preg_match ('/^ [0-9a-fA-F] + $/I', $ hex )? Pack ("H *", $ hex): false; return $ ret ;} /*** generate a signature ** @ param string signature material * @ param string signature encoding (base64/hex/bin) * @ return signature value */public function sign ($ data, $ code = 'base64') {$ ret = false; if (openssl_sign ($ data, $ ret, $ this-> priKey )) {$ ret = $ this-> _ encode ($ ret, $ code);} return $ ret ;} /***** verify the signature ** @ param string signature material * @ param string signature value * @ param string signature encoding (base64/hex/bin) * @ return bool */ Public function verify ($ data, $ sign, $ code = 'base64') {$ ret = false; $ sign = $ this-> _ decode ($ sign, $ code ); if ($ sign! = False) {switch (openssl_verify ($ data, $ sign, $ this-> pubKey) {case 1: $ ret = true; break; case 0: case-1: default: $ ret = false;} return $ ret;}/*** encrypt ** @ param string plaintext * @ param string ciphertext encoding (base64/hex/bin) * @ param int fill mode (it seems that php has a bug, so currently only OPENSSL_PKCS1_PADDING is supported) * @ return string ciphertext */public function encrypt ($ data, $ code = 'base64 ', $ padding = OPENSSL_PKCS1_PADDING) {$ ret = false; If (! $ This-> _ checkPadding ($ padding, 'en') $ this-> _ error ('padding error'); if (openssl_public_encrypt ($ data, $ result, $ this-> pubKey, $ padding) {$ ret = $ this-> _ encode ($ result, $ code);} return $ ret ;} /*** decrypt ** @ param string ciphertext * @ param string ciphertext encoding (base64/hex/bin) * @ param int fill mode (OPENSSL_PKCS1_PADDING/OPENSSL_NO_PADDING) * @ param bool whether to flip the plaintext (When passing Microsoft CryptoAPI-generated RSA cyphert Ext, revert the bytes in the block) * @ return string plaintext */public function decrypt ($ data, $ code = 'base64', $ padding = OPENSSL_PKCS1_PADDING, $ rev = false) {$ ret = false; $ data = $ this-> _ decode ($ data, $ code); if (! $ This-> _ checkPadding ($ padding, 'de') $ this-> _ error ('padding error'); if ($ data! = False) {if (openssl_private_decrypt ($ data, $ result, $ this-> priKey, $ padding) {$ ret = $ rev? Rtrim (strrev ($ result), "\ 0"): ''. $ result;} return $ ret ;}}

This is a specific RSA class

<? Php/*** Author: Wei ZhiHua * Date: 0030 * Time: */header ('content-Type: text/html; Charset = UTF-8 ;'); include "RSA. php "; echo '<pre>'; $ pubfile = 'd: \ WWW \ test \ rsa_public_key.pem '; $ prifile = 'd: \ WWW \ test \ rsa_private_key.pem '; $ rsa = new RSA ($ pubfile, $ prifile); $ rst = array ('ret '=> 200, 'code' => 1, 'data' => array (1, 2, 3, 4, 5, 6), 'msg '=> "success",); $ ex = json_encode ($ rst ); // encrypt $ ret_e = $ rsa-> encrypt ($ ex); // decrypt $ ret_d = $ rsa-> decrypt ($ ret_e); echo $ ret_e; echo '<pre>'; echo $ ret_d; echo '<pre>'; $ a = 'test '; // signature $ x = $ rsa-> sign ($ a); // verify $ y = $ rsa-> verify ($ a, $ x); var_dump ($ x, $ y); exit;

Related Article

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.