Question

I referred to this article http://www.codeproject.com/KB/security/DotNetCrypto.aspx and I am trying write an encrypted string instead of plain text. Below is the code I am using:

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();

However, when I open the file, I get System.IO.MemoryStream instead of some encrypted characters. What did I miss?

Was it helpful?

Solution

I think .net supports very well to encrypt string using MD5 algorithm. If you want to use MD5 see the following code.

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;
    }

OTHER TIPS

MemoryStream.ToString() relies on the default implementation of Object.ToString(), which writes out the classname. Create a FileStream and pass that to the CryptoStream ctor.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top