Encrypting/Decrypting large files (.NET)

后端 未结 5 1344
北恋
北恋 2020-11-29 04:35

I have to encrypt, store and then later decrypt large files. What is the best way of doing that? I heard RSA encryption is expensive and was advised to use RSA to encrypt an

5条回答
  •  遥遥无期
    2020-11-29 05:15

    This may help

    /// Encrypts a file using Rijndael algorithm.
    ///
    ///
    ///
    private void EncryptFile(string inputFile, string outputFile)
    {
    
        try
        {
            string password = @"myKey123"; // Your Key Here
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
    
            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
    
            RijndaelManaged RMCrypto = new RijndaelManaged();
    
            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);
    
            FileStream fsIn = new FileStream(inputFile, FileMode.Open);
    
            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
    
    
            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch
        {
            MessageBox.Show("Encryption failed!", "Error");
        }
    }
    
    ///
    /// Decrypts a file using Rijndael algorithm.
    ///
    ///
    ///
    private void DecryptFile(string inputFile, string outputFile)
    {
    
        {
            string password = @"myKey123"; // Your Key Here
    
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
    
            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
    
            RijndaelManaged RMCrypto = new RijndaelManaged();
    
            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);
    
            FileStream fsOut = new FileStream(outputFile, FileMode.Create);
    
            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);
    
            fsOut.Close();
            cs.Close();
            fsCrypt.Close();
    
        }
    }
    

    source: http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C

提交回复
热议问题