我参考了这篇文章http://www.codeproject.com/KB/security/DotNetCrypto.aspx,我正在尝试编写加密字符串而不是纯文本。以下是我正在使用的代码:
TextWriter tw = new StreamWriter("c:\\temp\\test.txt");
string plainString = "String to be encrypted";
PasswordDeriveBytes pdb = new PasswordDeriveBytes("Test",new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
tw.WriteLine(alg.IV.ToString());
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,alg.CreateEncryptor(), CryptoStreamMode.Write);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainString);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
tw.WriteLine(ms.ToString());
ms.Close();
tw.Flush();
但是,当我打开文件时,我会获得 System.IO.MemoryStream
而不是某些加密字符。我错过了什么?
答案 0 :(得分:0)
MemoryStream.ToString()依赖于Object.ToString()的默认实现,它写出了类名。创建一个FileStream并将其传递给CryptoStream ctor。
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx
答案 1 :(得分:0)
我认为.net支持使用MD5算法加密字符串。如果要使用MD5,请参阅以下代码。
private void encrypt(ref string password)
{
Int32 counter;
Char[] passwordArr;
String encryptedPassword;
Byte[] hashedPassword;
MD5CryptoServiceProvider obj = new MD5CryptoServiceProvider();
passwordArr = password.ToCharArray();
Byte[] passwordBytes = new byte[passwordArr.Length - 1];
for (counter = 0; counter < passwordBytes.Length; counter++)
{
passwordBytes[counter] = Convert.ToByte(passwordArr[counter]);
}
hashedPassword = obj.ComputeHash(passwordBytes);
encryptedPassword = BitConverter.ToString(hashedPassword);
password = encryptedPassword;
obj = null;
}
答案 2 :(得分:0)
问题在于ms.ToString()。你应该从内存流中读取字节,将其更改为适当的编码,然后写入文本流。