您的位置:首页 > 编程语言 > C#

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: