下面是加密解密的实例
$iv_size = mcrypt_get_iv_size(mcrypt_rijndael_256, mcrypt_mode_ecb); $iv = mcrypt_create_iv($iv_size, mcrypt_rand); $key = this is a very secret key;//密钥 $text = meet me at 11 o'clock behind the monument.;//需要加密的内容 echo ($text) . \n; $crypttext =base64_encode(mcrypt_encrypt(mcrypt_rijndael_256, $key, $text, mcrypt_mode_ecb, $iv)); echo $crypttext . \n;//加密后的内容 echo mcrypt_decrypt(mcrypt_rijndael_256,$key,base64_decode($crypttext),mcrypt_mode_ecb,$iv);//解密后的内容
在aes加密算法中通常会用到mcrypt_rijndael_128、mcrypt_rijndael_192、mcrypt_rijndael_256三种,后面的128、192、256代表的是秘钥(也就是加密的key)是多少bit的,比如使用的是mcrypt_rijndael_128,那么用这个算法加密时秘钥长度就是128bit的,比如 $key = 'fjjda0&9^$$#+*%$fada',是20个字符,那在实际加密的时候只用到前16个字符加密(16*8=128),不足128bit的php中会用'\0'来补齐。
有的时候做项目对接的时候,可能你用的是php加密的,而对方用的是java写的,对接的过程中就发现机加密后的内容对方解密不了,这是因为php跟java在实现这个算法的时候有差别,要想正确加密解密需要两边都做下处理:
php
'; echo security::decrypt($value, $key );
import javax.crypto.cipher; import javax.crypto.spec.secretkeyspec; import org.apache.commons.codec.binary.base64; public class security { public static string encrypt(string input, string key){ byte[] crypted = null; try{ secretkeyspec skey = new secretkeyspec(key.getbytes(), aes); cipher cipher = cipher.getinstance(aes/ecb/pkcs5padding); cipher.init(cipher.encrypt_mode, skey); crypted = cipher.dofinal(input.getbytes()); }catch(exception e){ system.out.println(e.tostring()); } return new string(base64.encodebase64(crypted)); } public static string decrypt(string input, string key){ byte[] output = null; try{ secretkeyspec skey = new secretkeyspec(key.getbytes(), aes); cipher cipher = cipher.getinstance(aes/ecb/pkcs5padding); cipher.init(cipher.decrypt_mode, skey); output = cipher.dofinal(base64.decodebase64(input)); }catch(exception e){ system.out.println(e.tostring()); } return new string(output); } public static void main(string[] args) { string key = 1234567891234567; string data = example; system.out.println(security.encrypt(data, key)); system.out.println(security.decrypt(security.encrypt(data, key), key)); } }