小编典典

在C#中复制T-SQL DecryptByPassPhrase

sql

我创建了一个C#类来解密使用T-SQL的EncryptByPassPhrase加密的字节数组。(是的,我知道我可以在SQL
Server中解密,但是我需要的是能够在数据库层和中间层中等效地进行加密/解密。)

我了解SQLServer的EncryptByPassPhrase和DecryptByPassPhrase使用TripleDES对称密钥算法。但是,对于我来说不清楚IV应该如何模拟SQLServer的密码学。我可以使用TripleDESCryptoServiceProvider类进行加密/解密,但找不到正确的密钥和IV实现来复制SQLServer正在执行的操作。

有人做过类似的事情吗?谢谢!


阅读 218

收藏
2021-03-23

共1个答案

小编典典

(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();
2021-03-23