I would like to perform some encryption on client using the asymmetric key stored and generated in SQL Server.
I can get the public key from the DMV using the following query:
SELECT public_key FROM sys.asymmetric_keys WHERE name = 'KeyName'
This returns the following value:
0x06020000002400005253413100020000010001008B656455D4C56392C45EEC3563203635F5F42DDA57069E7A880BF0AF055174A2A165DED75BA4E73E2A09BCBFAA50042B4E27354C1FEB3361F81C381AFF59A6A7
How can I use this binary value as public key for RSA_512 encryption in .Net? I have searched through similar questions here but failed to find any appropriate solution: I either need the key in XML form or at least to know .Modulus and .Exponent of the public key. Can I get it from these binary sequence?
EDIT:
Here is my code
SqlCommand cmd = new SqlCommand(string.Format("SELECT dbo.GetKey(@KeyName)", conn);
cmd.Parameters.AddWithValue("@KeyName", ConfigurationManager.AppSettings.Get("PublicKeyName"));
PublicKey = (byte[]) cmd.ExecuteScalar();
var rsa=new System.Security.Cryptography.RSACryptoServiceProvider(Convert.ToInt32(ConfigurationManager.AppSettings.Get("KeyLength")));
rsa.ImportCspBlob(PublicKey);
EncryptedData = rsa.Encrypt(Data,false);
I get the exception “Key not valid” in the last line.
with keyblob being a byte[] representation of the above key.
This comes directly from my shell: