2014-02-10 139 views
3

正在關注Replicate T-SQL DecryptByPassPhrase in C#,我無法使用MSSQL進行簡單的加密以在C#中進行加密。某些列中的加密值是必要的,因爲該表格定期導出到Excel和Access中,所以簡單的加密就足以「阻止」值而不需要開發人員參與(重新)執行視圖等。C#解密來自SQL Server EncryptByPassPhrase的字節?

在SQL Server 2012:

select EncryptByPassPhrase(N'hello' , N'world' ) 
-- returns 0x01000000AA959FFB3A8E4B06B734051437E198C8B72000A058ACE91D617123DA102287EB 

在C#:

byte[] buf = System.Text.Encoding.UTF8.GetBytes("0x010000003A95FA870ED699A5F90D33C2BF01491D9132F61BA162998E96F37117AF5DA0905D51EB6FB298EC88"); 
// bytes emitted from the database 
var cp = new TripleDESCryptoServiceProvider(); 
var m = new MemoryStream(buf); 
cp.Key = System.Text.Encoding.UTF8.GetBytes("hello"); // throws 
cp.IV = System.Text.Encoding.UTF8.GetBytes("hello"); // throws 
CryptoStream cs = new CryptoStream(m , cp.CreateDecryptor(cp.Key , cp.IV) , CryptoStreamMode.Read); 
StreamReader reader = new StreamReader(cs); 
string plainText = reader.ReadToEnd(); 

應該怎樣工作的C#代碼是什麼樣子?

謝謝。

+0

你看着辦吧? –

回答

1

我相信你所遵循的鏈接是建議一種新的方式來加密和解密模仿SQL EncryptByPassPhrase的方式。因此,如果您使用C#加密,則只能在C#中使用解密。

因爲,你已經在SQL中使用了EncryptByPassPhrase,所以我建議在傳遞給C#代碼之前在SQL中使用DecryptByPassPhrase。您的hello world加密和

例解密:

Declare @lEncryptedText VARBINARY(256) = (select ENCRYPTBYPASSPHRASE('hello','world')) 
SELECT @lEncryptedText --Encrypted VALUE for world 

SELECT CONVERT(VARCHAR(100),DECRYPTBYPASSPHRASE('hello',@lEncryptedText)) --Decrypted Value