文件解密出错

时间:2013-08-24 15:42:21

标签: .net visual-studio-2010 visual-c++ encryption c++-cli

我正在加密和解密文件。以下是代码。

加密代码

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));

enter image description here

1 个答案:

答案 0 :(得分:0)

首先检查您的加密代码。找到一些DES测试向量,然后通过加密方法运行。不要使用字符,而是检查字节级别。

如果您确定加密方法有效,请使用解密方法解密其中一个测试向量,并检查它返回的字节是否与您首先加密的字节相同。再次,使用字节而不是字符。使用字符可能会在过程中过早引入很多错误。

当您可以成功加密和解密字节数组时,请尝试使用字符。确保您在两侧使用相同的字符转换。您当前的加密方法为Key和IV指定ASCII,但似乎直接转换为明文的字节。您的解密函数也没有为解密的明文指定编码。这不是好习惯。指定两侧的编码,UTF-8作为首选项,但它取决于您当前保存数据的格式。

我之前强调字节级别检查的原因是为了避免字符编码的所有额外复杂性:BOM与否,不同的EoL标记,0x00字节以标记字符串的结尾与否等等。首先使用字节进行处理然后引入字符编码。一次查找并修复一个问题。