PHP Encryption and decryption method

Source: Internet
Author: User

<?php
Can be used for encryption and decryption, such as cookies, accounts, mobile phone number as so Onclass Des{var $key; var $iv;//Offset function __construct ($key, $iv =0) {//key length 8 for example: 1234ABCD $this->key = $key, if ($iv = = 0) {$this->iv = $key;//default $key as IV} else {$this->iv = $iv;//mcrypt_create_iv ( Mcrypt_get_block_size (Mcrypt_des, MCRYPT_MODE_CBC), mcrypt_dev_random);}} function Encrypt ($STR) {//encryption, return uppercase hexadecimal string $size = Mcrypt_get_block_size (Mcrypt_des, MCRYPT_MODE_CBC); $str = $this Pkcs5pad ($str, $size); return Strtoupper (Bin2Hex (MCRYPT_CBC (mcrypt_des, $this->key, $str, Mcrypt_encrypt, $this-&G T;IV)));} function Decrypt ($STR) {//Decrypt $strbin = $this->hex2bin (strtolower ($STR)); $str = MCRYPT_CBC (mcrypt_des, $this->key , $strBin, Mcrypt_decrypt, $this->iv) $str = $this->pkcs5unpad ($str); return $str;} function Hex2bin ($hexData) {$binData = ""; for ($i = 0; $i < strlen ($hexData); $i + = 2) {$binData. = Chr (Hexdec (substr ($hexData, $i, 2)));} return $binData;} function Pkcs5pad ($text, $blocksize) {$pad = $bLocksize-(strlen ($text)% $blocksize); return $text. Str_repeat (Chr ($pad), $pad);} function Pkcs5unpad ($text) {$pad = Ord ($text {strlen ($text)-1}), if ($pad > strlen ($text)) return False;if (St RSPN ($text, Chr ($pad), strlen ($text)-$pad)! = $pad) return False;return substr ($text, 0,-1 * $pad);}} Instantiate, and pass in two parameters, all 8 bits, i.e. KEY, vi value $des = new des (' abcd1234 ', ' 87654321 ');//encryption result $AA = 7a3c7bba8b42adc4$str = ' 123456 '; $aa = $ Des->encrypt ($STR); echo $aa;//decryption results $BB 123456$BB = $des->decrypt ($AA); Echo $bb; >

  

PHP Encryption and decryption method

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.