马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

c#文件加密解密

  [复制链接]
查看7995 | 回复3 | 2014-7-23 09:34:20 | 显示全部楼层 |阅读模式
废话没有,直接上代码,转自博客园

1.文件加密代码
[C#] 纯文本查看 复制代码
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.文件解密代码
[C#] 纯文本查看 复制代码
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;
        }
    }
}


调用方法:
调用加密文件:
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#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
Testing_C# | 2014-8-5 16:02:42 | 显示全部楼层
文件的加密和解密有这么长
caozhao | 2015-7-15 16:21:44 | 显示全部楼层
谢谢分享
881966 | 2018-12-4 20:55:18 | 显示全部楼层
谢谢分享,学习学习
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则