在C#中复制T-SQL DecryptByPassPhrase

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

据我所知,SQL Server的EncryptByPassPhrase和DecryptByPassPhrase使用TripleDES对称密钥算法.但是,我不清楚IV应该模拟SQL Server的密码学.我可以使用TripleDESCryptoServiceProvider类加密/解密,但我无法找到正确的密钥和IV实现来复制SQL Server正在做的事情.

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

最佳答案
(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();

转载注明原文:在C#中复制T-SQL DecryptByPassPhrase - 代码日志