PHP RAS Cryptography Class Code

Source: Internet
Author: User
Tags decrypt

Signing, checking, asymmetric, and decrypting with OpenSSL is required to be used with the files of the certificates of the "." (Crt and PEM).

<?php/** * RSA algorithm class * Signature and Cipher code: Base64 string/16 binary string/binary string stream * Fill mode: pkcs1padding (plus decrypt)/nopadding (decryption) * Notice:only accepts A single block.  Block size is equal to the RSA key size! * If the key length is a small bit, then the encrypted data should be less than 128 bytes, plus the pkcs1padding itself 11 bytes of information, so clear text needs less than 117 bytes * * @author: Linvo * @version: 1.0.0 * @date: 2013/1/     */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 in when checking and encrypting) * @param a String private key file (passed in when signing and decrypting) */publicly 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 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 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 cipher (base64/hex/bin) * @param int Fill method (seemingly php has BU G, so currently only supports openssl_pkcs1_padding) * @return String cipher */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, $co         DE);     } return $ret; }/** * Decrypt * * @param string cipher * @param string cipher (base64/hex/bin) * @param int fill mode (openssl_ pkcs1_padding/openssl_no_padding) * @param if bool flips clear text (when passing Microsoft cryptoapi-generated RSA Cyphertext, re Vert 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), "n"): '. $result;     }} return $ret; }//Private method/** * Detect fill type * Encryption only supports pkcs1_padding * decryption support pkcs1_padding and no_padding * * @para         m int Fill mode * @param string encryption en/decrypt 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 = 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;   }          }


Test example

<?php header (' content-type:text/html; Charset=utf-8; ');    Include "rsa.php";    Echo ' <pre> '; $a = isset ($_get[' a ')? $_get[' A ']: ' Test 123 '; $pubfile = ' E:\SSL\CERT\PWD.CRT '; $prifile = ' E:\ssl\cert\pwd.pem ';    $m = new RSA ($pubfile, $prifile); $x = $m->sign ($a); $y = $m->verify ($a, $x); Var_dump ($x, $y);       $x = $m->encrypt ($a); $y = $m->decrypt ($x); Var_dump ($x, $y);  

PHP RAS Cryptography Class Code

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.