我正在加密和解密文件。下面是代码。
加密代码
void InformationWriter::writeContacts(System::String ^phone, System::String ^email)
{
//Write the file
StreamWriter ^originalTextWriter = gcnew StreamWriter("contacts.dat",false);
originalTextWriter->WriteLine(phone);
originalTextWriter->WriteLine(email);
originalTextWriter->Close();
//Encrypt the file
FileStream ^fileWriter = gcnew FileStream("contacts2.dat",FileMode::Create,FileAccess::Write);
DESCryptoServiceProvider ^crypto = gcnew DESCryptoServiceProvider();
crypto->Key = ASCIIEncoding::ASCII->GetBytes("Intru235");
crypto->IV = ASCIIEncoding::ASCII->GetBytes("Intru235");
CryptoStream ^cStream = gcnew CryptoStream(fileWriter,crypto->CreateEncryptor(),CryptoStreamMode::Write);
//array<System::Byte>^ phoneBytes = ASCIIEncoding::ASCII->GetBytes(phone);
FileStream ^input = gcnew FileStream("contacts.dat",FileMode::Open); //Open the file to be encrypted
int data = 0;
while((data=input->ReadByte()!=-1))
{
cStream->WriteByte((System::Byte)data);
}
input->Close();
cStream->Close();
fileWriter->Close();
System::Windows::Forms::MessageBox::Show("Data Saved");
}
解密代码
void InformationReader::readInformation() { System::String ^password = "Intru235";
FileStream ^stream = gcnew FileStream("contacts2.dat",FileMode::Open,FileAccess::Read);
array<System::Byte>^data = File::ReadAllBytes("contacts2.dat");
System::Windows::Forms::MessageBox::Show(System::Text::Encoding::Default->GetString(data));
DESCryptoServiceProvider ^crypto = gcnew DESCryptoServiceProvider();
crypto->Key = ASCIIEncoding::ASCII->GetBytes(password);
crypto->IV = ASCIIEncoding::ASCII->GetBytes(password);
CryptoStream ^crypStream = gcnew CryptoStream(stream,crypto->CreateDecryptor(),CryptoStreamMode::Read);
StreamReader ^reader = gcnew StreamReader(crypStream);
phoneNumber = reader->ReadLine();
email = reader->ReadLine();
crypStream->Close();
reader->Close();
}
即使我的文件写入工作正常,读取文件也有问题。当我阅读东西时,我只会得到空白行!我知道该程序已读取“某物”,因为这些行是空白的(空格)。
我在这个解密或事情中做错了什么?
更新
上面的解密代码被编辑。现在我正在尝试将字节读取为字节,但是当我将它们显示为文本时(使用下面的代码),我只得到以下
System::Windows::Forms::MessageBox::Show(System::Text::Encoding::Default->GetString(data));