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.
I am using the following to get the keypair:
private static AsymmetricCipherKeyPair createASymRandomCipher()
{
RsaKeyPairGenerator r = new RsaKeyPairGenerator();
r.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
return keys;
}
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.
This is what I am currently using the encrypt the data (incorrectly?):
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;
}
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.
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?
Any help would be greatly appreciated.
Regarding the second part of your question, the data type that should be used for storing the key would be VARBINARY(256).
Back to the first part of your question, you actually have the option of having SQL Server handle the encryption for you. Granted, whether or not you would want to do this would be a matter of what your application requirements are, but I'll go over it in case it's an option.
We'll be pretty basic here and just use symmetric keys and Triple-DES.
First, the database has a master key which is used to protect certificates and asymmetric keys. The master key is encrypted with Triple-DES.
SQL Server 2005/2008 can generate their own X.509 certificates used to protect the keys used to encrypt the actual data.
There are a lot of options for encrypting symmetric keys (certificates, passwords, other keys), as well as many supported algorithms. But for this example, we'll use our certificate.
The key needs to be decrypted using the same method with which it was encrypted. In our case, this would be the certificate we created.
Decryption is just as straightforward.
Hopefully this solved your problem, or at least opened you up to alternative solutions (though someone who's had experience doing encryption in C# apps could probably find the fault in your above code). If you have requirements that necessitate that the data can't even go over the wire to the SQL Server in plain-text, obviously this is a no-go (well, you can actually create SSL connections to SQL Server...).
The correct approach is to use Peters' suggestion.
I have included a small C# code sample below :
The sample uses the Bouncy Castle API. Note that the sample does NOT encrypt the key. The
CreatePrivateKeyInfo
method is overloaded to allow the use of a password as protection of the key.As long as the object is marked as serializable, one way to convert an object to a byte array is to use the BinaryFormatter class in .Net.
You will need to add this using statement to your code file:
A binary formatter can output your class to a stream. As you intend to convert your object to a byte array, you can use a System.IO.MemoryStream as temporary storage.
You can then create a new binary formatter.
and use this to serialize your object.
To get the bytes you can use:
To deserialize the byte array you need to write the bytes to a memory stream.
Return to the beginning of the stream.
Then use the formatter to recreate the object.
If you are already using encryption functions you should be able to encrypt the created byte array quite easily before storing it in the database.
Hopefully that will help you in the right direction. If you are lucky, the BouncyCastle objects will be marked as serializable, if not you will need some extra code. Later, I will get a chance to look at the BouncyCastle librarys to be able to test this and will post more code if necessary.
... I have never used BouncyCastle before. After some testing, it appears that the public and private key objects are not serializable, so you will need to convert these objects into something that is!
It appears that the public and private keys expose properties as various BouncyCastle.Math.BigInteger values. (The keys can also be constructed from these BigIntegers). Further, BigIntegers have a ToByteArray() function and can also be constructed from a byte array. Very useful..
Knowing that you can break each key into BigIntegers and these in turn to a byte array and that the reverse is also possible, you a way to store all these in a serializable object. A simple struct or class would do e.g.
This gives us a pair of easy to use serializable objects.
The AsymmetricCipherKeyPair exposes the Public and Private keys as AsymmetricKeyParameter objects. To get at the more detailed properties you will need to cast these to the following:
keyPair.Public to BouncyCastle.Crypto.Parameters.RsaKeyParameters keyPair.Private to BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters
The following functions will convert these to the structs to declared earlier:
Using the binary formatter mentioned earlier, we can convert the serializable objects we have just created to a byte array.
Desierializing is then just the inverse as described earlier. Once you have either the public or private structs deserialized you can use the BouncyCastle contructors to recreate the keys. These functions demonstrate this.
If you need to recreate the original key pair for any reason:
Hopefully that all makes sense! The code samples should help you on your way.
For reasons that should be clear, default (and perhaps inadvertent) serialization does not play well with private keys which should only be written out in very limited situations.
BouncyCastle has support for PKCS#8, which is the relevant standard for "serializing" private keys. There are ASN.1 structures called PrivateKeyInfo and EncryptedPrivateKeyInfo. Since they are in ASN.1 there are standard ways to serialize/deserialize them. As the name suggests, one stores the key in plaintext, the other encrypts the key based on a password.
For the public keys - these would not ordinarily be encrypted. BC supports the X.509 standard format of SubjectPublicKeyInfo for serializing them.
In the C# build, the high-level classes to look at would be: