您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php des 加密解密实例

2024/11/11 12:16:57发布26次查看
des加密是对称加密中在互联网应用的比较多的一种加密方式,php 通过mcrypt扩展库来支持des加密,要在php中使用des加密,需要先安装mcrypt扩展库
下面是加密解密的实例
$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)); } }
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product