2011-12-28 48 views
0

我想使用SQL Server中存储和生成的非对称密钥在客户端上执行一些加密。使用来自SQL Server的公钥的.Net中的RSA加密?

我可以使用下面的查询得到的DMV公钥:

SELECT public_key FROM sys.asymmetric_keys WHERE name = 'KeyName' 

这将返回以下值:

0x06020000002400005253413100020000010001008B656455D4C56392C45EEC3563203635F5F42DDA57069E7A880BF0AF055174A2A165DED75BA4E73E2A09BCBFAA50042B4E27354C1FEB3361F81C381AFF59A6A7

我如何使用这个二进制VAL ue作为.Net中RSA_512加密的公钥?我在这里搜索了similar questions,但未能找到任何合适的解决方案:我需要XML格式的密钥或至少知道公钥的.Modulus.Exponent。我可以从这些二进制序列中获得它吗?


编辑

这里是我的代码

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); 

我得到的异常 “键无效” 中的最后一行。

回答

1
Security.Cryptography.RSACryptoServiceProvider rsa=new Security.Cryptography.RSACryptoServiceProvider(512); 
rsa.ImportCspBlob(keyblob) 

其中keyblob是上述密钥的byte []表示。

这直接来自于我的外壳:

[email protected]:~$ csharp 
Mono C# Shell, type "help;" for help 

Enter statements below. 
csharp> using System.Security.Cryptography;                                       
csharp> String keystring="06020000002400005253413100020000010001008B656455D4C56392C45EEC3563203635F5F42DDA57069E7A880BF0AF055174A2A165DED75BA4E73E2A09BCBFAA50042B4E27354C1FEB3361F81C381AFF59A6A7"; 
csharp> byte[] keybytes=new byte[keystring.Length/2]; 
csharp> for (int i=0;i<keystring.Length/2;i++) keybytes[i]=Convert.ToByte(keystring.Substring(2*i,2),16); 
csharp> RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(512); 
csharp> rsa.ImportCspBlob(keybytes); 
csharp> byte[] cleartext=new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 
csharp> byte[] ciphertext=rsa.Encrypt(cleartext,false); 
csharp> ciphertext; 
{ 62, 80, 66, 63, 4, 132, 69, 249, 97, 164, 131, 34, 89, 117, 173, 177, 222, 77, 23, 177, 127, 236, 116, 121, 25, 63, 59, 159, 182, 235, 190, 44, 24, 101, 127, 61, 185, 72, 93, 69, 66, 248, 64, 249, 5, 183, 214, 189, 252, 75, 22, 123, 159, 50, 13, 90, 137, 187, 180, 181, 252, 174, 98, 247 } 
csharp> keybytes; 
{ 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 2, 0, 0, 1, 0, 1, 0, 139, 101, 100, 85, 212, 197, 99, 146, 196, 94, 236, 53, 99, 32, 54, 53, 245, 244, 45, 218, 87, 6, 158, 122, 136, 11, 240, 175, 5, 81, 116, 162, 161, 101, 222, 215, 91, 164, 231, 62, 42, 9, 188, 191, 170, 80, 4, 43, 78, 39, 53, 76, 31, 235, 51, 97, 248, 28, 56, 26, 255, 89, 166, 167 } 
csharp> 
+0

这是行不通的。 'ImportCspBlob()'不给出警告,但只要我尝试使用'rsa'对象的'Encrypt()'方法,就会得到“无效密钥”异常。有趣的是,总的keyt大小只有84字节长 - 是否正确? – 2011-12-29 18:31:10

+0

适用于您的问题中的价值...这是真正的价值吗? – 2011-12-29 19:07:55

+0

84字节是672位,看起来不错 – 2011-12-29 19:08:26