在平时的工作中,在写一此接口时,需要对敏感的数据进行加密以增加数据的安全性。常用的开源算法如AES算法、DES算法等,其中AES是美国国家标准技术研究所NIST旨在取代DES的21世纪的加密标准,AES具有比DES更好的安全性、效率、灵活性。关于AES算法详见:http://baike.baidu.com/link?url=3qIHlffXlREYlENAzkeC_qpgFQlczN0RP4VfXwFHcyijZpiko1TO7qBLN9GQj0Ol_smwxYsN4BteE-4pKXekHKn5p2murOta2Ei23Z_RfVe
如下为AES算法的PHP实现方法:
class Aes { private $iv; private $key; public function __construct($iv, $key) { $this->iv = $iv; $this->key = $key; } public function encrypt($data) { $data = $this->pkcs5Pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB)); $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $data, MCRYPT_MODE_ECB, $this->iv); return base64_encode($data); } public function decrypt($data) { $data = base64_decode($data); $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $data, MCRYPT_MODE_ECB,$this->iv); return $this->strippadding($data); } private function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen($text)%$blocksize); return $text.str_repeat(chr($pad), $pad); } //去除填充 private function strippadding($string) { $slast = ord(substr($string, -1)); $slastc = chr($slast); if (preg_match("/$slastc{" . $slast . "}/", $string)) { $string = substr($string, 0, strlen($string) - $slast); return $string; } else { return false; } } }