解密字符串时偶尔出现错误数据错误:System.Security.Cryptography.CryptographicException

发布于 2024-11-18 01:32:42 字数 11230 浏览 2 评论 0原文

在我的 ASP.NET WebForms 应用程序中(该应用程序运行在 Windows Server 2008 R2、IIS 7.5 和运行时 v4.0 集成模式应用程序池上),我加密数据,将其放在 QueryString 上并使用 System.Security.Cryptography.SymmetricAlgorithm 类解密数据。但我偶尔会在解密数据时遇到一些问题,出现以下异常;

错误数据。

描述:未处理的异常 执行期间发生的 当前的网络请求。请查看 堆栈跟踪以获取有关的更多信息 错误及其起源 代码。

异常详细信息: System.Security.Cryptography.CryptographicException: 错误数据。

来源错误:

生成了未处理的异常 当前执行期间 网络请求。有关信息 异常的起源和地点 可以使用异常来识别 下面的堆栈跟踪。

堆栈跟踪:

[CryptographicException:错误数据。 ]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 小时)+33
System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey、Byte[] 数据、Int32 ib、Int32 cb、 字节[]&输出缓冲区,Int32 输出偏移量,PaddingMode PaddingMode, 布尔值 fDone) +0
System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(字节[] 输入缓冲区,Int32 输入偏移,Int32 输入计数)+313
System.Security.Cryptography.CryptoStream.FlushFinalBlock() +33 Cryptography35.SymmetricEncryptionUtility.DecryptData(Byte[] 数据,字符串 keyFile) 中 E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricEncryptionUtility.cs:124 Cryptography35.SymmetricQueryString.SymmetriclyEncryptedQueryString..ctor(字符串 加密数据,字符串密钥文件名, 字符串算法名称) in E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricQueryString\SymmetriclyEncryptedQueryString.cs:67 WebForms.Web.Views.purchase_a.GetSymmetriclyEncryptedQueryString() 在 E:\Documents\WebForms.Web\Views\purchase-a.aspx.cs:35 WebForms.Web.Views.purchase_a.Page_Load(对象 发送者、EventArgs e) 中 E:\Documents\WebForms.Web\Views\purchase-a.aspx.cs:56 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp、对象 o、对象 t、EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(对象 发送者,EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74 System.Web.UI.Page.ProcessRequestMain(布尔值 includeStagesBeforeAsyncPoint,布尔值 includeStagesAfterAsyncPoint)+2207 版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.1

正如我所指出的,我偶尔会收到此错误,而不是每次运行时都会出现此错误。我不知道我在哪里做错了(在加密阶段或解密阶段)这是我用于此目的的代码;

private SymmetriclyEncryptedQueryString GetSymmetriclyEncryptedQueryString() {

    #region _decrypting the value

    string KeyFileName;
    string AlgorithmName = "DES";

    Cryptography35.SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
    KeyFileName = HttpContext.Current.Server.MapPath("~/@config/") + "\\symmetric_key.config";

    #endregion

    #region _reading and assigning the value

    if (Request.QueryString["q"] == null)
        throw new NullReferenceException("QueryString value is null on search result page");

    SymmetriclyEncryptedQueryString QueryString = new SymmetriclyEncryptedQueryString(Request.QueryString["q"], KeyFileName, AlgorithmName);

    #endregion

    return QueryString;
}

SymmetriclyEncryptedQueryString

public class SymmetriclyEncryptedQueryString : System.Collections.Specialized.StringDictionary {

        public string KeyFileName { get; set; }
        public string AlgorithmName { get; set; }

        /// <summary>
        /// Use this for encrypte the value
        /// </summary>
        /// <param name="keyfilename"></param>
        /// <param name="algorithmname"></param>
        public SymmetriclyEncryptedQueryString(string keyfilename, string algorithmname) {

            KeyFileName = keyfilename;
            AlgorithmName = algorithmname;

        }

        /// <summary>
        /// Use this for decrypte the value.
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="keyfilename"></param>
        /// <param name="algorithmname"></param>
        public SymmetriclyEncryptedQueryString(string encryptedData, string keyfilename, string algorithmname) {

            #region _initials

            KeyFileName = keyfilename;
            AlgorithmName = algorithmname;

            if (String.IsNullOrEmpty(AlgorithmName)){
                SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
            }
            else{
                SymmetricEncryptionUtility.AlgorithmName = "DES";
            }

            SymmetricEncryptionUtility.ProtectKey = false;

            // Check for encryption key
            if (!File.Exists(KeyFileName)){
                throw new FileNotFoundException("Keyfilename for  SymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
            }

            #endregion

            //Arrange the data
            //In order not to get following exception
            //Invalid length for a Base-64 char array.
            //byte[] RawData = Convert.FromBase64String(encryptedData);
            encryptedData = encryptedData.Replace(" ", "+");
            int mod4 = encryptedData.Length % 4;
            if (mod4 > 0)
                encryptedData += new string('=', 4 - mod4);

            // Decrypt data passed in
            byte[] RawData = Convert.FromBase64String(encryptedData);
            string DecryptedVal = SymmetricEncryptionUtility.DecryptData(RawData, KeyFileName);
            string StringData = DecryptedVal;

            // Split the data and add the contents
            int Index;
            string[] SplittedData = StringData.Split(new char[] { '&' });
            foreach (string SingleData in SplittedData) {

                Index = SingleData.IndexOf('=');
                base.Add(
                    HttpUtility.UrlDecode(SingleData.Substring(0, Index)),
                    HttpUtility.UrlDecode(SingleData.Substring(Index + 1))
                );

            }
        }

        public override string ToString() {

            #region _initials

            if (String.IsNullOrEmpty(AlgorithmName)) {
                SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
            } else {
                SymmetricEncryptionUtility.AlgorithmName = "DES";
            }

            SymmetricEncryptionUtility.ProtectKey = false;

            // Check for encryption key
            if (!File.Exists(KeyFileName)) {
                throw new FileNotFoundException("Keyfilename for AsymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
            }

            #endregion

            #region _prepare for querystring

            // Go through the contents and build a 
            // typical query string
            StringBuilder Content = new StringBuilder();

            foreach (string key in base.Keys) {

                Content.Append(HttpUtility.UrlEncode(key));
                Content.Append("=");
                Content.Append(HttpUtility.UrlEncode(base[key]));
                Content.Append("&");

            }

            // Remove the last '&'
            Content.Remove(Content.Length - 1, 1);


            #endregion

            #region _encrypt the contents

            // Now encrypt the contents
            byte[] data = SymmetricEncryptionUtility.EncryptData(Content.ToString(), KeyFileName);
            string EncryptedVal = Convert.ToBase64String(data);

            #endregion

            return EncryptedVal;

        }

    }

SymmetricEncryptionUtility

public static class SymmetricEncryptionUtility {

    private static bool _ProtectKey;
    private static string _AlgorithmName;

    // Shhh!!! Don't tell anybody!
    private const string MyKey = "m$%&kljasldk$%/65asjdl";

    public static string AlgorithmName {

        get { return _AlgorithmName; }
        set { _AlgorithmName = value; }
    }

    public static bool ProtectKey {

        get { return _ProtectKey; }
        set { _ProtectKey = value; }
    }

    public static void GenerateKey(string targetFile) {

        // Create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        Algorithm.GenerateKey();

        // No get the key
        byte[] Key = Algorithm.Key;

        if (ProtectKey)
        {
            // Use DPAPI to encrypt key
            Key = ProtectedData.Protect(
                Key, null, DataProtectionScope.LocalMachine);
        }

        // Store the key in a file called key.config
        using (FileStream fs = new FileStream(targetFile, FileMode.Create))
        {
            fs.Write(Key, 0, Key.Length);
        }
    }

    public static void ReadKey(SymmetricAlgorithm algorithm, string keyFile)
    {
        byte[] Key;

        using (FileStream fs = new FileStream(keyFile, FileMode.Open))
        {
            Key = new byte[fs.Length];
            fs.Read(Key, 0, (int)fs.Length);
        }

        if (ProtectKey)
            algorithm.Key = ProtectedData.Unprotect(Key, null, DataProtectionScope.LocalMachine);
        else
            algorithm.Key = Key;
    }

    public static byte[] EncryptData(string data, string keyFile)
    {
        // Convert string data to byte array
        byte[] ClearData = Encoding.UTF8.GetBytes(data);

        // Now Create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        ReadKey(Algorithm, keyFile);

        // Encrypt information
        MemoryStream Target = new MemoryStream();

        // Append IV
        Algorithm.GenerateIV();
        Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

        // Encrypt actual data
        CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(ClearData, 0, ClearData.Length);
        cs.FlushFinalBlock();

        // Output the bytes of the encrypted array to the textbox
        return Target.ToArray();
    }

    public static string DecryptData(byte[] data, string keyFile) {

        // Now create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        ReadKey(Algorithm, keyFile);

        // Decrypt information
        MemoryStream Target = new MemoryStream();

        // Read IV
        int ReadPos = 0;
        byte[] IV = new byte[Algorithm.IV.Length];
        Array.Copy(data, IV, IV.Length);
        Algorithm.IV = IV;
        ReadPos += Algorithm.IV.Length;

        CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(data, ReadPos, data.Length - ReadPos);
        cs.FlushFinalBlock();

        // Get the bytes from the memory stream and convert them to text
        return Encoding.UTF8.GetString(Target.ToArray());
    }

}

更新 我想到了别的事。在我的其中一页上,我正在做以下事情;

protected override void OnInit(EventArgs e) {

    string url = Request.Url.AbsoluteUri.ToLower();
    if (url.StartsWith("http:"))
    {
        Response.Redirect(url.Replace("http://", "https://"), true);
    }
}

我认为这导致了问题。 (请记住,我的加密数据位于查询字符串内)当我尝试从 http 访问该页面时,它会将其重定向到 https 并繁荣。它给了我那个错误。好吧,现在我找到了错误的根源,但无论如何它都不应该发生。

In my ASP.NET WebForms App (The app is running on windows server 2008 R2, IIS 7.5 and Runtime v4.0 Integrated Mode App Pool if it matters), I am encrypting data, putting it on the QueryString and decrypting data using System.Security.Cryptography.SymmetricAlgorithm class. But I am occasionally having some problems with decrypting the data I am getting the following exception;

Bad Data.

Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.

Exception Details:
System.Security.Cryptography.CryptographicException:
Bad Data.

Source Error:

An unhandled exception was generated
during the execution of the current
web request. Information regarding the
origin and location of the exception
can be identified using the exception
stack trace below.

Stack Trace:

[CryptographicException: Bad Data. ]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32
hr) +33
System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle
hKey, Byte[] data, Int32 ib, Int32 cb,
Byte[]& outputBuffer, Int32
outputOffset, PaddingMode PaddingMode,
Boolean fDone) +0
System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[]
inputBuffer, Int32 inputOffset, Int32
inputCount) +313
System.Security.Cryptography.CryptoStream.FlushFinalBlock()
+33 Cryptography35.SymmetricEncryptionUtility.DecryptData(Byte[]
data, String keyFile) in
E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricEncryptionUtility.cs:124
Cryptography35.SymmetricQueryString.SymmetriclyEncryptedQueryString..ctor(String
encryptedData, String keyfilename,
String algorithmname) in
E:\Documents\@Library\Cryptography35\Cryptography35\SymmetricQueryString\SymmetriclyEncryptedQueryString.cs:67
WebForms.Web.Views.purchase_a.GetSymmetriclyEncryptedQueryString()
in
E:\Documents\WebForms.Web\Views\purchase-a.aspx.cs:35
WebForms.Web.Views.purchase_a.Page_Load(Object
sender, EventArgs e) in
E:\Documents\WebForms.Web\Views\purchase-a.aspx.cs:56
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
fp, Object o, Object t, EventArgs e)
+14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs
e) +91
System.Web.UI.Control.LoadRecursive()
+74 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.1

