using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace SqlResetPwd
{
class Program
{
static void Main(string[] args)
{
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Escape)
{
break;
}
else
{
Console.Write("IN FileName:"); string inFileName = Console.ReadLine();
Console.Write("OUT FileName:"); string outFileName = Console.ReadLine();
Console.Write("PassWord:"); string password = Console.ReadLine();
Console.Write("Choice 0:Encrypt other:Dcrypt:"); string Choice = Console.ReadLine();
// Create the password key
byte[] saltValueBytes = Encoding.ASCII.GetBytes("This is my sa1t");
Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(password, saltValueBytes);
// Create the algorithm and specify the key and IV
RijndaelManaged alg = new RijndaelManaged();
alg.Key = passwordKey.GetBytes(alg.KeySize / 8);
alg.IV = passwordKey.GetBytes(alg.BlockSize / 8);
if (Choice == "0")
{
encrypt
}
else
{
dencrypt
}
}
}
}
}
}
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace SqlResetPwd
{
class Program
{
static void Main(string[] args)
{
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Escape)
{
break;
}
else
{
Console.Write("IN FileName:"); string inFileName = Console.ReadLine();
Console.Write("OUT FileName:"); string outFileName = Console.ReadLine();
Console.Write("PassWord:"); string password = Console.ReadLine();
Console.Write("Choice 0:Encrypt other:Dcrypt:"); string Choice = Console.ReadLine();
// Create the password key
byte[] saltValueBytes = Encoding.ASCII.GetBytes("This is my sa1t");
Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(password, saltValueBytes);
// Create the algorithm and specify the key and IV
RijndaelManaged alg = new RijndaelManaged();
alg.Key = passwordKey.GetBytes(alg.KeySize / 8);
alg.IV = passwordKey.GetBytes(alg.BlockSize / 8);
if (Choice == "0")
{
encrypt
}
else
{
dencrypt
}
}
}
}
}
}
从中不难看出对称加密解密的步骤:
选择要采用的加解密算法的类
创建相应的KEY,IV
创建要读出或写入的文件流
利用SymmetricAlgorithm.CreateEncryptor() CreateDecryptor()方法创建ICryptoTransform对象
利用ICryptoTransform对象和创建的文件流创建CryptoStream对象
写入或读出加解密的文件流