【发布时间】:2013-08-24 15:42:20
【问题描述】:
我正在加密和解密一个文件。下面是代码。
加密代码
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));
【问题讨论】:
-
您是否尝试过阅读
reader中存在的所有行?你似乎只看两行。我还注意到您正在加密字节:WriteByte,但读取文本:ReadLine。最好对两者都使用字节,然后将字节转换回文本。 -
@rossum:哇,这很有趣。让我们看看
-
@rossum:嗨,我更新了代码和问题。请看一下
标签: .net visual-studio-2010 visual-c++ encryption c++-cli