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

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

问题描述

被加密玩弄和VC#快讯2010年解密的文件。



所有我见过的教程和文档需要两个FileSteams以加密文件。一种用于读取未加密的版本,以及其它用于加密。当我真正写它不停抛出一个错误,告诉我,因为它是由在输出文件流另一个进程打开了它无法打开该文件的代码。



我假设那是因为该文件是由输入FILESTREAM开放。所以这意味着我必须指定一个不同的文件名?所以即使手术成功我就知道有在目录中的原始未加密的文件和一个单独的加密版本?那个犯规打败呢?还是我做错了什么吗?我的代码是类似这样的...

 公共字符串文件名=的test.xml;使用
(的FileStream输入=新的FileStream(文件名,FileMode.Open,FileAccess.Read))
使用(的FileStream输出=新FileStram(文件名,FileMode.Open,FileAccess.Write))
采用(....所有的加密数据流和改造STUF ...)
{
...做加密....
}


解决方案

您是对的,但它不是战胜的地步。的(流)加密的API是为了从加密的Src至DST。在发送/接收通过网络等,这使他们简单,因为他们应该想想加密输出。



您使用的Src和Dst的同一个文件节外生枝。这不是完全不可能,但像在自己复制文件,它需要一些额外的照顾。



考虑到在一般情况下,加密会增加文件大小。因此,它是不是安全的加密到位的文件。解密可能是,但我不会冒这个险。



您需要的是一个临时文件,完成后重命名的动作。


Been playing around with encryption and decrypting files in VC# Express 2010.

All the tutorials and documentation I've seen requires two FileSteams 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 thats because the file is open by the input filestream. So that means I have to specify a different filename? So even after the operation is successful I'll know have the original unencrypted file in the directory and a separate encrypted version? Doesnt 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 stuf...)
 {
  ...do the encryption....
 }

解决方案

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.

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.

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

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

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