逐行加密/解密文件? [英] Encrypting/decrypting a file line by line?

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

问题描述

我相当新手加密,我正在试图让一个逐行加密器工作;在应用程序运行期间,我需要能够将加密的行附加到文件中,而不仅仅是一个大的大规模加密 - 一切保存。我有一个时间的野兽。这是我的加密器,在我自己的几次失败尝试后无耻地被盗:

  
class Encryption
{
private static readonly byte [] SALT = new byte [] {0x26,0xdc,0xff,0x00,0xad,0xed,0x7a,0xee,0xc5,0xfe,0x07,0xaf,0x4d,0x08,0x22,0x3c};

public static byte [] Encrypt(byte [] plain,string password)
{
MemoryStream memoryStream;
CryptoStream cryptoStream;
Rijndael rijndael = Rijndael.Create();
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password,SALT);
rijndael.Key = pdb.GetBytes(32);
rijndael.IV = pdb.GetBytes(16);
memoryStream = new MemoryStream();
cryptoStream = new CryptoStream(memoryStream,rijndael.CreateEncryptor(),CryptoStreamMode.Write);
cryptoStream.Write(plain,0,plain.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
return memoryStream.ToArray();
}

public static byte [] Decrypt(byte [] cipher,string password)
{
MemoryStream memoryStream;
CryptoStream cryptoStream;
Rijndael rijndael = Rijndael.Create();
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password,SALT);
rijndael.Key = pdb.GetBytes(32);
rijndael.IV = pdb.GetBytes(16);
memoryStream = new MemoryStream();
cryptoStream = new CryptoStream(memoryStream,rijndael.CreateDecryptor(),CryptoStreamMode.Write);
cryptoStream.Write(cipher,0,cipher.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
return memoryStream.ToArray();
}
}

这里是一个虚拟函数,显示如何我正在尝试:

 

private void EncryptFile(string filepath,string outputPath,string password)
{
FileInfo fileInfo = new FileInfo(filepath);
string filename = fileInfo.Name;

string fullpath = outputPath +\\+ filename;

BinaryWriter writer = new BinaryWriter(File.OpenWrite(fullpath),Encoding.ASCII);

///我在这里尝试过的两种方法:
/// 1.所需的方法:逐行加密 - 我假设我可以生成
///多个数据块,稍后解密。这不工作

// string [] lines = File.ReadAllLines(filepath);

/// 2.只需读取整个事物并加密并写入它。

string line = File.ReadAllText(filepath);

// foreach(行中的行)
{
byte [] bytes = Encoding.ASCII.GetBytes(line);
byte [] encoded = Encryption.Encrypt(bytes,password);

writer.Write(encoded);
writer.Flush();
}

writer.Close();
}



