1

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

加密代码

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

在此处输入图像描述

4

1 回答 1

0

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

当您确定您的加密方法有效时,请使用您的解密方法解密其中一个测试向量,并检查它返回给您的字节是否与您最初加密的字节相同。同样,使用字节而不是字符。使用字符会在过程中过早引入大量错误。

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

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

于 2013-08-25T17:59:06.783 回答