title: length of data to decrypt is invalid rijndael c# sql
body: <p>I am trying to encrypt / decrypt sensitive data such as SSN, the encryption process goes fine, saving in DB looks good too, retrieval looks good too, but when I am on the last step to decrypt the data I am getting error message: length of data to decrypt is invalid.</p>
  
  <p>I created a SQL Server table for testing which has one column to hold the data, of <code>varbinary</code> type with size of 500. </p>
  
  <p>This is how the data looks like in the table:</p>
  
  <p><img src="https://i.stack.imgur.com/X1fe6.png" alt="enter image description here"></p>
  
  <p>Now here is whole code in C# which is used to encrypt the data, insert in the db, get the last record (test) and decrypt. As I said the error happens on the last step in the decryption step:</p>
  
  <p>Encryption Step</p>
  
  <pre><code> public byte[] EncryptStringToBytes(string plainText)
   {
               // Check arguments. 
               if (plainText == null || plainText.Length &lt;= 0)
                   throw new ArgumentNullException("plainText");           
               byte[] encrypted;
               // Create an RijndaelManaged object 
               // with the specified key and IV. 
               using (RijndaelManaged rijAlg = new RijndaelManaged())
               {
                   rijAlg.Mode = CipherMode.CBC;
                   rijAlg.Padding = PaddingMode.PKCS7;
                   string keyStr = "cGFzc3dvcmQAAAAAAAAAAA==";
                   string ivStr = "cGFzc3dvcmQAAAAAAAAAAA==";
                   byte[] ivArr = Convert.FromBase64String(keyStr);
                   byte[] keyArr = Convert.FromBase64String(ivStr);
                   rijAlg.Key = keyArr;
                   rijAlg.KeySize = 256;
                   rijAlg.BlockSize = 128;
                   rijAlg.IV = ivArr;
  
                   // Create a decrytor to perform the stream transform.
                   ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
  
                   // Create the streams used for encryption. 
                   using (MemoryStream msEncrypt = new MemoryStream())
                   {
                       using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                       {
                           using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                           {
                               //Write all data to the stream.
                               swEncrypt.Write(plainText);
                           }
                           encrypted = msEncrypt.ToArray();
                           SaveData(encrypted);
                       }
                   }
              }
               // Return the encrypted bytes from the memory stream. 
               return encrypted;
           }
  </code></pre>
  
  <p>Saving data to database</p>
  
  <pre><code>public void SaveData(byte[] cipherText) {
     string queryStmt = "INSERT INTO TestSSN(SSN) VALUES(@Content)";
  
     using (SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
     using (SqlCommand _cmd = new SqlCommand(queryStmt, _con))
     {
        SqlParameter param = _cmd.Parameters.Add("@Content", SqlDbType.VarBinary);
        param.Value = cipherText;
  
        _con.Open();
        _cmd.ExecuteNonQuery();
        _con.Close();
     }
     GetSSNData(1); }
  </code></pre>
  
  <p>Getting data from database</p>
  
  <pre><code>public byte[] GetSSNData(int id)
  {
      byte[] cipherData = new byte[500];
      string queryStmt = "SELECT SSN FROM TestSSN WHERE ID=7";
  
      using (SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
      using (SqlCommand _cmd = new SqlCommand(queryStmt, _con))
      {              
            _con.Open();
            SqlDataReader rdr = _cmd.ExecuteReader();
  
            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                      cipherData = Encoding.ASCII.GetBytes(rdr[0].ToString());
                }
            }
            _con.Close();
      }
      string roundtrip = DecryptStringFromBytes(cipherData);          
      return cipherData;
  }
  </code></pre>
  
  <p>Trying to decrypt the data(you will notice two different ways for decryption here, but I'll get the same message for both of them)</p>
  
  <pre><code> static string DecryptStringFromBytes(byte[] cipherText)
   {
       // Check arguments. 
       if (cipherText == null || cipherText.Length &lt;= 0)
           throw new ArgumentNullException("cipherText");           
  
       // Declare the string used to hold 
       // the decrypted text. 
       string plaintext = null;
  
       // Create an RijndaelManaged object 
       // with the specified key and IV. 
       using (RijndaelManaged rijAlg = new RijndaelManaged())
       {
           rijAlg.Mode = CipherMode.CBC;
           rijAlg.Padding = PaddingMode.PKCS7;
           string keyStr = "cGFzc3dvcmQAAAAAAAAAAA==";
           string ivStr = "cGFzc3dvcmQAAAAAAAAAAA==";
           byte[] ivArr = Convert.FromBase64String(keyStr);
           byte[] keyArr = Convert.FromBase64String(ivStr);
           rijAlg.Key = keyArr;
           rijAlg.KeySize = 256;
           rijAlg.BlockSize = 128;
           rijAlg.IV = ivArr;
           // Create a decrytor to perform the stream transform.
           ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
  
           byte[] decryptedText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
           string decrpyted = ASCIIEncoding.UTF8.GetString(decryptedText);          
  
           // Create the streams used for decryption. 
           using (MemoryStream msDecrypt = new MemoryStream(cipherText))
           {
               using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
               {
                   using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                   {
                       //  byte[] decryptedText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
                       // Read the decrypted bytes from the decrypting stream 
                       // and place them in a string.
                       plaintext = srDecrypt.ReadToEnd();
                   }
               }
           }
       }
  
       return plaintext;
     }
  </code></pre>
  
  <p>Advices more then welcome, I've been battling with the decryption whole day.</p>
  
  <p>Thanks, Laziale</p>