海纳百川

文件的加密和解密

利用using System.Security.Cryptography命名空间下的类可以很方便的实现文件的加密和解密
代码如下:
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="inputFile">需要加密的文件</param>
        /// <param name="outputFile">加密后的文件路径</param>
        public void EncryptFile(string inputFile, string outputFile)
        {

            try
            {
                string password = @"mySecurity"; // Your Key Here
                byte[] key = ASCIIEncoding.ASCII.GetBytes(password);

                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

                DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    desCryptoServiceProvider.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
            {
                throw new Exception("文件加密失败!");
            }
        }

        /// <summary>
        /// 文件解密
        /// </summary>
        /// <param name="inputFile">被解密的文件</param>
        /// <param name="outputFile">解密后的文件</param>
        public void DecryptFile(string inputFile,string outputFile)
        {
            try
            {
                string password = @"mySecurity";
                byte[] key = ASCIIEncoding.ASCII.GetBytes(password);
                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
                DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();
                CryptoStream cs = new CryptoStream(fsCrypt,
                    desCryptoServiceProvider.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);
                FileStream fsWrite = new FileStream(outputFile, FileMode.CreateNew);
                int data;
                while((data=cs.ReadByte()) !=-1)
                {
                    fsWrite.WriteByte((byte)data);
                }
            }
            catch(Exception ex)
            {
                throw new Exception("解密文件失败!");
            }
        }

posted on 2010-07-06 22:43  These days  阅读(361)  评论(0编辑  收藏  举报

导航