Replicate T-SQL DecryptByPassPhrase in C#

2019-02-12 17:35发布

I wnat to create a C# class to decrypt a byte array encrypted using T-SQL's EncryptByPassPhrase. (Yes, I know I could decrypt within SQL Server, but what I need is to be able to encrypt/decrypt within both the database tier and in the middle tier equivalently.)

I understand that SQL Server's EncryptByPassPhrase and DecryptByPassPhrase use the TripleDES symmetric key algorithm. It's not clear to me, though, what the IV should to simulate SQL Server's cryptology. I can encrypt/decrypt using the TripleDESCryptoServiceProvider class, but I can't find the correct implementation of key and IV to replicate what SQL Server is doing.

Has anyone done something similar? Thanks!

1条回答
劳资没心,怎么记你
2楼-- · 2019-02-12 18:41

(1) Use C# to generate a key/iv pair: 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) Once we have that, use code like this to encode

            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) Then to decode:

            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();
查看更多
登录 后发表回答