RSA algorithm Class (PHP)

Source: Internet
Author: User

Signed, checked, asymmetric, and decrypted via OpenSSL need to be used in conjunction with X.509 certificates (such as CRT and PEM) files.

For a variety of reasons, this class is not very perfect, welcome to various tests.


<?php/** * RSA algorithm class * Signature and ciphertext code: Base64 string/16 binary string/binary string stream * Fill mode: pkcs1padding (add-Decrypt)/nopadding (decryption) * * Notice:only ACC Epts a single block. 
 Block size is equal to the RSA key size! * If the key length is 1024 bit, then the data should be less than 128 bytes when encrypted, plus 11 bytes of pkcs1padding itself, so plaintext needs to be less than 117 bytes * * @author: Linvo * @version: 1.0.0 * @date: 201
    3/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 in when checking and encrypting) * @param string private key file (passed in when signing and decrypting) * * __const Ruct ($public _key_file = ', $private _key_file = ') {if ($public _key_file) {$this->_getpublickey ($p
        Ublic_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; 
     /** * Verification 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; /** * Encryption * * @param string plaintext * @param string cipher Code (BASE64/HEX/BIN) * @param int fill mode (Looks like PHP
 There is a bug, so currently only supports openssl_pkcs1_padding) * @return string redaction    * * 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; /** * Decryption * * @param string redaction * @param string cipher Code (BASE64/HEX/BIN) * @param int Fill method (opens sl_pkcs1_padding/openssl_no_padding) * @param bool Flip plaintext (When passing Microsoft cryptoapi-generated RSA cyphertext , revert the bytes in the block) * @return string plaintext/Public function decrypt ($data, $code = ' base64 ', $PA
        dding = 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), "
            "): '. $result;
    } return $ret;  }//Private method/** * Detect fill type * Encryption only supports pkcs1_padding * decryption support pkcs1_padding and no_padding * * @param
        int fill 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 = 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);
        The Private Function _getprivatekey ($file) {$key _content = $this->_readfile ($file); if ($key_content) {$this->prikey = Openssl_get_privatekey ($key _content);
        The 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; The Private function _hex2bin ($hex = False) {$ret = $hex!== false && preg_match ('/^[0-9a-fa-f]+$/i '), $hex)?    
        Pack ("h*", $hex): false;
    return $ret; }



}

Testing a small Demo

<?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);




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.