Storing AES encrypted files in SQL Server and retrieving these files to decrypt them
-
Hi folks, Ive been working on a little app that lets u choose a file from your PC and encrypts it using AES encryption(Rijndael). The encrypted bytes are stored in Sql Server. I wanted to be able to retrieve the encrypted bytes so I can decrypt them. The process works fine. However when i open the decrypted file I have a ton of gibberish looking characters appended file but the decrypted text is fine. For example, this is what the decrypted text looks like. testing today Õ/þ°A¦ðI.Dº99ï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> øï_qýÆ;ßfÞàV¥u> ...... it continues on for a while. Can my goals even be achieved with this method? I have heard there are issues with doing this due to how SQLServer stores binary and padding issues with AES. Here is the code. public string EncryptFileData(string filename) { FileStream fsIn = new FileStream(filename, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; int bytesRead = fsIn.Read(buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Padding = PaddingMode.None; PasswordDeriveBytes pdb = new PasswordDeriveBytes(@"test", new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); try { CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(buffer, 0, buffer.Length); cs.Close(); byte[] encData = ms.ToArray(); SqlConnection conn = new SqlConnection(Settings1.Default.Properties["str"].DefaultValue.ToString()); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spStoreFileContent"; cmd.Parameters.AddWithValue("@FileName", @"c:\test\test.aop"); cmd.Parameters.AddWithValue("@EFileContent", encData); cmd.ExecuteNonQuery(); conn.Close(); return "Cool Beans"; } catch (SystemException sx)