As I indicated, I am getting this error on occasion, not every time I run that. I don't know where I am doing it wrong (on the encryption stage or decryption stage) Here is the code I used for that;

private SymmetriclyEncryptedQueryString GetSymmetriclyEncryptedQueryString() {

    #region _decrypting the value

    string KeyFileName;
    string AlgorithmName = "DES";

    Cryptography35.SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
    KeyFileName = HttpContext.Current.Server.MapPath("~/@config/") + "\\symmetric_key.config";

    #endregion

    #region _reading and assigning the value

    if (Request.QueryString["q"] == null)
        throw new NullReferenceException("QueryString value is null on search result page");

    SymmetriclyEncryptedQueryString QueryString = new SymmetriclyEncryptedQueryString(Request.QueryString["q"], KeyFileName, AlgorithmName);

    #endregion

    return QueryString;
}

SymmetriclyEncryptedQueryString Class

public class SymmetriclyEncryptedQueryString : System.Collections.Specialized.StringDictionary {

        public string KeyFileName { get; set; }
        public string AlgorithmName { get; set; }

        /// <summary>
        /// Use this for encrypte the value
        /// </summary>
        /// <param name="keyfilename"></param>
        /// <param name="algorithmname"></param>
        public SymmetriclyEncryptedQueryString(string keyfilename, string algorithmname) {

            KeyFileName = keyfilename;
            AlgorithmName = algorithmname;

        }

