浏览 6668 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-04-01
http://www.caocao.name/,http://www.caocao.mobi/
作者:caocao(网络隐士),转载请注明来源:http://www.iteye.com/topic/178321 有个项目要跨PHP平台和.NET平台进行数据交换,数据还必须是DES加密的,在折腾了一阵后隐士终于摸清楚代码该如何写,加密数据才能够通用于两个平台。 PHP加密方式 写道 $key="********"; $iv="********"; $message="kjsdfuihyweflgjerogjreg"; echo base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $message, MCRYPT_MODE_CBC, $iv)); C#加密解密方式 写道 /// <summary> /// DES加密方法,keyBytes和ivBytes必须为64bit即8位的 /// </summary> /// <param name="inBytes">待加密数组</param> /// <param name="keyBytes">key数组</param> /// <param name="ivBytes">iv数组</param> /// <returns>加密完的数组</returns> public static byte[] DESEncryptWithCBCZeros(byte[] inBytes, byte[] keyBytes, byte[] ivBytes) { using (MemoryStream memoryStream = new MemoryStream()) { DES desCBC = DES.Create(); desCBC.Mode = CipherMode.CBC; desCBC.Padding = PaddingMode.Zeros; using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desCBC.CreateEncryptor(keyBytes, ivBytes), CryptoStreamMode.Write)) { cryptoStream.Write(inBytes, 0, inBytes.Length); cryptoStream.FlushFinalBlock(); byte[] bytes = memoryStream.ToArray(); return bytes; } } } /// <summary> /// DES解密方法,keyBytes和ivBytes必须为64bit即8位的 /// </summary> /// <param name="inBytes">待解密数组</param> /// <param name="keyBytes">key数组</param> /// <param name="ivBytes">iv数组</param> /// <returns>解密完的数组</returns> public static byte[] DESDecryptWithCBCZeros(byte[] inBytes, byte[] keyBytes, byte[] ivBytes) { using (MemoryStream memoryStream = new MemoryStream(inBytes)) { DES desCBC = DES.Create(); desCBC.Mode = CipherMode.CBC; desCBC.Padding = PaddingMode.Zeros; using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desCBC.CreateDecryptor(keyBytes, ivBytes), CryptoStreamMode.Read)) { byte[] outEncrypt = new byte[inBytes.Length]; cryptoStream.Read(outEncrypt, 0, outEncrypt.Length); return outEncrypt; } } } C#调用方式 写道 try { byte[] inBytes = Encoding.UTF8.GetBytes("kldfgwehfo23905hfkjvbsdcsdc"); byte[] keyBytes = Encoding.ASCII.GetBytes("********"); byte[] ivBytes = Encoding.ASCII.GetBytes("********"); byte[] outBytes = StringEncryptHelper.DESEncryptWithCBCZeros(inBytes, keyBytes, ivBytes); Console.WriteLine(Convert.ToBase64String(outBytes)); Console.WriteLine(Encoding.UTF8.GetString(StringEncryptHelper.DESDecryptWithCBCZeros(outBytes, keyBytes, ivBytes))); } catch (CryptographicException e) { Console.WriteLine(e.StackTrace); Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-02-28
直接用SSL,.net和java都完美支持,加密/解密过程完全透明,而且安全性最高。
|
|
返回顶楼 | |