Search code examples
c#.netencryptionencryption-symmetric

Issue with .NET encryption


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?


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