title: Encrypting a BouncyCastle RSA Key Pair and storing in a SQL2008 database
body: <p>I have a function that generates a BouncyCastle RSA key pair. I need to encrypt the private key and then store the encrypted private and public keys into separate SQL2008 database fields.</p>
  
  <p>I am using the following to get the keypair:</p>
  
  <pre><code>private static AsymmetricCipherKeyPair createASymRandomCipher()
  {
      RsaKeyPairGenerator r = new RsaKeyPairGenerator();
      r.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
      AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
      return keys; 
  }
  </code></pre>
  
  <p>This is returning the keys fine, but I am not sure how I can then encrypt the private key and subsequently store it in the database. </p>
  
  <p>This is what I am currently using the encrypt the data (incorrectly?):</p>
  
  <pre><code>public static byte[] encBytes2(AsymmetricKeyParameter keyParam, byte[] Key, byte[] IV)
  {
      MemoryStream ms = new MemoryStream();
      Rijndael rjdAlg = Rijndael.Create();
      rjdAlg.Key = Key;
      rjdAlg.IV = IV;
      CryptoStream cs = new CryptoStream(ms, rjdAlg.CreateEncryptor(), CryptoStreamMode.Write);
      byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(keyParam.ToString());
      cs.Write(keyBytes, 0, keyBytes.Length);
      cs.Close();
      byte[] encryptedData = ms.ToArray();
      return encryptedData;
  }
  </code></pre>
  
  <p>Obviously the keyBytes setting where I am converting keyParam.ToString() is not correct as it only converts the KeyParameter name, not the actual value. I am submitting to this function the previous key pair return of keys.Private.</p>
  
  <p>The other question is as I am not encrypting the Public Key what format should I be storing this in the SQL2008 database, nvarchar(256) or other?</p>
  
  <p>Any help would be greatly appreciated.</p>