PHP uses asymmetric encryption algorithm (RSA)

Source: Internet
Author: User
Tags begin rsa private key decrypt openssl rsa asymmetric encryption

Explain

An asymmetric encryption algorithm requires two keys: Public key (PublicKey) and private key (Privatekey). Public key and private key is a pair, if the data encrypted with public key, only with the corresponding private key to decrypt, if the private key to encrypt the data, then only the corresponding public key can be decrypted. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm.

Usage Scenarios

PHP writes the API for the client (Android,ios) to decrypt the data.

Create a private key, public key

OpenSSL genrsa-out Rsa_private_key.pem 1024//generate original RSA private key file OpenSSL pkcs8-topk8-inform pem-in rsa_private_key.pem-outfor M pem-nocrypt-out private_key.pem//Convert the original RSA private key to PKCS8 format OpenSSL rsa-in rsa_private_key.pem-pubout-out RSA_PUBLIC_KEY.P EM//generates RSA public key//We use the private key Rsa_private_key.pem on the server side, the public key is issued to Android and iOS and other front end.

Service-side class library

Class RSA {private static $PRIVATE _key = '-----BEGIN Rsa Private KEY-----miicxgibaakbgqcozz8iubproic0kgckr5ax6/fd9 ikkmc/xhaykeavqps0oz0b1ojekpkdzbk0ownhp73ynv+ylkbwwxowb3u3hl8nblog/rilebbmdcf55cuznsfn/xf5cilr/aci/ ohute6ulvxs280t5m+nuh3ikdit6z9xrfbh69c+xfoninwidaqabaogae+ape7msdo+vc5vkcb4zprepvc3/ jmawifr3zg4cfpej7qjz8o9xcshxbs2zrkc6otex6idv/213shpzrt4l7+rsrgmoauwnjsvjr4t4z168uvsnnocn+3gwfzbbpqj3phje64r/ Mkwdvuq2uk945wytqfac6lt1mjaxhjxqpiecqqdygwybcsugqs0lndzreyotkb9eyr5ugli8nzn3pvwwkis3n3yusm2t3uokow02dlhkc4f1at097fm1w0fru snnakeax31taitigwgjg+ypmvwts8aenm0wxi/v6loexpbpxx2r4njsg+exyza7/dadq// mcksx0ecycsfn0e3hwsanmwjbajuxgohpuu1kiihrd25twissvdjbrateub4pp/2738qlwnqjfnmejluaak+ Kyjeuobl19ywymkucypw7pqqmlducqqc84dksdpyuk0pnfjk5qmxdehzsmafoy8gjpkrw286la8kmonz8tjcygvkr8ukkhqmrwcxanlafjopoknxyk8j1akea wcy3eheke4i3fhcjgsqagazffbs1jztnzxw/cxmmcbfxfh4wvhowqoc1iakdyz7hf7v+rcxcfuhobji/3+imeg==-----END RSA PRIVATE        KEY-----'; private static $PUBLIC _key = '-----BEGIN public KEY-----migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcozz8iubproic0kgckr5ax6/fd9ikkmc/xhaykeavqps0oz0b1ojekpkdzbk0ownhp73ynv+ ylkbwwxowb3u3hl8nblog/rilebbmdcf55cuznsfn/xf5cilr/aci/ohute6ulvxs280t5m+nuh3ikdit6z9xrfbh69c+       Xfoninwidaqab-----END Public KEY-----';                /** * Get private key * @return Bool|resource */private static function Getprivatekey () {                $privKey = self:: $PRIVATE _key;        Return Openssl_pkey_get_private ($privKey);    }/** * Get public key * @return Bool|resource */private static function Getpublickey ()                {$publicKey = self:: $PUBLIC _key;        Return Openssl_pkey_get_public ($publicKey); /** * Private key encryption * @param string $data * @return null|string */Public Stati               C function Privencrypt ($data = ") {if (!is_string ($data)) {return null; } return Openssl_privAte_encrypt ($data, $encrypted, Self::getprivatekey ())?        Base64_encode ($encrypted): null; }/** * Public key encryption * @param string $data * @return null|string * * * Stati                C function Publicencrypt ($data = ") {if (!is_string ($data)) {return null; } return Openssl_public_encrypt ($data, $encrypted, Self::getpublickey ())?        Base64_encode ($encrypted): null; }/** * Private key decryption * @param string $encrypted * @return NULL */public static function Privdecrypt ($encrypted = ") {if (!is_string ($encrypted)) {return                Null } return (Openssl_private_decrypt (Base64_decode ($encrypted), $decrypted, Self::getprivatekey ()))?        $decrypted: null; }/** * Public key decryption * @param string $encrypted * @return NULL */PubliC static function publicdecrypt ($encrypted = ") {if (!is_string ($encrypted)) {                return null; } return (Openssl_public_decrypt (Base64_decode ($encrypted), $decrypted, Self::getpublickey ()))?        $decrypted: null; }}

Service-side use

Require_once "rsa.php"; $rsa = new Rsa (); $data [' name '] = ' Tom '; $data [' age ']  = ' + '; $privEncrypt = $rsa Privencrypt (Json_encode ($data)); Echo ' private key is encrypted: '. $privEncrypt. '
'; $publicDecrypt = $rsa->publicdecrypt ($privEncrypt); Echo ' public key decrypted: '. $publicDecrypt. '
'; $publicEncrypt = $rsa->publicencrypt (Json_encode ($data)); Echo ' Public key is encrypted: '. $publicEncrypt. '
'; $privDecrypt = $rsa->privdecrypt ($publicEncrypt); Echo ' private key decrypted: '. $privDecrypt. '
';

Thanks ~

What is a good API design?

  • 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.