title: How to store a RijndaelManaged generated KEY and IV in the database for later use?
body: <p>Let me start by saying....yes I have read tons of posts on here in the last two days. No, I don't know anything about encryption, so don't bother...with the you shouldn't playing with fire comments..</p>
  
  <p>I have a asp.net MVC3 application and want to encrypt the photos that users upload using a key for each user.  I want to save this key and use it for any further uploads by the same user and for the decryption. (Although, I suppose I could store a key for each photo instead, not really relevant to this problem but...)</p>
  
  <p>I started with the code from here:
  <a href="http://www.codeproject.com/Articles/33344/Photo-Video-Viewer-with-Encryption-Capability" rel="nofollow">http://www.codeproject.com/Articles/33344/Photo-Video-Viewer-with-Encryption-Capability</a></p>
  
  <p>It works fine. It encrypts the photos and decrypts them to a new file and all is well.  The "on the fly version" also works and returns a MemoryStream that I can use for my WebImage.  However, as you can see the example is encrypting and decrypting in one pass and the key is a global variable (I don't know what it was, I just used the autogenerated key when I tested.  </p>
  
  <p>So, I need someone to tell me how to store the generated key (and IV I guess???  Told you I know nothing about enc...) in the database for each user and then pull that (those) value(s) back out to use for on the fly decryption. I am not going to bother to post all my code yet, as it is almost identical to what is on the above site.     </p>
  
  <p>I read another post on here and it said to use:</p>
  
  <pre><code>string x = Convert.ToBase64String(RMCrypto.Key);
  </code></pre>
  
  <p>Then when I wanted to decrypt I used:</p>
  
  <pre><code>RMCrypto.Key = Convert.FromBase64String(x);
  </code></pre>
  
  <p>I stored both the key and IV in this manner in my SQL DB, but when I pull the values and try to decrypt I get an error that the data is not the expected length. </p>
  
  <p>Maybe I'm totally off base or maybe it's three lines of code... Please let me know if more information is needed.</p>
  
  <p>Thanks!</p>