在解密密文时,输入数据不是完整的块

时间:2016-02-08 13:59:53

标签: c#

任何人都可以帮我解决问题吗? 这是Decrypt功能代码。

    public  static string DecryptStringAES(string cipherText)
    {
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("plainText");
        String key = "0102030405060708";
        String iv = "1020304050607080";
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (iv == null || iv.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] bytearraytodecrypt = Encoding.ASCII.GetBytes(cipherText);


        AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
        keydecrypt.BlockSize = 128;
        keydecrypt.KeySize = 128;
        keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
        keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
        keydecrypt.Padding = PaddingMode.PKCS7;
        keydecrypt.Mode = CipherMode.CBC;

        ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);

        byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
        crypto1.Dispose();
        return Convert.ToBase64String(returnbytearray);
    }

2 个答案:

答案 0 :(得分:1)

hi这是修改后的代码,它运行正常。 我对前一代码所做的更改是将密文从Base64字符串转换为字节格式,最后返回String时将其转换为System.Text.Encoding.UTF8.GetString格式。

public  static string DecryptStringAES(string cipherText)
{
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("plainText");

    String key = "0102030405060708";
    String iv = "1020304050607080";

    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("Key");

    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("IV");

    byte[] bytearraytodecrypt = Convert.FromBase64String(cipherText);

    AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
    keydecrypt.BlockSize = 128;
    keydecrypt.KeySize = 128;
    keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
    keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
    keydecrypt.Padding = PaddingMode.PKCS7;
    keydecrypt.Mode = CipherMode.CBC;

    ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);

    byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
    crypto1.Dispose();
    return System.Text.Encoding.UTF8.GetString(returnbytearray);
}

答案 1 :(得分:0)

不确定问题是什么。

CBC模式下的AES是块密码,即输入和输出是块大小的块。

如果加密的输入可能不总是块大小的倍数,则可以将填充(问题代码中的PKCS#7填充)添加到要加密的数据中以使其成为可能。输出将是块大小的倍数。

由于这个问题没有意义,如果使用PKCS#7填充(如代码中所示),加密数据将始终是块大小的多极。

在解密时,解密的输出将是块大小的倍数,然后可以删除填充。

通过在APIU调用中指定PKCS#7填充,填充/去填充将在API中发生。

还有其他模式,例如CTR,输出与输入的长度相同,它们通常是&#34;流媒体&#34;模式并且有其自身的复杂性,例如从不使用具有相同密钥的相同nonce。