3DES : Receive Different Byte Array of encoding String from Registry
<p>Tool : Visual Studio 2012. Windows 7 64bit.
Keywords : C#,registry,Triple DES Encryption Decryption. </p>

<p>I have created one demo program to read and write (Encrypted string) to registry.</p>

<p>Concept behind this program is : I want to Encrypt and Decrypt Data using Triple DES(I have Used <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider(v=vs.110).aspx" rel="nofollow noreferrer">TripleDESCryptoServiceProvider Class</a>.).After Encryption, encrypted byte array is stored in Registry as a string. Upto this, it work perfectly. <strong>But when I get this string from registry and convert it in byte array for decryption, the size of array is different</strong> and during encryption it display error : </p>

<blockquote>
  <p>Length of the data to decrypt is invalid.</p>
</blockquote>

<p>Below is my code : </p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace TripleDES_in_Memory
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey("MyCompanyName\\"))
                {
                    if (key != null)
                    {
                        object o = key.GetValue("TrialPeriod");
                        if (o != null)
                        {
                            string result = Convert.ToString(o);
                            byte[] Data = Encoding.UTF8.GetBytes(result);


                            BinaryFormatter bf = new BinaryFormatter();
                            using (var ms = new MemoryStream())
                            {
                                bf.Serialize(ms, o);
                               byte[] narray = ms.ToArray();
                            }

                            TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
                            string keybyjaimesh = "MyEncryptKey";
                            tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));

                            string ipmanual = "ivmanual";
                            tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
                            byte[] iv = tDESalg.IV;

                            tDESalg.IV = iv;
                            string Final = DecryptTextFromMemory(Data, tDESalg.Key, tDESalg.IV); //decrypt
                            Console.WriteLine(Final);
                        }
                    }
                    else
                    {
                        TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();

                        string sData = "aaaaaaaaaaaaaaaaaaaaaaaa";
                        DateTime today = DateTime.Today;
                        DateTime answer = today.AddDays(1);

                        string keybyjaimesh = "MyEncryptKey";

                        tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));

                        string ipmanual = "ivmanual";
                        tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
                        byte[] iv = tDESalg.IV;

                        byte[] Data = EncryptTextToMemory(sData, tDESalg.Key, tDESalg.IV);
                        Console.WriteLine("Encrypted data main function :  " + System.Text.Encoding.UTF8.GetString(Data));


                        Microsoft.Win32.RegistryKey key1;
                        key1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("MyCompanyName");
                        key1.SetValue("TrialPeriod", System.Text.Encoding.UTF8.GetString(Data));
                        key1.SetValue("IV", System.Text.Encoding.UTF8.GetString(iv));
                        key1.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
        {
            try
            {
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write);

                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
                string result = System.Text.Encoding.UTF8.GetString(toEncrypt);
                Console.WriteLine("byte to array : " + result);

                cStream.Write(toEncrypt, 0, toEncrypt.Length);
                cStream.FlushFinalBlock();

                byte[] ret = mStream.ToArray();
                Console.WriteLine("Encrypted data :  " + System.Text.Encoding.UTF8.GetString(ret));

                cStream.Close();
                mStream.Close();

                return ret;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }

        public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
        {
            try
            {
                MemoryStream msDecrypt = new MemoryStream(Data);

                CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                    new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
                    CryptoStreamMode.Read);

                byte[] fromEncrypt = new byte[Data.Length];

                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

                return new ASCIIEncoding().GetString(fromEncrypt);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }

    }
}
</code></pre>

<p>Encrypted String in registry : <a href="https://i.stack.imgur.com/iwc55.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iwc55.png" alt="enter image description here"></a></p>

<p>Please suggest your opinion on this.</p>

<p>How can I solve this?</p>