我正在加密和解密文件。以下是代碼。文件解密錯誤
加密代碼
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");
}
解密碼
空隙InformationReader :: readInformation() { 系統::字符串^密碼= 「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));
您是否試過閱讀'reader'中的所有行?你似乎只看兩條線。我還注意到,您正在加密字節:「WriteByte」,但是正在讀取文本:「ReadLine」。最好使用兩個字節,然後將字節轉換回文本。 – rossum
@rossum:哇,這很有趣。讓我們看看 –
@rossum:嗨,我更新了代碼和問題。請看一看 –