【问题标题】:Encrypted String length in c#c#中的加密字符串长度
【发布时间】:2019-02-08 05:43:06
【问题描述】:

我在我的应用程序中使用 AES 加密。我使用了 3 种加密类型 AES-128、AES-192、AES-256 密钥大小。 当我用相同的文本使用不同的密钥大小(128 或 192 或 256)加密时,所有密钥大小(128 和 192 和 256)的加密字符串长度相同,而加密字符仅不同。它是否正确?每个密钥大小的加密字符串长度是否总是相同?

  static string GetEncryptedString_Aes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;

        // Create an AesCryptoServiceProvider object
        // with the specified key and IV.
        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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 the encrypted bytes from the memory stream.
        return Convert.ToBase64String(encrypted);

    }

【问题讨论】:

  • 你试过不同的字符串长度吗?发布一些数字。
  • 并发布加密代码。您的加密可能是错误的。
  • 您尝试解密您加密的内容吗?如果你做错了,你可能无法解密它们。也发布您的代码。
  • @Richie86 感谢您的关注。我能够解密它并得到确切的文本

标签: c# encryption-symmetric


【解决方案1】:

查看下面的链接。您的密钥大小不会改变您的输出长度。 (分组密码加密)

Size of data after AES/CBC and AES/ECB encryption

【讨论】:

  • 请注意,这是特定于 AES 的。您可以从最小/最大块大小值中看出,它们在 128b / 16B 时是相同的
【解决方案2】:

根据所使用的填充、键大小等和算法,您会得到奇怪的大小

我总是喜欢验证它,所以我只是 fidle 使用我喜欢使用的类型和我希望输入具有的数据大小,像这样我知道数据库中数据需要的大小.

尝试在链接中使用您的数据,看看您需要什么。

【讨论】:

    【解决方案3】:

    您使用的是 SQL Server 2005 或更高版本吗?如果是这样,您可以只使用 VARCHAR(MAX) 或 NVARCHAR(MAX) 作为列类型。

    如果你想更精确一点...

    RijndaelManaged 的​​最大块大小为 256 位(32 字节)。

    您的最大输入大小为 20 个字符,因此即使我们假设每个字符 4 个字节的最坏情况,也只会达到 80 个字节,然后将填充到最多 96 个字节加密过程。

    如果您在加密输出上使用 Base64 编码,将从 96 个加密字节创建 128 个字符。如果您使用十六进制编码,那么将从 96 个加密字节中创建 192 个字符(如果您在十六进制字符串前加上“0x”前缀,可能还会加上几个额外的字符)。在任何一种情况下,200 个字符的列宽都应该为您提供足够的空间。

    (注意:这些只是我头脑中的计算。我还没有验证它们是否真的正确!)

    【讨论】:

    • 问题中没有任何内容表明使用了数据库。
    猜你喜欢
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多