        /// <summary>
        /// Use this for decrypte the value.
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="keyfilename"></param>
        /// <param name="algorithmname"></param>
        public SymmetriclyEncryptedQueryString(string encryptedData, string keyfilename, string algorithmname) {

            #region _initials

            KeyFileName = keyfilename;
            AlgorithmName = algorithmname;

            if (String.IsNullOrEmpty(AlgorithmName)){
                SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
            }
            else{
                SymmetricEncryptionUtility.AlgorithmName = "DES";
            }

            SymmetricEncryptionUtility.ProtectKey = false;

            // Check for encryption key
            if (!File.Exists(KeyFileName)){
                throw new FileNotFoundException("Keyfilename for  SymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
            }

            #endregion

            //Arrange the data
            //In order not to get following exception
            //Invalid length for a Base-64 char array.
            //byte[] RawData = Convert.FromBase64String(encryptedData);
            encryptedData = encryptedData.Replace(" ", "+");
            int mod4 = encryptedData.Length % 4;
            if (mod4 > 0)
                encryptedData += new string('=', 4 - mod4);

            // Decrypt data passed in
            byte[] RawData = Convert.FromBase64String(encryptedData);
            string DecryptedVal = SymmetricEncryptionUtility.DecryptData(RawData, KeyFileName);
            string StringData = DecryptedVal;

            // Split the data and add the contents
            int Index;
            string[] SplittedData = StringData.Split(new char[] { '&' });
            foreach (string SingleData in SplittedData) {

                Index = SingleData.IndexOf('=');
                base.Add(
                    HttpUtility.UrlDecode(SingleData.Substring(0, Index)),
                    HttpUtility.UrlDecode(SingleData.Substring(Index + 1))
                );

            }
        }

        public override string ToString() {

            #region _initials

            if (String.IsNullOrEmpty(AlgorithmName)) {
                SymmetricEncryptionUtility.AlgorithmName = AlgorithmName;
            } else {
                SymmetricEncryptionUtility.AlgorithmName = "DES";
            }

            SymmetricEncryptionUtility.ProtectKey = false;

            // Check for encryption key
            if (!File.Exists(KeyFileName)) {
                throw new FileNotFoundException("Keyfilename for AsymmetriclyEncryptedQueryString is not found on '" + KeyFileName + "'!");
            }

            #endregion

            #region _prepare for querystring

            // Go through the contents and build a 
            // typical query string
            StringBuilder Content = new StringBuilder();

            foreach (string key in base.Keys) {

                Content.Append(HttpUtility.UrlEncode(key));
                Content.Append("=");
                Content.Append(HttpUtility.UrlEncode(base[key]));
                Content.Append("&");

            }

            // Remove the last '&'
            Content.Remove(Content.Length - 1, 1);


            #endregion

            #region _encrypt the contents

            // Now encrypt the contents
            byte[] data = SymmetricEncryptionUtility.EncryptData(Content.ToString(), KeyFileName);
            string EncryptedVal = Convert.ToBase64String(data);

            #endregion

            return EncryptedVal;

        }

    }

SymmetricEncryptionUtility Class

public static class SymmetricEncryptionUtility {