private void DecryptFile(string filepath,string outputPath,string password)
{
FileInfo fileInfo = new FileInfo(filepath );
string filename = fileInfo.Name;
string fullpath = outputPath +\\+ filename;

StreamWriter writer = new StreamWriter(fullpath,false,Encoding.UTF8);

byte [] bytes = File.ReadAllBytes(filepath);

///这是正在解密的方法;只需
///抓取所有数据并一次解密。

byte [] decryptpted = Encryption.Decrypt(bytes,password);

string s = Encoding.ASCII.GetString(decryptpted);

writer.Write(s);
writer.Flush();


///我已经尝试了一些这样的事情来逐行解密,
///其中没有一个可以工作。这个问题关于填充
///无效的问题。

/ *
int index = 0;
int count = 32;

while(index

我不完全确定我应该做什么了,我一直在徘徊事情和在线阅读的例子,但他们似乎都是如何加密一个整个文件,或者只是加密一个数据,不做任何事情,而不是立即解密它,我应该如何处理逐行写作? / p>

解决方案

而不是为你编程,我会给你一个可以实现的方案。



如果您有每行加密,我想你想要每行解密,请注意,行是计算机相当不方便的术语,它只是一堆字符这些字符本身使用特定的



此外,我将做出以下假设:




  • 加密文本应以行显示,这意味着字节需要从二进制转换为字符(使用的问题编码);

  • 您希望在保持安全状态下使用单个密钥;

  • 您不需要完整性保护或验证密文,只有机密性。



现在的想法很简单:


  1. 使用基于密码的密钥导出功能创建单个密钥;

  2. 打开文本文件进行阅读(使用正确的 character-encoding );

  3. 读一行并再次将行转换为字节(例如使用UTF-8);

  4. 创建一个在下面创建一个字节数组的输出流;

  5. 创建一个随机的IV并将其写入字节数组(IV总是单个块大小);

  6. 创建加密流并将其连接到同一个输出流;

  7. 加密编码行;

  8. base 64对加密的字节进行编码,并确保它保持在一行中;

  9. 将编码的加密行写入新的文本文件。

相反,反过来,虽然IV应该从基础64解码后的字节中检索,当然可以使用加密时使用的相同方法来计算。


I'm fairly novice to encryption, and I'm trying to get a line-by-line encryptor working; I need to be able to append encrypted lines to a file as I go during an application's run, rather than just one big massive encrypt-everything-and-save. I'm having a beast of a time with it though. Here's my encryptor, shamelessly stolen after several failed attempts at my own:


class Encryption
    {
        private static readonly byte[] SALT = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };

        public static byte[] Encrypt(byte[] plain, string password)
        {
            MemoryStream memoryStream;
            CryptoStream cryptoStream;
            Rijndael rijndael = Rijndael.Create();
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
            rijndael.Key = pdb.GetBytes(32);
            rijndael.IV = pdb.GetBytes(16);
            memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(plain, 0, plain.Length);
            cryptoStream.FlushFinalBlock();
            cryptoStream.Close();
            return memoryStream.ToArray();
        }

        public static byte[] Decrypt(byte[] cipher, string password)
        {
            MemoryStream memoryStream;
            CryptoStream cryptoStream;
            Rijndael rijndael = Rijndael.Create();
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
            rijndael.Key = pdb.GetBytes(32);
            rijndael.IV = pdb.GetBytes(16);
            memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(cipher, 0, cipher.Length);
            cryptoStream.FlushFinalBlock();
            cryptoStream.Close();
            return memoryStream.ToArray();
        }
    }

And here's a dummy function showing how I'm attempting it:


       private void EncryptFile(string filepath, string outputPath, string password)
        {
            FileInfo fileInfo = new FileInfo(filepath);
            string filename = fileInfo.Name;

            string fullpath = outputPath + "\\" + filename;

            BinaryWriter writer = new BinaryWriter(File.OpenWrite(fullpath), Encoding.ASCII);

            /// Two methods that I've attempted here:
            /// 1.  The desired method: encrypt line by line - I assumed I'd be able to generate
            ///     multiple blocks of data and decrypt them later.  This isn't working

            //string[] lines = File.ReadAllLines(filepath);

            /// 2.  Just read the whole thing and encrypt and write it in one swoop.

            string line = File.ReadAllText(filepath);

            //foreach(string line in lines)
            {
                byte[] bytes = Encoding.ASCII.GetBytes(line);
                byte[] encoded = Encryption.Encrypt(bytes, password);

                writer.Write(encoded);
                writer.Flush();
            }

            writer.Close();
        }



        private void DecryptFile(string filepath, string outputPath, string password)
        {
            FileInfo fileInfo = new FileInfo(filepath);
            string filename = fileInfo.Name;
            string fullpath = outputPath + "\\" + filename;

            StreamWriter writer = new StreamWriter(fullpath, false, Encoding.UTF8);

            byte[] bytes = File.ReadAllBytes(filepath);

            ///  Here is the method that's working at the moment for decrypting; just
            ///  grab all the data and decrypt it on one swoop.

            byte[] decrypted = Encryption.Decrypt(bytes, password);

            string s = Encoding.ASCII.GetString(decrypted);

            writer.Write(s);
            writer.Flush();


            ///  I've tried a number of things here to decrypt line by line,
            ///  none of which work.  This crashes with an issue about the padding
            ///  being invalid.  

            /*
            int index = 0;
            int count = 32;

            while (index 

I'm not entirely sure what I should be doing anymore. I've been wandering around poking at things and reading through examples online, but they all seem to be how to encrypt a whole file or just encrypt a piece of data and do nothing with it other than immediately decrypt it again. How should I handle line-by-line writing?

解决方案

Instead of programming this for you, I'll give you a scheme which you could implement.

If you have per line encryption, I presume you want to be able to decrypt per line as well. Note that a "line" is a rather inconvenient term for a computer. It's just a bunch of characters that end with some kind of line terminator. The characters in themselves are encoded using a specific .

Furthermore, I'll make the following assumptions:

  • the encrypted text should be presented in lines, which means that the bytes need to converted from binary to characters (using an );
  • you want a single key to be used, while staying secure;
  • you don't need integrity protection or authentication of the cipher text, only confidentiality.

Now the idea is simple:

  1. create a single key using a password based key derivation function;
  2. open the text file for reading (using the correct );
  3. read a line and convert the line to bytes again (e.g. using UTF-8);
  4. create an output stream that creates a byte array underneath;
  5. create a random IV and write it to the byte array (IV is always a single block size);
  6. create a crypto stream and connect it to the same output stream;
  7. encrypt the encoded line;
  8. base 64 encode the encrypted bytes, and make sure it stays in one line;
  9. write the encoded, encrypted line to a new text file.

To do the opposite, reverse the process, although the IV should be retrieved from the bytes after base 64 decoding, and the key should of course be calculated using the same method as used during encryption.

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

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