.net 下檔案加密和解密

來源:互聯網
上載者:User
加密|解密 關鍵詞:.net 2005  Framework 加密解密檔案本文:用XML檔案記錄配置資訊時,有時候不希望別人看到配置資訊的內容.怎麼才能實現呢.這裡介紹幾種常見的加密和解密演算法.這些演算法Framework已經封裝好了.我們不用理會具體的實現,只需要會用就行.下面給出一個來源程式供大家參考.
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;namespace coder
{
    /// <summary>
    /// SymmCrypto 的摘要說明。
    /// SymmCrypto類實現.NET架構下的加密和解密服務。
    /// 原作者: Frank Fang : fangfrank@hotmail.com
    ///改進者:ligang : nkligang@163.com
    /// </summary>
    public class SymmCrypto
    {
        public enum SymmProvEnum : int
        {
            DES, RC2, Rijndael
        }        private SymmetricAlgorithm mobjCryptoService;        /// <remarks>
        /// 使用.Net SymmetricAlgorithm 類的構造器.
        /// </remarks>
        public SymmCrypto(SymmProvEnum NetSelected)
        {
            switch (NetSelected)
            {
                case SymmProvEnum.DES:
                    mobjCryptoService = new DESCryptoServiceProvider();
                    break;
                case SymmProvEnum.RC2:
                    mobjCryptoService = new RC2CryptoServiceProvider();
                    break;
                case SymmProvEnum.Rijndael:
                    mobjCryptoService = new RijndaelManaged();
                    break;
            }
        }        /// <remarks>
        /// 使用自訂SymmetricAlgorithm類的構造器.
        /// </remarks>
        public SymmCrypto(SymmetricAlgorithm ServiceProvider)
        {
            mobjCryptoService = ServiceProvider;
        }        /// <remarks>
        /// Depending on the legal key size limitations of
        /// a specific CryptoService provider and length of
        /// the private key provided, padding the secret key
        /// with space character to meet the legal size of the algorithm.
        /// </remarks>
        private byte[] GetLegalKey(string Key)
        {
            string sTemp;
            if (mobjCryptoService.LegalKeySizes.Length > 0)
            {
                int lessSize = 0, moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;
                // key sizes are in bits
                while (Key.Length * 8 > moreSize)
                {
                    lessSize = moreSize;
                    moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;
                }
                sTemp = Key.PadRight(moreSize / 8, ' ');
            }
            else
                sTemp = Key;            // convert the secret key to byte array
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }        public byte[] Encrypting(byte[] bytIn, string Key)
        {            // create a MemoryStream so that the process can be done without I/O files
            System.IO.MemoryStream ms = new System.IO.MemoryStream();            byte[] bytKey = GetLegalKey(Key);            // set the private key
            mobjCryptoService.Key = bytKey;
            mobjCryptoService.IV = bytKey;            // create an Encryptor from the Provider Service instance
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();            // create Crypto Stream that transforms a stream using the encryption
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);            // write out encrypted content into MemoryStream
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();            // get the output and trim the '\0' bytes
            byte[] bytOut = ms.GetBuffer();            return bytOut;
        }        public byte[] Decrypting(byte[] bytIn, string Key)
        {
            // create a MemoryStream with the input
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);            byte[] bytKey = GetLegalKey(Key);            // set the private key
            mobjCryptoService.Key = bytKey;
            mobjCryptoService.IV = bytKey;            // create a Decryptor from the Provider Service instance
            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();            // create Crypto Stream that transforms a stream using the decryption
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            // read out the result from the Crypto Stream
            cs.Write(bytIn, 0, bytIn.Length);
            cs.Flush();            return ms.ToArray();
        }
    }
}下面給出具體使用的例子:        //編碼        public bool Encoding(string inputfile,string outputfile)
        {
            byte[] buffer = new byte[1024];
            byte[] buf = new byte[1032];            int temp;
            coder.SymmCrypto coding = new SymmCrypto(coder.SymmCrypto.SymmProvEnum.DES);
            if (System.IO.File.Exists(inputfile))
            {
                // 定義檔案讀取類
                Stream inStream = File.Open(inputfile,FileMode.Open);
                Stream outStream = File.Create(outputfile);
                // 讀取檔案
                do
                {
                    temp = inStream.Read(buffer, 0, 1024);
                    buf = coding.Encrypting(buffer, "12345678");
                    if (temp > 0)
                    {
                        outStream.Write(buf, 0, temp+8);
                    }
                    else
                        break;
                }
                while (true);                // 釋放流資源
                inStream.Close();
                outStream.Close();
            }            return true;
        }        //解碼        public bool Decoding(string inputfile, string outputfile)
        {
            byte[] buffer = new byte[1032];
            byte[] buf = new byte[1024];
            int temp;
            coder.SymmCrypto coding = new SymmCrypto(coder.SymmCrypto.SymmProvEnum.DES);
            if (System.IO.File.Exists(inputfile))
            {
                Stream inStream = File.Open(inputfile, FileMode.Open);
                Stream outStream = File.Create(outputfile);
                do
                {
                    temp = inStream.Read(buffer, 0, 1032);
                    buf = coding.Decrypting(buffer, "12345678");                    if (temp > 0)
                    {
                        outStream.Write(buf, 0, temp-8);
                    }
                    else
                        break;
                }
                while (true);                inStream.Close();
                outStream.Close();
            }            return true;
        } 需要說明的幾點問題:1.本程式適用於對檔案的加密和解密.源作者的加密和解密程式對於二進位檔案甚至文字檔的讀寫是存在問題的2.本程式去掉了來源程式中base64編碼和解碼過程.因為存在這樣的問題,對於檔案內容進行加密後可能會出現字元0(ASCII),而這個特殊字元在base64編碼中會出問題.base64編碼函數會認為0是結束並把以後的部分填充一些字元.3.針對於檔案輸入輸出緩衝區大小問題.考慮到加密後字元數目會增加8個.所以讀入的緩衝區在加密時應當比寫入的緩衝區小8,但是解密部分可以不採取讀入緩衝區大小比寫入緩衝區大小大8個字元的方案,但是建議按照這個方案進行.


相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。