C#中的常用加密算法及与其它语言的兼容性
|
源代码网整理以下 源代码网整理以下1:MD5 源代码网整理以下以前在asp时代常用的MD5算法好象是从动网流出来的,后来大家都用它,基本上有两种 ,区别在md5.asp的结尾部分 源代码网整理以下MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d)) 源代码网整理以下分别对应32位和16位加密方式 源代码网整理以下在C#中对应的实现为 源代码网整理以下/// <summary> /// <returns>加密后的字串</returns> public string MD5Encrypt(string strSource, int length) { byte[] bytes = Encoding.ASCII.GetBytes(strSource); byte[] hashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes); StringBuilder sb = new StringBuilder(); switch (length) { case 16: for (int i = 4; i < 12; i++) sb.Append(hashValue[i].ToString("x2")); break; case 32: for (int i = 0; i < 16; i++) { sb.Append(hashValue[i].ToString("x2")); } break; default: for (int i = 0; i < hashValue.Length; i++) { sb.Append(hashValue[i].ToString("x2")); } break; } 源代码网整理以下同样的其它语言都实现了DES加密与.net framework的des基础实现也不一样,比较郁闷的是我刚开始使用.net framework时还真的改写过perl版的des,后面才发现其实有更简单的办法,因为网上流传的perl/c/java版的des算法都是块加密的,设置CipherMode为ECB就好了,郁闷ing. 源代码网整理以下源代码如下 源代码网整理以下 public static byte[] DESKey = new byte[] {0x82, 0xBC, 0xA1, 0x6A, 0xF5, 0x87, 0x3B, 0xE6, 0x59, 0x6A, 0x32, 0x64, 0x7F, 0x3A, 0x2A, 0xBB, 0x2B, 0x68, 0xE2, 0x5F, 0x06, 0xFB, 0xB8, 0x2D, 0x67, 0xB3, 0x55, 0x19, 0x4E, 0xB8, 0xBF, 0xDD }; } public string DESDecrypt(string strSource,byte[] key) { SymmetricAlgorithm sa = Rijndael.Create(); sa.Key = key; sa.Mode = CipherMode.ECB; sa.Padding = PaddingMode.Zeros; ICryptoTransform ct = sa.CreateDecryptor(); byte[] byt = Convert.FromBase64String(strSource); MemoryStream ms = new MemoryStream(byt); CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read); 软件开发网 www.mscto.com StreamReader sr = new StreamReader(cs, Encoding.Unicode); return sr.ReadToEnd(); } 源代码网整理以下 源代码网推荐 源代码网供稿. |
