usingSystem;
usingSystem.Security.Cryptography;
usingSystem.IO;
usingSystem.Text;
namespaceSqlResetPwd
{
classProgram
{
staticvoidMain(string[]args)
{
while(true)
{
ConsoleKeyInfoi=Console.ReadKey(true);
if(i.Key==ConsoleKey.Escape)
{
break;
}
else
{
Console.Write("INFileName:");stringinFileName=Console.ReadLine();
Console.Write("OUTFileName:");stringoutFileName=Console.ReadLine();
Console.Write("PassWord:");stringpassword=Console.ReadLine();
Console.Write("Choice0:Encryptother:Dcrypt:");stringChoice=Console.ReadLine();
//Createthepasswordkey
byte[]saltValueBytes=Encoding.ASCII.GetBytes("Thisismysa1t");
Rfc2898DeriveBytespasswordKey=newRfc2898DeriveBytes(password,saltValueBytes);
//CreatethealgorithmandspecifythekeyandIV
RijndaelManagedalg=newRijndaelManaged();
alg.Key=passwordKey.GetBytes(alg.KeySize/8);
alg.IV=passwordKey.GetBytes(alg.BlockSize/8);
if(Choice=="0")
{
encrypt#regionencrypt
//Createthepasswordkey
try
{
//ReadtheunencryptedfileintofileData
FileStreaminFile=newFileStream(inFileName,FileMode.Open,FileAccess.Read);
byte[]fileData=newbyte[inFile.Length];
inFile.Read(fileData,0,(int)inFile.Length);
//CreatetheICryptoTransformandCryptoStreamobject
ICryptoTransformencryptor=alg.CreateEncryptor();
FileStreamoutFile=newFileStream(outFileName,FileMode.OpenOrCreate,FileAccess.Write);
CryptoStreamencryptStream=newCryptoStream(outFile,encryptor,CryptoStreamMode.Write);
//WritethecontentstotheCryptoStream
encryptStream.Write(fileData,0,fileData.Length);
//Closethefilehandles
encryptStream.Close();
inFile.Close();
outFile.Close();
}
catch(Exceptionex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
#endregion
}
else
{
dencrypt#regiondencrypt
try
{
//ReadtheencryptedfileintofileData
ICryptoTransformdecryptor=alg.CreateDecryptor();
FileStreaminFile=newFileStream(inFileName,FileMode.Open,FileAccess.Read);
CryptoStreamdecryptStream=newCryptoStream(inFile,decryptor,CryptoStreamMode.Read);
byte[]fileData=newbyte[inFile.Length];
decryptStream.Read(fileData,0,(int)inFile.Length);
//Writethecontentsoftheunencryptedfile
FileStreamoutFile=newFileStream(outFileName,FileMode.OpenOrCreate,FileAccess.Write);
outFile.Write(fileData,0,fileData.Length);
//Closethefilehandles
decryptStream.Close();
inFile.Close();
outFile.Close();
}
catch(Exceptionex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
#endregion
}
}
}
}
}
}
从中不难看出对称加密解密的步骤:
选择要采用的加解密算法的类
创建相应的KEY,IV
创建要读出或写入的文件流
利用SymmetricAlgorithm.CreateEncryptor() CreateDecryptor()方法创建ICryptoTransform对象
利用ICryptoTransform对象和创建的文件流创建CryptoStream对象
写入或读出加解密的文件流
优质内容筛选与推荐>>
1、写测试用例心得2、博客园客户端UAP开发随笔 -- App的心动杀手锏:动画3、远程通信的几种选择(RPC,Webservice,RMI,JMS的区别)4、[转]wordpress安装插件的3种方式5、使用Redis实现分布式锁