我想创建一个C#类来解密使用T-SQL的EncryptByPassPhrase加密的字节数组。 (是的,我知道我可以在SQL Server中解密,但我需要的是能够在数据库层和中间层中等效地加密/解密。)
据我所知,SQL Server的EncryptByPassPhrase和DecryptByPassPhrase使用TripleDES对称密钥算法。但是,我不清楚IV应该模拟SQL Server的密码学。我可以使用TripleDESCryptoServiceProvider类加密/解密,但我找不到正确的密钥和IV实现来复制SQL Server正在做的事情。
有没有人做过类似的事情?谢谢!
答案 0 :(得分:1)
github 上有一个公共存储库,可以在 C# 中重新创建 EncryptByPassPhrase
,并且随着实现的更改,IV 取决于 SQL Server 的版本。您可以查看代码的 repo。 https://github.com/krcs/SQLServerCrypto
答案 1 :(得分:-2)
(1)使用C#生成密钥/ iv对: TripleDESCryptoServiceProvider cp = new TripleDESCryptoServiceProvider();
MemoryStream m = new MemoryStream(Convert.FromBase64String(Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(plainText))));
CryptoStream cs = new CryptoStream(m, cp.CreateEncryptor(cp.Key, cp.IV), CryptoStreamMode.Read);
cp.Key = Convert.FromBase64String("BeaYzNeHfDb27OFYgaYHUd5HUJE2aZyI");
cp.IV = Convert.FromBase64String("T/ENF5G4sCA=");
string key = Convert.ToBase64String(cp.Key);
string iv = Convert.ToBase64String(cp.IV);
// write key/iv to a file here
(2)一旦我们有了这个,就用这样的代码来编码
TripleDESCryptoServiceProvider cp = new TripleDESCryptoServiceProvider();
MemoryStream m = new MemoryStream(Convert.FromBase64String(Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(plainText))));
CryptoStream cs = new CryptoStream(m, cp.CreateEncryptor(cp.Key, cp.IV), CryptoStreamMode.Read);
cp.Key = Convert.FromBase64String("the key value from above");
cp.IV = Convert.FromBase64String("the iv value from above");
string key = Convert.ToBase64String(cp.Key);
string iv = Convert.ToBase64String(cp.IV);
List<byte> r = new List<byte>();
int x = 0;
for (; x > -1; )
{
x = cs.ReadByte();
if (x > -1)
r.Add((byte)x);
}
byte[] y = r.ToArray();
string cypherText = Convert.ToBase64String(y);
(3)然后解码:
TripleDESCryptoServiceProvider cp = new TripleDESCryptoServiceProvider();
MemoryStream m = new MemoryStream(Convert.FromBase64String(cypherText));
cp.Key = Convert.FromBase64String("the key value from above");
cp.IV = Convert.FromBase64String("the iv value from above");
CryptoStream cs = new CryptoStream(m, cp.CreateDecryptor(cp.Key, cp.IV), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cs);
string plainText = reader.ReadToEnd();