Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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
C#
rijndaelCipher.Key = Convert.FromBase64String("ABC");

I also tried
C#
 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);
            cryptoStream.FlushFinalBlock();
            byte[] cipherBytes = memoryStream.ToArray();

            memoryStream.Close();
            cryptoStream.Close();

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


Every suggestion would be appreciate.

Regards
Jayanta.
Posted
Updated 28-Jun-14 16:19pm
v2

1 solution

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

C#
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");
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900