System.Security.Cryptography_AES_CAPI_usage问题 [英] System.Security.Cryptography_AES_CAPI_usage poblem

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

问题描述

你好!我需要编写使用AESCryptoServiceProvider加密和解密文件的程序,所以我花了很多时间才能使它工作)现在我有了以下代码:

Hello! I need to write program that encrypts and decrypts files using AESCryptoServiceProvider,  so i have spand lots of timem to make it work) And now I have this code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;


namespace Cryptographic
{
 static public class AESCryptographic
 {
  //Object for AES cryptography
  static AesCryptoServiceProvider AESProvider = new AesCryptoServiceProvider();

  static public string EncryptFile(String inputFile, String OutputFile, byte[] Key, byte[] IV, byte CryptoFlag, int KeySize)
  {
   CryptoStream cryptStream = null;
   FileStream fsInput = null;
   FileStream fsCiperText = null;

   try
   {
    //File stream to read the data from the Seleted file
    fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
    //File stream used to write my cipertext to the selected location.
    fsCiperText = new FileStream(OutputFile, FileMode.Create, FileAccess.Write);

    switch (CryptoFlag)
    {
     case 0:
      AESProvider.Mode = CipherMode.CBC;
      break;
     case 1:
      AESProvider.Mode = CipherMode.ECB;
      break;
     default:
      AESProvider.Mode = CipherMode.CBC;
      break;
    }
    AESProvider.KeySize = KeySize;
    AESProvider.Key = Key;
    AESProvider.IV = IV;

    //Create Encryption files
    //create symmentric encryptor object using Key and Initialize vecor.
    ICryptoTransform encrypt = AESProvider.CreateEncryptor(AESProvider.Key, AESProvider.IV);

    //Stream make link with datastream to Cryptographic transformation   
    cryptStream = new CryptoStream(fsCiperText, encrypt, CryptoStreamMode.Write);

    //Calculate number of bytes in the input file
    byte[] byteArrayInput = new byte[fsInput.Length];

    //Read block of bytes from the stream and write into given buffer
    int count = fsInput.Read(byteArrayInput, 0, byteArrayInput.Length);
    //Write sequence of bytes.
    cryptStream.Write(byteArrayInput, 0, count);

    cryptStream.Close();

    return "Complete!";
   }
   catch (Exception exc)
   {
    return "Error!: " + exc.Message;
   }
   finally
   {
    fsCiperText.Close();
    fsInput.Close();
   }
  }

  static public string DecryptFile(String inputFile, String outputFile, byte[] Key, byte[] IV, byte CryptoFlag, int KeySize)
  {
   FileStream fsCiperFile = null;
   FileStream fsOutputFile = null;
   CryptoStream decryptStream = null;
   //Calculate number of bytes in the input file
   try
   {
    //Read the cipertext from the input files
    fsCiperFile = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
    //Output file given after decryption
    fsOutputFile = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite);

    AESProvider.KeySize = KeySize;
    AESProvider.Key = Key;
    AESProvider.IV = IV;

    switch (CryptoFlag)
    {
     case 0:
      AESProvider.Mode = CipherMode.CBC;
      break;
     case 1:
      AESProvider.Mode = CipherMode.ECB;
      break;
     default:
      AESProvider.Mode = CipherMode.CBC;
      break;
    }

    //Decrypt the data based on key and IV values
    ICryptoTransform decrypt = AESProvider.CreateDecryptor(AESProvider.Key, AESProvider.IV);

    byte[] byteArrayInput = new byte[fsCiperFile.Length];

    decryptStream = new CryptoStream(fsCiperFile, decrypt, CryptoStreamMode.Read);

    int count = decryptStream.Read(byteArrayInput, 0, byteArrayInput.Length);
    decryptStream.Close();

    //Write the decrypted data into the Output files
    fsOutputFile.Write(byteArrayInput, 0, count);
    return "Complete!";
   }
   catch (Exception exc)
   {
    return "Error!: " + exc.Message;
   }
   finally
   {
    fsCiperFile.Close();
    fsOutputFile.Close();
   }
  }
 }
}

推荐答案

这是一件很有趣的事情.因此,据我了解,您可能有一个巨大的文件,加密或解密在每个点都会读取所有文件.因此,我在您的代码中添加了一个循环,每次处理需要占用100个字节的块.这样你就没有所有 这个巨大的文件加载到内存中.

This one was a pret interesting one to do. So as i understand, you probably have a huge file and at each point Encrypt or Decrypt reads all of it. So i added loops in your code that take chunks of 100 bytes at a time to process. This way you dont have all this huge file loaded in memory.


static public string EncryptFile(String inputFile, String OutputFile, byte[] Key, byte[] IV, byte CryptoFlag, int KeySize)
        {
            CryptoStream cryptStream = null;
            FileStream fsInput = null;
            FileStream fsCiperText = null;

            try
            {
                //File stream to read the data from the Seleted file
                fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
                //File stream used to write my cipertext to the selected location.
                fsCiperText = new FileStream(OutputFile, FileMode.Create, FileAccess.Write);

                switch (CryptoFlag)
                {
                    case 0:
                        AESProvider.Mode = CipherMode.CBC;
                        break;
                    case 1:
                        AESProvider.Mode = CipherMode.ECB;
                        break;
                    default:
                        AESProvider.Mode = CipherMode.CBC;
                        break;
                }
                AESProvider.KeySize = KeySize;
                AESProvider.Key = Key;
                AESProvider.IV = IV;

                //Create Encryption files
                //create symmentric encryptor object using Key and Initialize vecor.
                ICryptoTransform encrypt = AESProvider.CreateEncryptor(AESProvider.Key, AESProvider.IV);

                //Stream make link with datastream to Cryptographic transformation   
                cryptStream = new CryptoStream(fsCiperText, encrypt, CryptoStreamMode.Write);

                //Create a chunksize byte array
                int lChunkSize = 100;
                byte[] byteArrayInput = new byte[lChunkSize];

                //Here, instead of loading the whole file into memory we just do it in chunks
                while (fsInput.Position < fsInput.Length)
                {
                    //Read data
                    int lBytesRead = fsInput.Read(byteArrayInput, 0, fsInput.Length - fsInput.Position < lChunkSize? Convert.ToInt32(fsInput.Length - fsInput.Position): lChunkSize);
                    //Write data
                    cryptStream.Write(byteArrayInput, 0, lBytesRead);
                    cryptStream.Flush();
                }

                cryptStream.Close();

                return "Complete!";
            }
            catch (Exception exc)
            {
                return "Error!: " + exc.Message;
            }
            finally
            {
                fsCiperText.Close();
                fsInput.Close();
            }
        }


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

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