パディングが無効で削除できませんか? 質問する

パディングが無効で削除できませんか? 質問する

この例外が私のプログラムに関連して何を意味するのかオンラインで調べましたが、解決策や私の特定のプログラムで発生する理由が見つからないようです。私は、Rijndael アルゴリズムを使用して XmlDocument を暗号化および復号化するために、MSDN で提供されている例を使用しています。暗号化は正常に機能しますが、復号化しようとすると、次の例外が発生します。

パディングが無効であるため削除できません

この問題を解決するにはどうすればいいか、誰か教えていただけませんか? 以下のコードは、キーやその他のデータを取得するコードです。cryptoMode が false の場合、例外が発生する decrypt メソッドが呼び出されます。

public void Cryptography(XmlDocument doc, bool cryptographyMode)
{
    RijndaelManaged key = null;
    try
    {
    // Create a new Rijndael key.
    key = new RijndaelManaged();
    const string passwordBytes = "Password1234"; //password here 

    byte[] saltBytes = Encoding.UTF8.GetBytes("SaltBytes");
    Rfc2898DeriveBytes p = new Rfc2898DeriveBytes(passwordBytes, saltBytes);
    // sizes are devided by 8 because [ 1 byte = 8 bits ] 
    key.IV = p.GetBytes(key.BlockSize/8);
    key.Key = p.GetBytes(key.KeySize/8);

    if (cryptographyMode)
    {
        Ecrypt(doc, "Content", key);
    }
    else
    {
        Decrypt(doc, key);
    }

    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    finally
    {
    // Clear the key.
    if (key != null)
    {
        key.Clear();
    }
    }

}

private void Decrypt(XmlDocument doc, SymmetricAlgorithm alg)
{
    // Check the arguments.  
    if (doc == null)
    throw new ArgumentNullException("Doc");
    if (alg == null)
    throw new ArgumentNullException("alg");

    // Find the EncryptedData element in the XmlDocument.
    XmlElement encryptedElement = doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;

    // If the EncryptedData element was not found, throw an exception.
    if (encryptedElement == null)
    {
    throw new XmlException("The EncryptedData element was not found.");
    }


    // Create an EncryptedData object and populate it.
    EncryptedData edElement = new EncryptedData();
    edElement.LoadXml(encryptedElement);

    // Create a new EncryptedXml object.
    EncryptedXml exml = new EncryptedXml();


    // Decrypt the element using the symmetric key.
    byte[] rgbOutput = exml.DecryptData(edElement, alg); <----  I GET THE EXCEPTION HERE
    // Replace the encryptedData element with the plaintext XML element.
    exml.ReplaceData(encryptedElement, rgbOutput);

}

ベストアンサー1

Rijndael/AES はブロック暗号です。128 ビット (16 文字) のブロックでデータを暗号化します。暗号パディングメッセージの最後のブロックが常に正しいサイズであることを確認するために使用されます。

復号化メソッドは、デフォルトのパディングを期待していますが、それを見つけることができません。@NetSquirrel が言うように、暗号化と復号化の両方に対してパディングを明示的に設定する必要があります。他の理由がない限り、PKCS#7 パディングを使用してください。

おすすめ記事