    private static bool _ProtectKey;
    private static string _AlgorithmName;

    // Shhh!!! Don't tell anybody!
    private const string MyKey = "m$%&kljasldk$%/65asjdl";

    public static string AlgorithmName {

        get { return _AlgorithmName; }
        set { _AlgorithmName = value; }
    }

    public static bool ProtectKey {

        get { return _ProtectKey; }
        set { _ProtectKey = value; }
    }

    public static void GenerateKey(string targetFile) {

        // Create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        Algorithm.GenerateKey();

        // No get the key
        byte[] Key = Algorithm.Key;

        if (ProtectKey)
        {
            // Use DPAPI to encrypt key
            Key = ProtectedData.Protect(
                Key, null, DataProtectionScope.LocalMachine);
        }

        // Store the key in a file called key.config
        using (FileStream fs = new FileStream(targetFile, FileMode.Create))
        {
            fs.Write(Key, 0, Key.Length);
        }
    }

    public static void ReadKey(SymmetricAlgorithm algorithm, string keyFile)
    {
        byte[] Key;

        using (FileStream fs = new FileStream(keyFile, FileMode.Open))
        {
            Key = new byte[fs.Length];
            fs.Read(Key, 0, (int)fs.Length);
        }

        if (ProtectKey)
            algorithm.Key = ProtectedData.Unprotect(Key, null, DataProtectionScope.LocalMachine);
        else
            algorithm.Key = Key;
    }

