2

我参考了这篇文章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的不是一些加密字符。我错过了什么?

4

3 回答 3

0

MemoryStream.ToString() 依赖于 Object.ToString() 的默认实现,它会写出类名。创建一个 FileStream 并将其传递给 CryptoStream ctor。

http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx

于 2010-12-22T04:32:09.203 回答
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;
    }
于 2010-12-22T04:41:23.497 回答
0

well the issue is with the ms.ToString(). your should rather be reading the bytes from memorystream, changing it to appropriate encoding and then writing to the text stream.

于 2010-12-22T04:41:39.577 回答