1

I have this AES alogrithm to encrypt and decrypt a string. It works just fine if I try to decrypt 1 letter / character but as soon as it overstrides 1 and goes up to maybe 20+ characters it starts throwing me this error.

Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

I'm new to AES encryption/descryption so I've never encountered this error before. How and what do I need to convert to a Convert.ToBase64String()?

This all happends when I press the decrypt button.

And the line throwing me the error would be this
byte[] encryptedBytes = Convert.FromBase64String(encrypted);

Here is an example of a encrypted string zg1Y3w6pPSoYW36q8nR7iQ==gDY7P3Kg6jxWM/bn0N+f6Q==x8FfbeOUwSxqYkokfFtY8Q==4iycn+vyY6UN9Y99k4aljg==N//H6vUxhIboleXlETNj9A==V017IsPvKRmJcn8GH9W+Vg==NZNjLcLJZTkyXGhh3E6mNw==hmnbcfZdVXPU04ywXR3nWQ==SU5RemiwkhpqTAai6/OQOw==p/2GA7NdspZDt6G/RPR9yQ==8l83Pv/2ZQLkHE/4iKYyOA==cSJ+0Um4s160QPDn/pueYw==J+Wxf9fR8MyHTg0FzpurvQ==ufke4Nlwkwb2V6PNdMCPtg==NKeRkuObfma9PdktTiy/AA==tv1JTHMelvuUIzGjZmLEdA==CO3qyFFDu20kMhU8MwE42w==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==N//H6vUxhIboleXlETNj9A==

private const string constKey = "qMvdN091nWru1aUG";
private static string IV = "asdfghjkliyt52g6";




private void encryptButton_Click(object sender, RoutedEventArgs e)
{
    string encryptthis = Encrypt(texttoencrypt.Text);
    encryptedtext.Text = encryptthis;
}

private static string Encrypt(string text)
{
    byte[] plaintextBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
    aes.BlockSize = 128;
    aes.KeySize = 256;
    aes.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(constKey);
    aes.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
    aes.Padding = PaddingMode.PKCS7;
    aes.Mode = CipherMode.CBC;
    ICryptoTransform crypto = aes.CreateEncryptor(aes.Key, aes.IV);
    byte[] encrypted = crypto.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
    return Convert.ToBase64String(encrypted);
}

private static string Decrypt(string encrypted)
{
    byte[] encryptedBytes = Convert.FromBase64String(encrypted);
    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
    aes.BlockSize = 128;
    aes.KeySize = 256;
    aes.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(constKey);
    aes.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
    aes.Padding = PaddingMode.PKCS7;
    aes.Mode = CipherMode.CBC;
    ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);
    byte[] secret = crypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
    crypto.Dispose();
    return System.Text.ASCIIEncoding.ASCII.GetString(secret);

}

0 Answers0