你應該使用System.IO.CryptoStream,微軟的流裝飾讀/寫加密的數據流。簡單!
要閱讀加密文本,這樣的事情就足夠了:
static IEnumerable<string> ReadEncryptedTextFile(string path , byte[] key , byte[] iv , Encoding encoding)
{
string value ;
using (Stream s = File.OpenRead(path))
using (SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create())
using (ICryptoTransform transform = algorithm.CreateDecryptor(key , iv))
using (CryptoStream cs = new CryptoStream(s , transform , CryptoStreamMode.Read))
using (TextReader sr = new StreamReader(cs,encoding))
{
string line ;
while (null != (line = sr.ReadLine()))
{
yield return line ;
}
}
}
要寫入加密的文本,這樣的事情:
static void WriteEncryptedTextFile (IEnumerable<string> lines , string path , byte[] key , byte[] iv , Encoding encoding)
{
using (Stream s = File.OpenWrite(path))
using (SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create())
using (ICryptoTransform transform = algorithm.CreateEncryptor(key , iv))
using (CryptoStream cs = new CryptoStream(s , transform , CryptoStreamMode.Write))
using (TextWriter tw = new StreamWriter(cs , encoding))
{
foreach (string line in lines)
{
tw.WriteLine(line) ;
}
}
return ;
}
你可能想在你使用特定的算法來撥(並且每個算法都有關於key
和iv
大小的要求)。
這個問題沒有意義 –
@SamIam - 我同意。屁笑話是有趣的。 – Brian
-1:沒有描述實際問題的嘗試。 –