Home > Net >  Why decrypting Persian text in AES256 remove some characters from the end?
Why decrypting Persian text in AES256 remove some characters from the end?

Time:02-10

Want to encrypt and decrypt Persian text in C# (.net framework 8) it works fine in English alphabets but when I use Persian/Arabic text, some characters have been removed from the end of the result, what's wrong with my codes?

public class AES256
{
    private static RijndaelManaged rijndaelManaged;
    private static byte[] key, pwd, ivBytes, iv;
    private enum EncryptMode { ENCRYPT, DECRYPT };

    public static string Encrypt(string _plainText, string _key, string _initVector)
    {
        InitAES256();
        return Process(_plainText, _key, EncryptMode.ENCRYPT, _initVector);
    }
    public static string Decrypt(string _encryptedText, string _key, string _initVector)
    {
        InitAES256();
        return Process(_encryptedText, _key, EncryptMode.DECRYPT, _initVector);
    }

    private static void InitAES256()
    {
        rijndaelManaged = new RijndaelManaged();
        rijndaelManaged.Mode = CipherMode.CBC;
        rijndaelManaged.Padding = PaddingMode.PKCS7;
        rijndaelManaged.KeySize = 256;
        rijndaelManaged.BlockSize = 128;
        key = new byte[32];
        iv = new byte[rijndaelManaged.BlockSize / 8]; 
        ivBytes = new byte[16];
    }

    private static string Process(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector)
    {
        string _out = string.Empty;


        pwd = Encoding.UTF8.GetBytes(_encryptionKey);
        ivBytes = Encoding.UTF8.GetBytes(_initVector);

        int len = pwd.Length;
        if (len > key.Length)
        {
            len = key.Length;
        }
        int ivLenth = ivBytes.Length;
        if (ivLenth > iv.Length)
        {
            ivLenth = iv.Length;
        }

        Array.Copy(pwd, key, len);
        Array.Copy(ivBytes, iv, ivLenth);

        rijndaelManaged.Key = key;
        rijndaelManaged.IV = iv;


        if (_mode.Equals(EncryptMode.ENCRYPT))
        {
            byte[] plainText = rijndaelManaged.CreateEncryptor().TransformFinalBlock(Encoding.UTF8.GetBytes(_inputText), 0, _inputText.Length);
            _out = Convert.ToBase64String(plainText);
        }
        else if (_mode.Equals(EncryptMode.DECRYPT))
        {
            byte[] plainText = rijndaelManaged.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length);
            _out = Encoding.UTF8.GetString(plainText);
        }
        rijndaelManaged.Dispose();

        return _out;
    }
}

Using:

string initVector = "123";
string SyncGetKey = "2587";
string result = AES256.Encrypt("داود", SyncGetKey, initVector);
result = AES256.Decrypt(h, SyncGetKey, initVector);

The result is "دا" and "ود" has been removed from the end (as an example).

CodePudding user response:

  •  Tags:  
  • Related