我正在尝试加密有人输入到富文本框中的文本,但我遇到了一些麻烦。当按下按钮加密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);
这些是我使用的局部变量:
string cData;
byte[] cBytes;
byte[] pBytes;
byte[] pBytes2;
byte[] pKey;
SymmetricAlgorithm desObj;#
我在表单初始化时这样做:
desObj = Rijndael.Create();
所以我知道Key必须能被8整除。所以我试图扩展Key i,在文本框中输入,结果是divisibnle为8,所以f.e。如果输入的字符串是“test”,它会将此字符串扩展为“test1234”。
错误讯息:
mscorlib.dll中出现未处理的“System.Security.Cryptography.CryptographicException”类型的异常附加信息:给定密钥的此算法大小无效