C#原生加密方法: System.Security.Cryptography.CryptoStream DataSet加密解密

采用16位密钥形式加密,把数据 dataset或文本转换为二进制流,然后进行加密解密。代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CryptoHelperLib
{
    public class CryptoHelper
    {

        // 对称加密算法提供器
        private ICryptoTransform encryptor;     // 加密器对象
        private ICryptoTransform decryptor;     // 解密器对象
        //public string key = "ABCDEFGHIJKLMNOP";//长度16
        //public static byte[] DESKey = new byte[] { 11, 23, 93, 102, 72, 41, 18, 12 };
        //public static byte[] DESIV = new byte[] { 75, 158, 46, 97, 78, 57, 17, 36 };
        private const int BufferSize = 1024;
        public CryptoHelper(string algorithmName, string key)
        {
            SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);
            provider.Key = Encoding.UTF8.GetBytes(key);

            provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            encryptor = provider.CreateEncryptor();
            decryptor = provider.CreateDecryptor();
        }

        public CryptoHelper(string key) : this("TripleDES", key) { }

        public MemoryStream EncryptMemoryStream(MemoryStream itemStream)
        {
            // 创建空的密文流
            MemoryStream encryptedStream = new MemoryStream();

            CryptoStream cryptoStream =
                new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);

            // 将明文流写入到buffer中
            // 将buffer中的数据写入到cryptoStream中
            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];
            itemStream.Position = 0;
            do
            {
                bytesRead = itemStream.Read(buffer, 0, BufferSize);
                cryptoStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            cryptoStream.FlushFinalBlock();
            byte[] buffer2 = encryptedStream.ToArray();
            string encryptedText = Convert.ToBase64String(buffer2);
            return encryptedStream;
        }
        public Stream EncryptByte(byte[] data)
        {
            MemoryStream clearStream = new MemoryStream(data);
            clearStream.Position = 0;
            // 创建空的密文流
            MemoryStream encryptedStream = new MemoryStream();

            CryptoStream cryptoStream =
                new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);

            // 将明文流写入到buffer中
            // 将buffer中的数据写入到cryptoStream中
            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];
            do
            {
                bytesRead = clearStream.Read(buffer, 0, BufferSize);
                cryptoStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);
            cryptoStream.FlushFinalBlock();
            // 获取加密后的文本
            byte[] buffer2 = encryptedStream.ToArray();
            string encryptedText = Convert.ToBase64String(buffer2);
            return encryptedStream;
        }

        // 加密算法
        public string EncryptText(string clearText)
        {
            // 创建明文流
            byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
            MemoryStream clearStream = new MemoryStream(clearBuffer);

            // 创建空的密文流
            MemoryStream encryptedStream = new MemoryStream();

            CryptoStream cryptoStream =
                new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);

            // 将明文流写入到buffer中
            // 将buffer中的数据写入到cryptoStream中
            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];
            do
            {
                bytesRead = clearStream.Read(buffer, 0, BufferSize);
                cryptoStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            cryptoStream.FlushFinalBlock();

            // 获取加密后的文本
            buffer = encryptedStream.ToArray();
            string encryptedText = Convert.ToBase64String(buffer);
            return encryptedText;
        }

        public MemoryStream DecryptMemoryStream(MemoryStream encryptedStream)
        {
            MemoryStream clearStream = new MemoryStream();
            CryptoStream cryptoStream =
                new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);

            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];

            do
            {
                bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
                clearStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            buffer = clearStream.GetBuffer();
            MemoryStream clearStreamResult = new MemoryStream(buffer);
            return clearStreamResult;
        }

        //
        // 解密算法, http://www.51testing.com/html/67/n-220867-4.html
        // 解密算法
        public string DecryptText(string encryptedText)
        {
            byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
            Stream encryptedStream = new MemoryStream(encryptedBuffer);

            MemoryStream clearStream = new MemoryStream();
            CryptoStream cryptoStream =
                new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);

            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];

            do
            {
                bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
                clearStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            buffer = clearStream.GetBuffer();
            string clearText =
                Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length);

            return clearText;
        }

        public static string Encrypt(string clearText, string key)
        {
            CryptoHelper helper = new CryptoHelper(key);
            return helper.EncryptText(clearText);
        }

        public static string Decrypt(string encryptedText, string key)
        {
            CryptoHelper helper = new CryptoHelper(key);
            return helper.DecryptText(encryptedText);
        }
    }
}

调用示例:

    // string key="ABCDEFGHIJKLMNOP"; //16位字符串

        public byte[] DataSetToBytes(DataSet ds)
        {
            DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();
            MemoryStream dataStream = new MemoryStream();
            MemoryStream dataStream2 = new MemoryStream();
            ds.WriteXml(dataStream, XmlWriteMode.WriteSchema);

            CryptoHelperLib.CryptoHelper cryhelper = new CryptoHelperLib.CryptoHelper(key);
            dataStream2= cryhelper.EncryptMemoryStream(dataStream);
            byte[] buf = dataStream2.ToArray();

            return buf;
        }

        public DataSet DataSetFromBytes(byte[] buf)
        {

            MemoryStream dataStream = new MemoryStream(buf);
            MemoryStream dataStream2 = new MemoryStream();
            CryptoHelperLib.CryptoHelper cryhelper = new CryptoHelperLib.CryptoHelper(key);
            dataStream2 = cryhelper.DecryptMemoryStream(dataStream);
            dataStream2.Position = 0;
            DataSet ds = new DataSet();
            ds.ReadXml(dataStream2);
            return ds;
        }
