How to use encryption and decryption DES in php
This article is about how to use encryption and decryption DES in php. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Task flow chart
Segment 1
Just do it, and I started writing the des encryption class code as follows
Class DES {var $key; var $iv; / / offset function DES ($key, $iv=0) {/ / key length 8 for example: 1234abcd $this- > key = $key; if ($iv= = 0) {$this- > iv= $key;} else {$this- > iv= $iv; / / mcrypt_create_iv (mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM) }} function encrypt ($str) {/ / encryption returns the uppercase hexadecimal string $size = mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC); $str = $this- > pkcs5Pad ($str, $size); return strtoupper (mcrypt_cbc (MCRYPT_DES, $this- > key, $str, MCRYPT_ENCRYPT, $this- > 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 (strspn ($text, chr ($pad), strlen ($text)-$pad)! = $pad) return false; return substr ($text, 0,-1 * $pad);}}
Test code