-->

Bad PKCS7 Padding error: Invalid length 106

2019-02-20 10:34发布

问题:

I'm trying to encrypt and decrypt with the following functions, however, it results in a bad padding error.

If I set PaddingMode to None it returns some alpha characters and random symbols in Log.

I'm possibly missing something from setting the correct structure which is as follows:

  • Cipher Rijndael (AES)
  • Block Size 128 bits (16 bytes)
  • Mode CBC (Cipher Block Chaining) Key
  • MD5 hash passphrase
  • IV Same as the key
  • Data Encoding Base64 Character
  • UTF-8 Encoding

Any help fixing this error and any assistance with ensuring the above structure is met would be greatly appreciated! Thanks

Error

CryptographicException: Bad PKCS7 padding. Invalid length 106.
Mono.Security.Cryptography.SymmetricTransform.ThrowBadPaddingException (PaddingMode padding, Int32 length, Int32 position) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs:363)
Mono.Security.Cryptography.SymmetricTransform.FinalDecrypt (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs:515)
Mono.Security.Cryptography.SymmetricTransform.TransformFinalBlock (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs:554)
System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Security.Cryptography/RijndaelManagedTransform.cs:94)
APIConnector.Decrypt (System.String toDecrypt) (at Assets/APIConnector.cs:85)

My code

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.IO;

public class APIConnector : MonoBehaviour {

    // Use this for initialization
    void Start () {

        Debug.Log ("Starting API connector");


    }

    // Update is called once per frame
    void Update () {



    }

    static string data;
    string firstName="";
    string password="";

    void OnGUI() {

        firstName = GUILayout.TextField (firstName, GUILayout.Width(300));
        password = GUILayout.TextField (password, GUILayout.Width(300));

        if (GUILayout.Button ("Submit"))
                        submit ();

    }

    //Our functions

    void submit(){

        Debug.Log ("Name is: " + firstName + " encrypted is: " + Encrypt(firstName));
        Debug.Log ("Name is: " + firstName + " decrypted is: " + Decrypt(firstName));

    }


            public static string Encrypt (string toEncrypt)
            {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("SecretPassphrase");
                // 256-AES key
        int numBytes = System.Text.Encoding.UTF8.GetBytes(toEncrypt).Length;
        Debug.Log ("Bytes: " + numBytes);
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (toEncrypt);
                RijndaelManaged rDel = new RijndaelManaged ();
                rDel.Key = keyArray;
                rDel.BlockSize = 128;
                rDel.Mode = CipherMode.CBC;
                // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
                rDel.Padding = PaddingMode.PKCS7;
                // better lang support
                ICryptoTransform cTransform = rDel.CreateEncryptor ();
                byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
                return Convert.ToBase64String (resultArray, 0, resultArray.Length);
            }

            public static string Decrypt (string toDecrypt)
            {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("SecretPassphrase");
                // AES-256 key
        byte[] encryptedData = System.Convert.FromBase64String(toDecrypt);
                //byte[] toEncryptArray = Convert.FromBase64String (toDecrypt);
                RijndaelManaged rDel = new RijndaelManaged ();
                rDel.Key = keyArray;
                rDel.BlockSize = 128;
                rDel.Mode = CipherMode.CBC;
                rDel.IV = rDel.Key;
                // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
                rDel.Padding = PaddingMode.PKCS7;
                // better lang support
                ICryptoTransform cTransform = rDel.CreateDecryptor ();
        byte[] resultArray = cTransform.TransformFinalBlock (encryptedData, 0, encryptedData.Length);
                return UTF8Encoding.UTF8.GetString (resultArray);
            }


}

回答1:

You don't appear to be setting the IV when encrypting, and so a random IV will be used automatically. Since you are setting the IV when decrypting (and it won't be the same as was used during encryption), the first output block will be corrupt. If the message is short enough (< 1 block), then the padding will also be corrupt likely resulting in this error.

As usual, I'll note that among other possible issues, the use of the same IV as key is bad practice, as is the use of Encoding.UTF8.GetBytes() for key derivation.