解密工作和加密不

Hil*_*boy 0 c# sql asp.net encryption cryptography

我已经将一个旧项目(废话,0文档)从asp.net 1.1转换为4.5,它工作正常.但是现在我们必须更改与我们交互的项目的连接字符串,以便它指向我们新的sql数据库.我们需要加密新的sqlconnection字符串,但有关于此的0文档以及它们如何加密字符串

我设法让解密者工作:

public static string DecryptConnectionString(string value)
        {
            string cryptoKey = "xxxxxxxx";
            Byte[] IV = { xxx, x, xx, xx, x, xx,xxx,xx};
            Byte[] byt;
            byt = Convert.FromBase64String(value);

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            des.Key = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
            des.IV = IV;

            return Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(byt, 0, byt.Length));

        }
Run Code Online (Sandbox Code Playgroud)

但我的加密器不工作它给我一个伪造的随机字符串(如俱乐部),当我插回到解密器时它崩溃了

到目前为止,这是我的加密工作:

 public static string EncryptConnectionString(string value)
        {
            char[] v =value.ToCharArray();
            string cryptoKey = "xxxxxxxxx";
            Byte[] IV = { xxx, x, xx, xx, x, xx,xxx,xx};
            Byte[] byt;
             byt = Encoding.ASCII.GetBytes(value);



            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            des.Key = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
            des.IV = IV;


            return Encoding.ASCII.GetString(des.CreateEncryptor().TransformFinalBlock(byt, 0, byt.Length));
        }
Run Code Online (Sandbox Code Playgroud)

提前致谢

Jon*_*eet 5

这是有问题的:

return Encoding.ASCII.GetString(...);
Run Code Online (Sandbox Code Playgroud)

加密的结果是任意二进制数据.不要尝试将其转换成这样的一个字符串-你几乎总是会丢失数据.

相反,要么只是将加密数据作为a返回byte[],要么使用像Base64这样的东西以可逆的方式将其转换为文本:

return Convert.ToBase64String(...);
Run Code Online (Sandbox Code Playgroud)

实际上,在您的解密代码中,您似乎已经假设它是Base64:

byt = Convert.FromBase64String(value);
Run Code Online (Sandbox Code Playgroud)

...所以你甚至不需要更改解密代码.

(顺便说一句,我对使用MD5创建这样的密钥非常怀疑 - 但这是另一回事.哦,目前你无法处理任何非ASCII文本(改为使用UTF-8)而你打电话ToCharArray没有明显的原因.)

有关此类事情的更多详细信息,请参阅我关于可逆数据转换的博客文章,以及如果您将来遇到类似问题,如何逐步分离该过程.