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

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

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

C#原生加密方法: System.Security.Cryptography.CryptoStream DataSet加密解密第1张C#原生加密方法: System.Security.Cryptography.CryptoStream DataSet加密解密第2张
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Security.Cryptography;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceCryptoHelperLib
{
    public classCryptoHelper
    {

        //对称加密算法提供器
        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, stringkey)
        {
            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) { }


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

            CryptoStream cryptoStream =
                newCryptoStream(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);
            returnencryptedStream;
        }
        public Stream EncryptByte(byte[] data)
        {
            MemoryStream clearStream = newMemoryStream(data);
            clearStream.Position = 0;
            //创建空的密文流
            MemoryStream encryptedStream = newMemoryStream();

            CryptoStream cryptoStream =
                newCryptoStream(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);
            returnencryptedStream;
        }


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

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

            CryptoStream cryptoStream =
                newCryptoStream(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);
            returnencryptedText;
        }


        publicMemoryStream DecryptMemoryStream(MemoryStream encryptedStream)
        {
            MemoryStream clearStream = newMemoryStream();
            CryptoStream cryptoStream =
                newCryptoStream(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 = newMemoryStream(buffer);
            returnclearStreamResult;
        }


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

            MemoryStream clearStream = newMemoryStream();
            CryptoStream cryptoStream =
                newCryptoStream(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);

            returnclearText;
        }

        public static string Encrypt(string clearText, stringkey)
        {
            CryptoHelper helper = newCryptoHelper(key);
            returnhelper.EncryptText(clearText);
        }

        public static string Decrypt(string encryptedText, stringkey)
        {
            CryptoHelper helper = newCryptoHelper(key);
            returnhelper.DecryptText(encryptedText);
        }
    }
}
View Code

调用示例:

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

        public byte[] DataSetToBytes(DataSet ds)
        {
            DESCryptoServiceProvider objDES = newDESCryptoServiceProvider();
            MemoryStream dataStream = newMemoryStream();
            MemoryStream dataStream2 = newMemoryStream();
            ds.WriteXml(dataStream, XmlWriteMode.WriteSchema);
            
            CryptoHelperLib.CryptoHelper cryhelper = newCryptoHelperLib.CryptoHelper(key);
            dataStream2=cryhelper.EncryptMemoryStream(dataStream);
            byte[] buf =dataStream2.ToArray();

            returnbuf;
        }

        public DataSet DataSetFromBytes(byte[] buf)
        {

            MemoryStream dataStream = newMemoryStream(buf);
            MemoryStream dataStream2 = newMemoryStream();
            CryptoHelperLib.CryptoHelper cryhelper = newCryptoHelperLib.CryptoHelper(key);
            dataStream2 =cryhelper.DecryptMemoryStream(dataStream);
            dataStream2.Position = 0;
            DataSet ds = newDataSet();
            ds.ReadXml(dataStream2);
            returnds;
        }

免责声明:文章转载自《C#原生加密方法: System.Security.Cryptography.CryptoStream DataSet加密解密》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇自己用C语言写单片机PIC18 serial bootloader关于对VGA、DVI、HDMI的区别下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

RabbitMQ在普通MAVEN项目中的使用

五、在普通的Maven应用中使用MQ rabbitmq的队列结构 5.1简单模式 5.1.1 消息生产者 创建Maven项目 添加RabbitMQ连接所需要的依赖 <!--https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --> <dependency>...

那些年java MD5加密字符编码的坑

相信做过MD5加密的童鞋都遇到过字符编码的坑,一般加密出来的结果和其他人不一样都是字符编码不一致导致的,比如类文件的字符编码、浏览器的字符编码等和对方不一致,所以就需要转码统一字符。 以下是笔者转码过程中遇到的坑: 不要new String("XXXX".getBytes("UTF-8")),之后将转码后的字串传入MD5去加密,会遇到意想不到的效果,有的字...

熟悉Hbase常用命令及操作

(一) 编程实现以下指定功能,并用Hadoop提供的HBase Shell命令完成相同任务: 列出HBase所有的表的相关信息,例如表名; 在终端打印出指定的表的所有记录数据; 向已经创建好的表添加和删除指定的列族或列; 清空指定的表的所有记录数据; 统计表的行数。 (二)HBase数据库操作 1.现有以下关系型数据库中的表和数据,要求将其转换为适合于HB...

DevExpress WinForm MVVM数据和属性绑定指南(Part 1)

根据您绑定的属性,存在以下三种可能的情况: 常规绑定- ViewModel属性绑定到任何不可编辑的View元素属性。由于该元素不可编辑,因此您无需将更新通知发送回绑定属性(单向绑定)。 数据绑定- Model属性(数据字段)绑定到编辑器属性。如果用户可以更改编辑器值,则需要更新绑定属性(双向绑定)。 属性依赖- 来自同一个ViewModel的两个属性被绑...

Swing菜单与工具栏(二)

6.1.4 JMenuItem类 JMenuItem组件是用户可以在菜单栏上选择的预定义组件。作为AbstractButton的子类,JMenuItem是一个特殊的按钮组件,其行为类似于JButton。除了作为AbstractButton的子类,JMenuItem类共享JButton的数据模型(ButtonModel接口与DefaultButtonMode...

httpclient x-www-form-urlencoded

1. 使用Apache httpclient提交post请求 http工具方法(需指定编码, 否则出错,这里用的UTF-8) public static String postWithParamsForString(String url, List<NameValuePair> params){ HttpClient clie...