[英]Cryptographic Exception: Input is not a complete block
这是我用于设置masterpassword的一段代码:
private void button1_Click(object sender, EventArgs e)
{
string current = textBox1.Text;
string newPass = textBox2.Text;
string confirmed = textBox3.Text;
string massPass = "winxp.pma";
if (File.Exists(massPass))
{
byte[] cipertext = File.ReadAllBytes(massPass);
string decoded;
if(Encryptor.TryDecrypt(current, cipertext, out decoded))
{
FileStream fs = new FileStream(massPass, FileMode.Truncate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
if(newPass == confirmed)
{
byte[] newCipher = Encryptor.Encrypt(newPass, newPass);
string writeIt = System.Text.Encoding.UTF8.GetString(newCipher);
sw.Write(writeIt);
sw.Flush();
sw.Close();
fs.Close();
this.Close();
}
else
{
MessageBox.Show("New password do not match.", "Error", MessageBoxButtons.OK);
}
}
}
else
{
FileStream fs = new FileStream(massPass, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
if (newPass == confirmed)
{
byte[] ciphertext = Encryptor.Encrypt(newPass, newPass);
string writeIt = System.Text.Encoding.UTF8.GetString(ciphertext);
sw.Write(ciphertext);
sw.Flush();
sw.Close();
fs.Close();
this.Close();
}
回到主窗体,我以以下方式使用TryDecrypt方法:
private void S_Click(object sender, EventArgs e)
{
byte[] ciphertext = File.ReadAllBytes(massPass);
string decoded;
if (Encryptor.TryDecrypt(textBox1.Text, ciphertext, out decoded))
{
accountGroupsBox.Enabled = true;
addNewPasswordToolStripMenuItem.Enabled = true;
label2.Text = "Interface Unlocked";
}
else
{
MessageBox.Show("Incorrect Master Password.", "Authentication Error", MessageBoxButtons.OK);
}
但是,正如我指出的那样,它不会返回true。...我打赌这与我以另一种形式处理FileStreams的方式有关,但是我不太了解幕后发生的事情来确定是否我做对了。
您的输入流不完整。 为了能够对其进行解密,它必须具有一定的大小。 确保您的加密过程正确。 加密的数据应等于或长于您的纯数据。
[编辑]
我在另一个站点上得出的结论是,在关闭输出文件之前,CryptoStream没有机会完成写入数据。 在处置CryptoStream之前,输出流应保持打开状态,以便能够写入其余密文和必要的填充。
我的测试代码:
public static byte[] Encrypt(string password, string plaintext, SymmetricAlgorithm algorithm)
{
byte[] key, iv;
CreateKeyIV(password, out key, out iv);
using (MemoryStream encrypted = new MemoryStream())
{
using (CryptoStream enc = new CryptoStream(encrypted, algorithm.CreateEncryptor(key, iv), CryptoStreamMode.Write))
using (StreamWriter writer = new StreamWriter(enc))
writer.Write(plaintext);
return encrypted.ToArray();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.