C# 檔案加密和解密

來源:互聯網
上載者:User

標籤:des   io   os   ar   for   檔案   資料   sp   cti   

1、加密

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Security.Cryptography;
 
namespace Sky.Encrypt
{
    /// <summary>
    /// 加密
    /// </summary>
    public class Encryption
    {
        /// <summary>
        /// 產生認證檔案
        /// </summary>
        /// <param name="data">註冊資訊</param>
        /// <param name="fileName">認證檔案路徑</param>
        /// <param name="key"></param>
        public void GenerateFile(string data,string fileName,string key)
        {
            string str = this.EncryptString(data, key);
            this.SerializeFile(str,fileName);
        }
 
        /// <summary>
        /// 序列化對象
        /// </summary>
        /// <param name="data">資料字串</param>
        /// <param name="path">檔案路徑</param>
        private void SerializeFile(string data, string path)
        {
            IFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            if(data!=null)
            {
                using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    binaryFormatter.Serialize(fileStream, data);
                    fileStream.Close();
                }
            }
        }
 
        public string EncryptString(string data, string key)
        {
            string str = string.Empty;
 
            if(string.IsNullOrEmpty(data))
            {
                return str;
            }
 
            MemoryStream ms = new MemoryStream();
            byte[] myKey = Encoding.UTF8.GetBytes(key);
            byte[] myIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
            DES myProvider = new DESCryptoServiceProvider();
            CryptoStream cs = new CryptoStream(ms, myProvider.CreateEncryptor(myKey, myIV), CryptoStreamMode.Write);
 
            try
            {
                byte[] bs = Encoding.UTF8.GetBytes(data);
                cs.Write(bs, 0, bs.Length);
                cs.FlushFinalBlock();
                str = Convert.ToBase64String(ms.ToArray());
            }
            finally
            {
                cs.Close();
                ms.Close();
            }
            return str;
        }
    }
}
2、檔案解密

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
 
namespace Sky.Decrypt
{
    /// <summary>
    /// 解密
    /// </summary>
    public class Decryption
    {
        public Decryption()
        {
        }
 
        /// <summary>
        /// 擷取檔案內容——字串
        /// </summary>
        /// <param name="path">檔案路徑</param>
        /// <returns>檔案內容</returns>
        public string GetString(string path)
        {
            return this.DeserializeFile(path);
        }
 
        /// <summary>
        /// 還原序列化檔案
        /// </summary>
        /// <param name="path">檔案路徑</param>
        /// <returns>檔案內容</returns>
        private string DeserializeFile(string path)
        {
            string str = "";
 
            if(!File.Exists(path))
            {
                throw new Exception("File is not exist!");
            }
 
            IFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using(FileStream fileStream=new FileStream(path,FileMode.Open,FileAccess.Read))
            {
                str = (string)binaryFormatter.Deserialize(fileStream);
                fileStream.Close();
            }
 
            return str;
        }
 
        public string DecryptString(string data,string key)
        {
            string str = string.Empty;
 
            if(string.IsNullOrEmpty(data))
            {
                throw new Exception("data is empty");
            }
 
            MemoryStream ms = new MemoryStream();
            byte[] myKey = Encoding.UTF8.GetBytes(key);
            byte[] myIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
            DES myProvider = new DESCryptoServiceProvider();
            CryptoStream cs = new CryptoStream(ms, myProvider.CreateDecryptor(myKey, myIV), CryptoStreamMode.Write);
 
            try
            {
                byte[] bs =Convert.FromBase64String(data);
                cs.Write(bs, 0, bs.Length);
                cs.FlushFinalBlock();
                str = Encoding.UTF8.GetString(ms.ToArray());
            }
            finally
            {
                cs.Close();
                ms.Close();
            }
            return str;
        }
    }
}
 3、調用方法


調用加密檔案:

Encryption encry = new Encryption();

string xmldata = File.ReadAllText("檔案路徑1");

string data = encry.EncryptString(xmldata,"abcdefgh");//abcdefgh關鍵,密碼

File.WriteAllText("儲存到檔案2",data);

解密

Decryption decrypt = new Decryption();

string strData = File.ReadAllText("儲存到檔案2");

string newData = decrypt.DecryptString(strData,"abcdefgh");//abcdefgh加密是的密鑰

C# 檔案加密和解密

相關文章

聯繫我們

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

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

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.