C#的DES加密及解密
2014-11-22 00:00
351 查看
using System; using System.Text; using System.Security.Cryptography; using System.IO; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { byte[] key, iv; createKey(out key, out iv); string str = "tosone"; byte[] b = EncryptStringToBytes(str, key, iv); Console.WriteLine("密钥:" + Convert.ToBase64String(key)); Console.WriteLine("密钥向量:" + Convert.ToBase64String(iv)); Console.WriteLine(); Console.WriteLine("待加密字符串:" + str); Console.WriteLine("加密后字符串:" + Convert.ToBase64String(b)); Console.WriteLine("解密后字符串:" + DecryptStringFromBytes(b, key, iv)); Console.Read(); } private static void createKey(out byte[] key, out byte[] iv) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); key = des.Key; iv = des.IV; } static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) { if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("Key"); byte[] encrypted; using (DESCryptoServiceProvider dsAlg = new DESCryptoServiceProvider()) { dsAlg.Key = Key; dsAlg.IV = IV; ICryptoTransform encryptor = dsAlg.CreateEncryptor(dsAlg.Key, dsAlg.IV); 3ff0 using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } return encrypted; } static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) { if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("Key"); string plaintext = null; using (DESCryptoServiceProvider dsAlg = new DESCryptoServiceProvider()) { dsAlg.Key = Key; dsAlg.IV = IV; ICryptoTransform decryptor = dsAlg.CreateDecryptor(dsAlg.Key, dsAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; } } }
相关文章推荐
- C#的des加密解密
- C#实现Des加密和解密
- C#DES加密和解密
- php实现和c#一致的DES加密解密
- C#中DES加密解密
- 用C#实现DES加密解密
- c#实现DES加密与解密
- C# DES加密和解密
- C# Java DES加密解密
- C#中DES加密解密
- 用C#进行MD5、SHA、DES加密解密
- C#实现md5加密 sha1加密 sha256加密 sha384加密 sha512加密 des加密解密
- c# DES加密与解密代码
- 在AS3 DES加密,在C# DES解密
- C#用DES加密JAVA用DES解密,JAVA用DES加密C#用DES解密的实现
- c#中DES加密解密的类
- C# DES加密、解密
- 使用C# DES解密java DES加密的字符串
- C#使用DES加密解密DataSet!
- C#用DES加密JAVA用DES解密,JAVA用DES加密C#用DES解密的实现