0

其他链接对我没有用。我在保存到 mysql 数据库之前加密字符串。这工作正常。但是当我想检索时,它给我的数据长度加密是无效错误。在我的加密要求之前,我使用的是 varchar 大小为 500 的数据类型。现在我使用的是大小为 800 的 varbinary。任何人也可以就大小给我建议吗?

加密方式:

public static byte[] encryptStringToBytes(string plainText)
    {
        byte[] encrypted;
        //create an Rijndael object
        using (Rijndael rijAlg = Rijndael.Create())
        {
            //create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

            //create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        return encrypted;
    }

解密方法:

        public static string decryptStringFromBytes(byte[] cipherText)
    {
        string plaintext = null;

        //create an Rijndael object
        using (Rijndael rijAlg = Rijndael.Create())
        {
            //create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            //create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        //read the decrypted bytes from the decrypting stream and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }
        return plaintext;
    }

从结果集中检索

                    using (Rijndael myRijndael = Rijndael.Create())
                {
                    temp5 = EncryptDecrypt.decryptStringFromBytes((byte[])reader.GetValue(reader.GetOrdinal("Body")));
                }
4

1 回答 1

0

您没有以任何方式控制密钥和 IV。这是一个问题...... :) 它导致您的加密是数据的随机加扰,因为密钥和 IV 是由框架随机初始化的。

使用与加密相同的密钥和 IV 进行解密。为什么你认为数据库与问题有关?它没有,也没有证据证明这一点。

于 2013-02-24T19:32:58.740 回答