1

I am getting the error "Invalid length for a Base-64 char array."

My code is :-

public string Encrypt(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}

public string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";

    byte[] cipherBytes = Convert.FromBase64String(cipherText); //it gives error

    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}

I am able to Encrypt the Xml, the Encrypt method is working as expected. but Decrypt method gives error. How to resolve it?

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
user3265656
  • 23
  • 1
  • 5

1 Answers1

0

It works fine for me. But have a look here:

Invalid length for a Base-64 char array

http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5607e26-7c81-467b-8e90-c6d71d11de6d/invalid-length-for-a-base64-char-array-or-string?forum=vbgeneral

Community
  • 1
  • 1
C0d1ngJammer
  • 550
  • 1
  • 6
  • 21
  • Well I tested it for the Windows Form Application and it worked very well. Does it work for you also on a Windows Form Application? The exception may be caused by different factors. – C0d1ngJammer Feb 04 '14 at 13:03