Click here to Skip to main content
14,271,421 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi, I want to Encrypt and Decrypt plain Text with C# with different keys.
When I run this code its gives the error Invalid length for a Base-64 char array on
rijndaelCipher.Key = Convert.FromBase64String("ABC");

I also tried
 rijndaelCipher.Key = Encoding.ASCII.GetBytes("ABC");
// but it gives this error "Specified key is not a valid size for this algorithm."

My code is :
public string EncryptString(string plainText)
            // Instantiate a new RijndaelManaged object to perform string symmetric encryption
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            // Set key and IV
            rijndaelCipher.Key = Convert.FromBase64String("ABC"); //Error is here                       

            MemoryStream memoryStream = new MemoryStream();
            ICryptoTransform rijndaelEncryptor = rijndaelCipher.CreateEncryptor();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelEncryptor, CryptoStreamMode.Write);
            byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
            byte[] cipherBytes = memoryStream.ToArray();


            string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
            return cipherText;

Every suggestion would be appreciate.

Updated 28-Jun-14 16:19pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Solved this problems by adding this method for converting string to byte array :

private static byte[] CreateKey(string password)
            var salt = new byte[] { 1, 2, 23, 234, 37, 48, 134, 63, 248, 4 };

            const int Iterations = 9872;
            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, Iterations);
                return rfc2898DeriveBytes.GetBytes(32);


Previous Code is :
rijndaelCipher.Key = Convert.FromBase64String("ABC");

After solved code is :
rijndaelCipher.Key =CreateKey("ABC");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100