    public static byte[] EncryptData(string data, string keyFile)
    {
        // Convert string data to byte array
        byte[] ClearData = Encoding.UTF8.GetBytes(data);

        // Now Create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        ReadKey(Algorithm, keyFile);

        // Encrypt information
        MemoryStream Target = new MemoryStream();

        // Append IV
        Algorithm.GenerateIV();
        Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

        // Encrypt actual data
        CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(ClearData, 0, ClearData.Length);
        cs.FlushFinalBlock();

        // Output the bytes of the encrypted array to the textbox
        return Target.ToArray();
    }

    public static string DecryptData(byte[] data, string keyFile) {

        // Now create the algorithm
        SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
        ReadKey(Algorithm, keyFile);

        // Decrypt information
        MemoryStream Target = new MemoryStream();

        // Read IV
        int ReadPos = 0;
        byte[] IV = new byte[Algorithm.IV.Length];
        Array.Copy(data, IV, IV.Length);
        Algorithm.IV = IV;
        ReadPos += Algorithm.IV.Length;

        CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(data, ReadPos, data.Length - ReadPos);
        cs.FlushFinalBlock();

        // Get the bytes from the memory stream and convert them to text
        return Encoding.UTF8.GetString(Target.ToArray());
    }

}

UPDATE
I figured something else. On one of my pages I am doing the following thing;

protected override void OnInit(EventArgs e) {

    string url = Request.Url.AbsoluteUri.ToLower();
    if (url.StartsWith("http:"))
    {
        Response.Redirect(url.Replace("http://", "https://"), true);
    }
}

I figured that it causes the problem. (Remember that my encrypted data sits inside the Query String) when I try to reach that page from http and it redirects it to https and boom. it gives me that error. ok now I found the source of the error but it shouldn't be happening anyway.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小兔几 2024-11-25 01:32:42

您的代码中潜伏着一个错误...

您永远不应该将任何 System.Text.Encoding 类用于密文。您将会遇到间歇性错误。您应该使用 Base64 编码和 System.Convert 类方法。

  1. 要从加密的 byte[] 获取加密的字符串,应使用: Convert.ToBase64String(byte[] bytes)

  2. 要从要加密的字符串中获取原始 byte[],您应该使用: Convert.FromBase64String(string data)

有关详细信息,请参阅 MS安全专家 Shawn Farkas 的帖子 http://blogs.msdn.com/b/shawnfa/archive/2005/11/10/491431.aspx

You have a bug lurking in your code...

You should never use any of the System.Text.Encoding classes for cipher text. You will experience intermittent errors. You should use Base64 encoding and the System.Convert class methods.

  1. To obtain an encrypted string from an encrypted byte[], you should use: Convert.ToBase64String(byte[] bytes)

  2. To obtain a a raw byte[] from a string to be encrypted, you should use: Convert.FromBase64String(string data)

For additional info, please refer to MS Security guru Shawn Farkas's post at http://blogs.msdn.com/b/shawnfa/archive/2005/11/10/491431.aspx

傾城如夢未必闌珊 2024-11-25 01:32:42

对于“错误数据”错误,我有一个不同的根本原因,这与没有“FlushFinalBlock”代码有关。这显然引起了一个问题,因为我从未存储过完全加密的值。
现在,在上面的代码示例中,包含了 ,但显然它被隐藏在代码中。我希望这不是太偏离主题,但我确实很快从谷歌找到了这篇文章,所以我认为其他人可能也会来这里并犯同样的简单错误。

还值得一提的是,@Dave Black 的答案似乎与上面发布的最终代码无关......?我正确地阅读了上面的代码吗?
这可能是随着时间的推移而发生变化的结果 - 但这让我在尝试找出问题所在时稍微误入歧途(我已经正确存储了我的加密数据,只是不是全部:-( )

I had a different root cause, for "Bad Data" error, and that was related to not having the "FlushFinalBlock" code. This obviously caused a problem as I never stored the fully encrypted value.
Now in the code example above that is included, but obvioulsy it is buried in the code. I hope this is not too off topic, but I did find this post from Google fairly quickly so I assume others might come here and make that same simple mistake as well.

It might also be worth mentioning that the @Dave Black answer does not appear to relate to the final code posted above... ? Have I read the code above correctly?
This might be a result of the changes over time - but this lead me slightly astray in trying to sort out what had gone wrong (I had stored my encrypted data correctly, just not all of it :-( )

焚却相思 2024-11-25 01:32:42

设置加解密模式为ECB。
正如 rossum 所说:“ECB 不安全,它会泄露信息”,因此如果您需要随机访问文件,请使用 CTR。

Set encryption and decryption mode to ECB.
As rossum say: "ECB is not secure, it leaks information" so if you need random access to your file Use CTR.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文