时间: 2024-11-07 13:09:08

C#原生加密方法: System.Security.Cryptography.CryptoStream DataSet加密解密的相关文章

转:system.Security.Cryptography C# 加密和解密

以下文转自: http://www.360doc.com/content/13/0122/05/19147_261678471.shtml 总结:注册的时候经过MD5加密存进数据库,在登录的时候需要先加密输入的密码,再进行和数据库里的比对,因为同一字符串加密后是一样的,并不是无规则的:实例: string name = this.TextBox1.Text;        string pwd = System.Web.Security.FormsAuthentication.HashPassw

部署时,出现用户代码未处理 System.Security.Cryptography.CryptographicException 错误解决方法

转载:http://www.cnblogs.com/jys509/p/4499978.html 在调用RSA加密的.pfx密钥时,在本地调试没有问题,可以布署到服务器,就会报以下的错误: 用户代码未处理 System.Security.Cryptography.CryptographicException HResult=-2146893792 Message=出现了内部错误. Source=mscorlib StackTrace: 在 System.Security.Cryptography.

"System.Security.Cryptography.CryptographicException: 拒绝访问" 问题的解决方法

.net web程序使用rsa算法进行加解密时,程序报告“System.Security.Cryptography.CryptographicException: 拒绝访问”错.按网上搜的解决方法做了各种权限配置,然并卵.试了两天终于解决,现记录如下: C:\Documents and Settings\All Users\Application Data 添加项目应用程序池对应启动帐号(或iis_wpg组) 读取,读取并运行,列出文件夹目录权限. C:\Documents and Settin

.Net使用system.Security.Cryptography.RNGCryptoServiceProvider类与System.Random类生成随机数

.Net中我们通常使用Random类生成随机数,在一些场景下,我却发现Random生成的随机数并不可靠,在下面的例子中我们通过循环随机生成10个随机数: for (int i = 0; i < 10; i++) { Random random1 = new Random(); Console.WriteLine(random1.Next()); } 测试生成随时基本都是相同的结果: 很显然上面的结果是不靠谱的,为什么会这样呢,因为微软的Random类,发现在C#中生成随机数使用的算法是线性同余法

WebApi 数据保护操作未成功。这可能是由于未为当前线程的用户上下文加载用户配置文件导致的。当线程执行模拟时,可能会出现此情况。&quot;,&quot;ExceptionType&quot;:&quot;System.Security.Cryptography.CryptographicException&quot;,&quot;StackTrace

在调用System.Security.Cryptography.ProtectedData.Protect方法来保护私密信息时,IIS可能会报以下错误:CryptographicException: 数据保护操作未成功.这可能是由于未为当前线程的用户上下文加载用户配置文件导致的.当线程执行模拟时,可能会出现此情况. 解决方法:1.打开应用程序池2.在应用程序上右键选择高级设置3.进程模型下设置“加载用户配置文件”为True

使用证书部署出现System.Security.Cryptography.CryptographicException 错误解决方案

一.System.Security.Cryptography.CryptographicException: 找不到对象 at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, In

System.Security.Cryptography.CryptographicException: 出现了内部错误

(转载: http://www.cnblogs.com/ithome8/p/5189926.html) 调用微信退款接口时出现System.Security.Cryptography.CryptographicException: 出现了内部错误 解决办法 我总结了一下出现证书无法加载的原因有以下三个 1.证书密码不正确,微信证书密码就是商户号 解决办法:请检查证书密码是不是和商户号一致 2.IIS设置错误,未加载用户配置文件 解决办法:找到网站使用的应用程序池-->右击-->高级设置--&g

System.Security.Cryptography.RSA.FromXmlString 系统找不到指定的文件和X509读取证书文件系统找不到指定的文件异常

前言: 最近公司增加服务器,在新增加的服务器中发现一些问题. 1.应用程序在读取证书文件中出现"系统找不到指定的文件."异常,但是已经确认证书文件存在.本地测试也可以读取,就在新增加的服务器上不可以. 2.RSA加密过程中在 System.Security.Cryptography.RSA.FromXmlString()抛异常: System.Security.Cryptography.CryptographicException: 系统找不到指定的文件. 解决方案: 打开IIS设置,

.NET:System.Security.Cryptography.CryptographicException 的解决办法

问题描述:微信退款提示加载证书失败问题(System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile) 详细内容参考此网址:http://social.msdn.microsoft.com/Forums/en-US/ec93922a-fd1e-4225-b5cf-1472ebb3acd1/systemsecuritycryptographycryptographicexception-the-system-ca