码迷,mamicode.com
首页 > Web开发 > 详细

php 加密解密方法

时间:2015-01-07 16:28:19      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

<?php
//可用于加密解密,如cookie,账号,手机号 as so on class DES { var $key; var $iv; //偏移量 function __construct( $key, $iv=0 ) { //key长度8例如:1234abcd $this->key = $key; if( $iv == 0 ) { $this->iv = $key; //默认以$key 作为 iv } else { $this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM ); } } function encrypt($str) { //加密,返回大写十六进制字符串 $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->iv ) ) ); } function decrypt($str) { //解密 $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 ); } } // 实例化,并传入两个参数,都为8位,即 KEY, VI的值 $des = new DES(‘abcd1234‘, ‘87654321‘); //加密结果 $aa 为 7A3C7BBA8B42ADC4 $str = ‘123456‘; $aa = $des->encrypt($str); echo $aa; // 解密结果 $bb 为 123456 $bb = $des->decrypt($aa); echo $bb; ?>

  

php 加密解密方法

标签:

原文地址:http://www.cnblogs.com/lin3615/p/4208647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!