Php implements RSA encryption instances and phprsa encryption instances

Source: Internet
Author: User
Tags readfile asymmetric encryption

Php implements RSA encryption instances and phprsa encryption instances

This example describes how to implement RSA encryption in php. Share it with you for your reference. The specific analysis is as follows:

Openssl-based signatures, signatures, and asymmetric encryption and decryption must be used with x.509 certificates (such as crt and pem) files.
For various reasons, this class is not perfect. You are welcome to test it!

<? 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: linvo * @ version: 1.0.0 * @ date: 2013/1/23 */class RSA {private $ pubKey = null; private $ priKey = null; /*** custom error handling */private function _ Error ($ msg) {die ('rsa error :'. $ msg); // TODO}/*** constructor ** @ param string public key file (passed during signature verification and encryption) * @ param string private key file (imported during signature and decryption) */public function _ construct ($ public_key_file = '', $ Private_key_file = '') {if ($ public_key_file) {$ this-> _ getPublicKey ($ public_key_file);} if ($ private_key_file) {$ this-> _ getPrivateKey ($ private_key_file) ;}/ *** 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 cypherte Xt, 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 ;} // Private method/*** 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) {case 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': default:} return $ data ;} private function _ decode ($ data, $ code) {switch (strtolower ($ code) {case 'base64': $ data = B Ase64_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 ;}}

Test demo:

<? Php header ('content-Type: text/html; Charset = UTF-8; '); include "rsa. php "; echo '<pre>'; $ a = isset ($ _ GET ['a'])? $ _ GET ['a']: 'test 100 '; /// ///$ pubfile = 'e: \ ssl \ cert \ pwd. crt '; $ prifile = 'e: \ ssl \ cert \ pwd. pem'; $ m = new RSA ($ pubfile, $ prifile); $ x = $ m-> sign ($ ); $ y = $ m-> verify ($ a, $ x); var_dump ($ x, $ y); $ x = $ m-> encrypt ($ ); $ y = $ m-> decrypt ($ x); var_dump ($ x, $ y );

I hope this article will help you with php programming.

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.