PHP和.NET通用的加密解密函数类,均使用3DES加解密 .
以下为php代码
<PRE class=PHP name="code"> </PRE><PRE class=PHP name="code">PHP加解密函数:</PRE><PRE class=PHP name="code"> </PRE><PRE class=PHP name="code"> function encrypt($string) { //加密用的密钥文件 $key = "xxxxxxxx"; //加密方法 $cipher_alg = MCRYPT_TRIPLEDES; //初始化向量来增加安全性 $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,MCRYPT_MODE_ECB), MCRYPT_RAND); //开始加密 $encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_ECB, $iv); return base64_encode($encrypted_string);//转化成16进制 // return $encrypted_string; } function decrypt($string) { $string = base64_decode($string); //加密用的密钥文件 $key = "xxxxxxxx"; //加密方法 $cipher_alg = MCRYPT_TRIPLEDES; //初始化向量来增加安全性 $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,MCRYPT_MODE_ECB), MCRYPT_RAND); //开始解密 $decrypted_string = mcrypt_decrypt($cipher_alg, $key, $string, MCRYPT_MODE_ECB, $iv); return trim($decrypted_string); }</PRE>
以下为.net代码
using System; using System.Security.Cryptography; using System.Text; /**//// <SUMMARY> /// Crypto3DES 的摘要说明。 /// </SUMMARY> public class Crypto3DES { public Crypto3DES() { // // TODO: 在此处添加构造函数逻辑 // } private System.Text.Encoding encoding; /**//// <SUMMARY> /// 获取密匙 /// </SUMMARY> public string Key { get { return "xxxxxxxx"; } } /**//// <SUMMARY> /// 获取或设置加密解密的编码 /// </SUMMARY> public System.Text.Encoding Encoding { get { if( encoding == null ) { encoding = System.Text.Encoding.UTF8; } return encoding; } set { encoding = value; } } /**//// <SUMMARY> /// 加密 /// </SUMMARY> /// <PARAM name="strString"></PARAM> /// <PARAM name="strKey"></PARAM> /// <PARAM name="encoding"></PARAM> /// <RETURNS></RETURNS> public string Encrypt3DES( string strString ) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = Encoding.GetBytes( this.Key ); DES.Mode = CipherMode.ECB; DES.Padding = PaddingMode.Zeros; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = encoding.GetBytes(strString); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } /**//// <SUMMARY> /// 解密 /// </SUMMARY> /// <PARAM name="strString"></PARAM> /// <PARAM name="strKey"></PARAM> /// <RETURNS></RETURNS> public string Decrypt3DES( string strString ) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider (); DES.Key = Encoding.UTF8.GetBytes( this.Key ); DES.Mode = CipherMode.ECB; DES.Padding = PaddingMode.Zeros; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); byte[] Buffer = Convert.FromBase64String(strString); return UTF8Encoding.UTF8.GetString( DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length) ); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。