C#使用DES加解密数据

     C#的DES加解密,同时支持.NET与.NET CF 2.0平台,这样就可以把一个封装好的类同时用在PC/WM手机上。C#的DES比其他语言的DES算法多了个IV实现,其实IV可以设置为随意的8位byte即可,注意要加入desc.Mode = CipherMode.ECB 兼容其他语言的Des加密算法。


        直接贴出代码,下面部分代码比较普通,高手们切勿见笑!

 

using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Globalization; using System.IO; class Cls_Cryptography { /// <summary> /// IV随便设置为8位 /// </summary> private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// 加密字符串 /// </summary> /// <returns>返回密文</returns> public static String EncryptString(String key, String str) { byte[] data = Encoding.Default.GetBytes(str); byte[] result = EncryptData(key, data); if (result != null) return Convert.ToBase64String(result, 0, result.Length); else return ""; } /// <summary> /// 加密二进制数据 /// </summary> /// <returns>返回二进制密文</returns> public static byte[] EncryptData(String key, byte[] data) { byte[] bKey = Encoding.Default.GetBytes(key.Substring(0, 8)); byte[] bIV = IV; try { DESCryptoServiceProvider desc = new DESCryptoServiceProvider(); desc.Mode = CipherMode.ECB;//兼容其他语言的Des加密算法 desc.Padding = PaddingMode.Zeros;//自动补0 MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, desc.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write); cStream.Write(data, 0, data.Length); cStream.FlushFinalBlock(); return mStream.ToArray(); } catch { return null; } } /// <summary> /// 把密文解密为明文 /// </summary> /// <returns>返回明文</returns> public static String DecryptString(String key, String decryptStr) { byte[] data = Convert.FromBase64String(decryptStr); byte[] result = DecryptData(key, data); if (result != null) return Encoding.Default.GetString(result, 0, result.Length); else return ""; } /// <summary> /// 把二进制密文解密为明文二进制 /// </summary> /// <returns>返回明文二进制</returns> public static byte[] DecryptData(String key, byte[] data) { try { byte[] bKey = Encoding.Default.GetBytes(key.Substring(0, 8)); byte[] bIV = IV; DESCryptoServiceProvider desc = new DESCryptoServiceProvider(); desc.Mode = CipherMode.ECB;//兼容其他语言的Des加密算法 desc.Padding = PaddingMode.Zeros;//自动补0 MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, desc.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write); cStream.Write(data, 0, data.Length); cStream.FlushFinalBlock(); return mStream.ToArray(); } catch { return null; } } } 

 

至于怎么调用。。。很简单的说

 

String str = Cls_Cryptography.EncryptString("12345678", "12345678"); MessageBox.Show(str); str = Cls_Cryptography.DecryptString("12345678", str); MessageBox.Show(str);

你可能感兴趣的:(加密,String,解密,C#,byte,Cryptography)