Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

[SOLVED] CryptographicException: Invalid input block size AES Decrypt

Discussion in 'Scripting' started by malak, Sep 9, 2018.

  1. malak

    malak

    Joined:
    Jan 23, 2014
    Posts:
    65
    Hi everybody and thanks by advance for your time ;)

    i have a trouble since 2 days with my AES encryp/decrypt
    to do this i use Usecurity asset from assetstore.

    but the problem is when i send an encrypted text to my database sometimes i get errors :(

    if i send something simple like "hello world how are you today ?" that's work but if i send something stupid like:
    "gaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" i get error :(
    i get error about invalid input block size on unity 5+ and invalid length on unity 2018+

    i know the easy way it's to not send something stupid but the apk gonna be used by some people so i prefere to prevent errors .

    here is the error code from unity 5+
    Code (CSharp):
    1. ryptographicException: Invalid input block size.
    2. Mono.Security.Cryptography.SymmetricTransform.FinalDecrypt (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs:462)
    3. Mono.Security.Cryptography.SymmetricTransform.TransformFinalBlock (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs:554)
    4. System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock (System.Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.Cryptography/RijndaelManagedTransform.cs:94)
    5. System.Security.Cryptography.CryptoStream.Read (System.Byte[] buffer, Int32 offset, Int32 count) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.Cryptography/CryptoStream.cs:205)
    6. Assets.USecurity.AES.Decrypt (System.String value, System.String password) (at Assets/USecurity/AES.cs:70)
    7. Body.ShowMessages () (at Assets/CommUnity/Scripts/Body.cs:503)
    8. Header.MessagesBtn () (at Assets/CommUnity/Scripts/Header.cs:44)
    9. UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:154)
    10. UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:637)
    11. UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:773)
    12. UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:52)
    13. UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
    14. UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
    15. UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
    16. UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
    17. UnityEngine.EventSystems.EventSystem:Update()
    18.  
    error code on unity 2018+:
    Code (CSharp):
    1. FormatException: Invalid length.
    2. System.Convert.FromBase64String (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Convert.cs:146)
    3. Assets.USecurity.AES.Decrypt (System.String value, System.String password) (at Assets/USecurity/AES.cs:60)
    4. Body.ShowMessages () (at Assets/CommUnity/Scripts/Body.cs:503)
    5. Header.MessagesBtn () (at Assets/CommUnity/Scripts/Header.cs:44)
    6. UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:166)
    7. UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
    8. UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
    9. UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
    10. UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
    11. UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
    12. UnityEngine.EventSystems.EventSystem:Update()
    and this is the AES encryption script i use :
    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using System.Security.Cryptography;
    4. using System.Text;
    5.  
    6. namespace Assets.USecurity
    7. {
    8.     /// <summary>
    9.     /// AES (Advanced Encryption Standard) implementation with 128-bit key (default);
    10.     /// 128-bit AES is approved  by NIST, but not the 256-bit AES;
    11.     /// 256-bit AES is slower than the 128-bit AES (by about 40%);
    12.     /// Use it for secure data protection;
    13.     /// Do NOT use it for data protection in RAM (in most common scenarios);
    14.     /// </summary>
    15.     public static class AES
    16.     {
    17.         /// <summary>
    18.         /// Key lenght, 128 (default) or 256.
    19.         /// </summary>
    20.         public static int KeyLength = 128;
    21.         private const string SaltKey = "ShMG8hLyZ7k~Ge5@";
    22.         private const string VIKey = "~6YUi0Sv5@|{aOZO"; // TODO: It's strongy recommended to generate random VI each encryption (and store it with encrypted value)
    23.  
    24.         /// <summary>
    25.         /// Encrypt plain string using password.
    26.         /// </summary>
    27.         public static string Encrypt(string value, string password)
    28.         {
    29.             return Encrypt(Encoding.UTF8.GetBytes(value), password);
    30.         }
    31.  
    32.         /// <summary>
    33.         /// Encrypt plain byte array using password.
    34.         /// </summary>
    35.         public static string Encrypt(byte[] value, string password)
    36.         {
    37.             var keyBytes = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(SaltKey)).GetBytes(KeyLength / 8);
    38.             var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
    39.             var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.UTF8.GetBytes(VIKey));
    40.  
    41.             using (var memoryStream = new MemoryStream())
    42.             {
    43.                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
    44.                 {
    45.                     cryptoStream.Write(value, 0, value.Length);
    46.                     cryptoStream.FlushFinalBlock();
    47.                     cryptoStream.Close();
    48.                     memoryStream.Close();
    49.  
    50.                     return Convert.ToBase64String(memoryStream.ToArray());
    51.                 }
    52.             }
    53.         }
    54.  
    55.         /// <summary>
    56.         /// Decrypt AES-encrypted string using password.
    57.         /// </summary>
    58.         public static string Decrypt(string value, string password)
    59.         {
    60.             var cipherTextBytes = Convert.FromBase64String(value);
    61.             var keyBytes = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(SaltKey)).GetBytes(KeyLength / 8);
    62.             var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.None };
    63.             var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.UTF8.GetBytes(VIKey));
    64.  
    65.             using (var memoryStream = new MemoryStream(cipherTextBytes))
    66.             {
    67.                 using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
    68.                 {
    69.                     var plainTextBytes = new byte[cipherTextBytes.Length];
    70.                     var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    71.  
    72.                     memoryStream.Close();
    73.                     cryptoStream.Close();
    74.  
    75.                     return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    76.                 }
    77.             }
    78.         }
    79.     }
    80. }
    please help me to solve this , i really dont understand what's the problem.
    thanks a lot for your help i really appreciate that .

    or maybe check if the length is invalid and send "error message"
    because in my apk if i get the error message i can't access to the messaging center anymore :(
     
    Last edited: Sep 9, 2018
  2. malak

    malak

    Joined:
    Jan 23, 2014
    Posts:
    65
    i solved it by waiting to receive the encrypted text and after this decrypt the text , it was a conflit because and decrypt it in the same time i received it .

    that was the problem ;)
     
  3. berk_can

    berk_can

    Joined:
    Feb 8, 2016
    Posts:
    15
    I am having same problem but didnt understand a bit from your solution what do you mean by waiting to receive, lease help