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#region encrypt
// Create the password key
try
{
// Read the unencrypted file into fileData
FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
byte[] fileData = new byte[inFile.Length];
inFile.Read(fileData, 0, (int)inFile.Length);
// Create the ICryptoTransform and CryptoStream object
ICryptoTransform encryptor = alg.CreateEncryptor();
FileStream outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
CryptoStream encryptStream = new CryptoStream(outFile, encryptor, CryptoStreamMode.Write);
// Write the contents to the CryptoStream
encryptStream.Write(fileData, 0, fileData.Length);
// Close the file handles
encryptStream.Close();
inFile.Close();
outFile.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
#endregion
}
else
{
dencrypt#region dencrypt
try
{
// Read the encrypted file into fileData
ICryptoTransform decryptor = alg.CreateDecryptor();
FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
CryptoStream decryptStream = new CryptoStream(inFile, decryptor, CryptoStreamMode.Read);
byte[] fileData = new byte[inFile.Length];
decryptStream.Read(fileData, 0, (int)inFile.Length);
// Write the contents of the unencrypted file
FileStream outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
outFile.Write(fileData, 0, fileData.Length);
// Close the file handles
decryptStream.Close();
inFile.Close();
outFile.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
#endregion
}
}
}
}
}
}
从中不难看出对称加密解密的步骤:
选择要采用的加解密算法的类
创建相应的KEY,IV
创建要读出或写入的文件流
利用SymmetricAlgorithm.CreateEncryptor() CreateDecryptor()方法创建ICryptoTransform对象
利用ICryptoTransform对象和创建的文件流创建CryptoStream对象
写入或读出加解密的文件流