I'm trying to encrypt a text someone entered into a richTextBox, but i'm having some troubles with it. I use this code when a Button is pressed to encrypt the text of the richTextBox:
cData = richTextBox1.Text;
pBytes = Encoding.ASCII.GetBytes(cData);
string pKey2 = InputBox("Encryption-Key", "Enter a Encryption-Key:");
if (pKey2.Length % 8 != 0)
{
int pKey2NeededLength = 0;
for (int i = 0; i < (pKey2.Length + 8); i++)
{
if ((i+pKey2.Length) % 8 == 0)
{
pKey2NeededLength = i;
MessageBox.Show("" + pKey2NeededLength);
break;
}
}
StringBuilder sB = new StringBuilder();
string[] pArray = { "1", "12", "123", "1234", "12345", "123456", "1234567", "12345678" };
sB.Append(pKey2 + pArray[pKey2NeededLength-1]);
pKey2 = sB.ToString();
MessageBox.Show("" + pKey2);
}
pKey = Encoding.ASCII.GetBytes(pKey2);
MessageBox.Show(""+pKey);
desObj.Key = pKey;//Error occures here
desObj.Mode = CipherMode.CBC;
desObj.Padding = PaddingMode.PKCS7;
System.IO.MemoryStream mS = new System.IO.MemoryStream();
CryptoStream cS = new CryptoStream(mS, desObj.CreateEncryptor(), CryptoStreamMode.Write);
cS.Write(pBytes, 0, pBytes.Length);
cS.Close();
cBytes = mS.ToArray();
mS.Close();
richTextBox1.Text = Encoding.ASCII.GetString(cBytes);
These are the local variables i use:
string cData;
byte[] cBytes;
byte[] pBytes;
byte[] pBytes2;
byte[] pKey;
SymmetricAlgorithm desObj;#
and i'm doing this when the form is initialized:
desObj = Rijndael.Create();
So i know that the Key must be divisible by 8. So i tried to extend the Key i enter in the textbox so that the result is divisibnle by 8, so f.e. if the entered string is "test" it will extend this string to "test1234".
Error message:
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll Additional information: The given key has an invalid size for this algorithm