You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中如何读取数据库加密值并与当前日期进行比较

问题修复方案

现有问题梳理

  1. 解密密钥和加密密钥不一致:解密方法的EncryptionKey前多了一个空格,导致生成的AES密钥和IV完全不匹配,解密直接失败
  2. 解密方法存在语法错误:cs.Write方法调用缺少右括号,代码无法正常编译运行
  3. 日期比较逻辑不严谨:直接通过字符串对比日期,受系统区域格式、大小写、冗余字符影响很大,容易出现逻辑判断错误
  4. 语法拼写错误:原代码中Datetime、小写的toString都不符合C#语法规范

修复后的代码

1. Decrypt.cshtml.cs 解密方法修复

public string Decrypt(string cipherText)
{
    // 去掉密钥前的多余空格,和加密方法密钥完全保持一致
    string EncryptionKey = "Bt2a";
    cipherText = cipherText.Replace(" ", "+");
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x01, 0x22, 0xcc, 0x0e, 0x50, 0x4d, 0x05, 0xa4, 0x4f, 0xff, 0xe3, 0x69, 0x7a });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using MemoryStream ms = new MemoryStream();
        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
        {
            // 补全方法调用的右括号
            cs.Write(cipherBytes, 0, cipherBytes.Length);
            cs.Close();
        }
        cipherText = Encoding.Unicode.GetString(ms.ToArray());
    }
    return cipherText;
}

2. 加密调用优化(可选,规避格式问题)

建议加密日期时指定固定格式,避免不同环境的格式差异:

// 加密时用固定日期格式,后续解密解析格式保持一致即可
string encryptedDate = Encrypt(DateTime.Today.AddDays(8).ToString("yyyy-MM-dd"));

3. Decrypt.cshtml 页面比较逻辑修复

改用日期类型直接对比,避免字符串对比的不可靠问题:

@if (DateTime.TryParse(Model.Decrypt(Model.Date.DateEnc), out DateTime decryptedDate) 
    && decryptedDate.Date == DateTime.Today.Date)
{
    <p>Correct</p>
}
else
{
    <p>Wrong</p>
}

内容的提问来源于stack exchange,提问作者blackwolf511

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:30:03