文件加密和解密问题 [英] File Encryption and Decryption issue

查看:88
本文介绍了文件加密和解密问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在VC#Express 2010中研究加密和解密文件。

I've been playing around with encrypting and decrypting files in VC# Express 2010.

我见过的所有教程和文档都需要两个 FileStream 来加密文件-一个用于读取未加密的版本,另一个用于加密。当我实际编写代码时,它一直抛出错误,告诉我它无法打开文件,因为它是由输出文件流中的另一个进程打开的。

All the tutorials and documentation I've seen require two FileStreams in order to encrypt the file - one for reading the unencrypted version, and the other for encrypting. When I actually wrote the code it kept throwing an error telling me it could not open the file because it was opened by another process at the output filestream.

我假设那是因为文件是由输入文件流打开的。这意味着我必须指定其他文件名?因此,即使操作成功后,我现在仍将在目录中拥有原始的未加密文件以及单独的加密版本?那不是要害吗?还是我在这里做错了什么?我的代码与此类似。

I'm assuming that's because the file is opened by the input filestream. So that means I have to specify a different filename? So even after the operation is successful I'll now have the original unencrypted file in the directory and a separate encrypted version? Doesn't that defeat the point? Or am I doing something wrong here? My code is similar to this...

public string filename = "test.xml";
using (FileStream input = new FileStream(filename, FileMode.Open, FileAccess.Read))
using (FileStream output = new FileStram(filename, FileMode.Open, FileAccess.Write))
using (....all the crypto stream and transform stuff...)
{
    ...do the encryption....
}


推荐答案

您是对的,但这并没有解决问题。 (流式)加密API旨在从Src到Dst进行加密。在通过网络等进行发送/接收时,请考虑对输出进行加密。这可以使输出保持应有的简单性。

You're right but it's not defeating the point. The (streaming) crypto APIs are intended to encrypt from Src to Dst. Think encrypting output while sending/receiving over a network etc. This keeps them simple, as they should be.

对于Src和Dst使用相同的文件会使问题复杂化。这并非完全不可能,但是就像在其自身上复制文件一样,它需要格外小心。

You complicate the issue by using the same file for Src and Dst. That is not totally impossible but like Copying a File over itself it needs some extra care.

通常,加密会增加文件的大小。因此,将文件加密到位并不安全。可以解密,但我不会冒险。

Consider that in general, encrypting will increase the File size. So it is not safe to Encrypt a file in place. Decrypting might be, but I wouldn't risk it.

您需要的是Temp文件和完成后的重命名操作。

What you need is a Temp file and a rename action after completion.

这篇关于文件加密和解密问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