C#加密解密类实例程序

前两年写的东西,现在整理一下发出来!以前公司需要做WebService,并且对WebService的SoapHeader进行加密,所以就写了这么个东东!使用这个类,需要密钥管理!为了保证数据的安全性往往要对数据进行加密,但是加密的缺点之一,就是影响程序的运行效率,所以,当时我的思路是只对用户的登录信息(用户名,密码)进行加密!数据用明文传输,用户信息验证没有通过的情况下, 不进行数据传输。
实际在网络通讯中,使用密钥匙的方式并非无懈可击,如果黑客可以捕捉到用密钥加密的,用户验证信息,然后,做个模拟请求,向提供WebService的服务器发请求,还是可以获得请求数据!所以,我又使用了IP或者域名绑定的方式!毕竟,WebService不是直接对最终用户提供的!所以,加上以上这些手段后,就算有不良企图者想通过非法方式获得WebService提供的服务,就再费点劲吧!
还有一点安全建议,就是定期的更换密钥,在这个例子中,我用的是对称加密,加密方和解密方的密钥一致!定期的更换密钥可以让安全性提高一大截!

大家要有更好的方法,或者建议,可以留言讨论一下!共同提高!

代码如下:

代码如下:

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

namespace SEDO
{
    /// <summary>
    /// SEDO 的摘要说明。
    /// SEDO 实现的是用一个封装了4种对称加密方法(Des,Rc2,Rijndael,TripleDes)的组件
    ///
    /// 注意事项:
    /// 1:TripleDes和Rijndael加密/解密对象使用16或者24位byte的Key
    /// 2:Rijndael只能使用16位的初始化向量IV
    /// 3:Des和Rc2均使用8位Byte的Key和IV
    /// 4:对需要加密/解密的数据流采用何种方法进行编码/解码,由调用组件的用户自己决定
    /// 5:密钥和初始化向量IV由使用者自己定义
    /// 程序员: 罗旭成2010-10-30 lxc880615@163.com
    /// </summary>

//定义加密类型的枚举
    public enum EncryptionAlgorithm { Des = 1, Rc2, Rijndael, TripleDes };

//定义加密类
    internal class EncryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

internal EncryptTransformer(EncryptionAlgorithm algId)
        {
            //Save the algorithm being used.
            algorithmID = algId;
        }

internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            //当数据密钥Key或者初始化向量IV为空的时候,
            //将使用加密对象自动产生的密钥Key或者初始化向量IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;

// See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des.Key;
                        }
                        else
                        {
                            des.Key = bytesKey;
                            encKey = des.Key;
                        }
                        // See if the client provided an initialization vector
                        if (null == initVec)
                        { // Have the algorithm create one
                            initVec = des.IV;
                        }
                        else
                        { //No, give it to the algorithm
                            des.IV = initVec;
                        }
                        return des.CreateEncryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        // See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des3.Key;
                        }
                        else
                        {
                            des3.Key = bytesKey;
                            encKey = des3.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = des3.IV;
                        }
                        else
                        { //No, give it to the alg.
                            des3.IV = initVec;
                        }
                        return des3.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rc2.Key;
                        }
                        else
                        {
                            rc2.Key = bytesKey;
                            encKey = rc2.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rc2.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rc2.IV = initVec;
                        }
                        return rc2.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rijndael.Key;
                        }
                        else
                        {
                            rijndael.Key = bytesKey;
                            encKey = rijndael.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rijndael.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rijndael.IV = initVec;
                        }
                        return rijndael.CreateEncryptor();
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        }

//加密的偏移向量
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        //加密的密钥
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

}

//定义解密类
    internal class DecryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

internal DecryptTransformer(EncryptionAlgorithm deCryptId)
        {
            algorithmID = deCryptId;
        }

//加密的偏移向量
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

//加密的密钥
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            //当数据密钥Key或者初始化向量IV为空的时候,
            //将使用加密对象自动产生的密钥Key或者初始化向量IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;
                        des.Key = bytesKey;
                        des.IV = initVec;
                        return des.CreateDecryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        return des3.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        return rc2.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        return rijndael.CreateDecryptor(bytesKey, initVec);
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        } //end GetCryptoServiceProvider

}

//定义加密者类
    public class Encryptor
    {
        private EncryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

public Encryptor(EncryptionAlgorithm algId)
        {
            transformer = new EncryptTransformer(algId);
        }

public byte[] Encrypt(byte[] bytesData, byte[] bytesKey, byte[] bytesIV)
        {
            //设置流对象用来保存加密数据字节流.
            MemoryStream memStreamEncryptedData = new MemoryStream();

transformer.IV = bytesIV;
            transformer.Key = bytesKey;

ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream encStream =
                new CryptoStream(memStreamEncryptedData,
                    transform, CryptoStreamMode.Write);

try
            {
                //将加密数据写进流对象
                encStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("在数据加密的时候出现错误!"+
                    "错误提示: \n" + ex.Message);
            }

//设置加密的Key和初始向量IV属性
            encKey = transformer.Key;
            initVec = transformer.IV;

encStream.FlushFinalBlock();
            encStream.Close();

//Send the data back.
            return memStreamEncryptedData.ToArray();
        }

public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

}

//定义解密者类
    public class Decryptor
    {
        private DecryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

public Decryptor(EncryptionAlgorithm algId)
        {
            transformer = new DecryptTransformer(algId);
        }

public byte[] Decrypt(byte[] bytesData,
            byte[] bytesKey, byte[] bytesIV)
        {
            //设置流对象用来保存解密数据字节流.
            MemoryStream memStreamDecryptedData =
                new MemoryStream();

//Pass in the initialization vector.
            transformer.IV = bytesIV;
            transformer.Key = bytesKey;

ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream decStream =
                new CryptoStream(memStreamDecryptedData,
                    transform, CryptoStreamMode.Write);

try
            {
                decStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("在数据解密的时候出现错误!"+
                    "错误提示: \n" + ex.Message);
            }
            decStream.FlushFinalBlock();
            decStream.Close();
            // 返回解密数据.
            return memStreamDecryptedData.ToArray();
        }

public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

}

//类描述:文件加密/解密类
    public class SecurityFile
    {
        private DecryptTransformer Dec_Transformer; //解密转换器
        private EncryptTransformer Enc_Transformer; //加密转换器
        private byte[] initVec;
        private byte[] encKey;

public SecurityFile(EncryptionAlgorithm algId)
        {
            Dec_Transformer = new DecryptTransformer(algId);
            Enc_Transformer = new EncryptTransformer(algId);
        }

//加密的偏移向量
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        //加密的密钥
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

//功能描述:加密文件
        public void EncryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout = new FileStream(outFileName,
                    FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

//Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len;

Enc_Transformer.IV = bytesIV;
                Enc_Transformer.Key = bytesKey;

ICryptoTransform transform =
                    Enc_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

//Read from the input file, then encrypt and write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }

encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("在文件加密的时候出现错误!"+
                    "错误提示: \n" + ex.Message);
            }
        }

//功能描述:解密文件
        public void DecryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout =
                    new FileStream(outFileName,
                        FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

//Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len;

Dec_Transformer.IV = bytesIV;
                Dec_Transformer.Key = bytesKey;

ICryptoTransform transform =
                    Dec_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

//Read from the input file, then encrypt and
                //write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }
                encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("在文件加密的时候出现"+
                    "错误!错误提示: \n" + ex.Message);
            }
        }
    }
}

(0)

相关推荐

  • c#多种加解密示例(md5加密解密)

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Globalization;using System.IO;using System.Security.Cryptography;using System.Text; /// <summary>/// 加解密/// </summary>public static class CryptHelper{    #region RSA加密 /// &

  • C#字符串加密解密方法实例

    本文实例讲述了C#字符串加密解密方法.分享给大家供大家参考.具体如下: 复制代码 代码如下: #region 加密解密 static string encryptKey= "Oyea"; #region 加密字符串 public static string Encrypt(string str) /// <summary> /// 加密字符串 /// </summary> /// <param name="str">要加密的字符串

  • C#实现基于Base64的加密解密类实例

    本文实例讲述了C#实现基于Base64的加密解密类.分享给大家供大家参考.具体如下: 这个C#类是一个基于Base64的加密和解密类,用户可以可以使用默认的秘钥进行加密.解密,也可以自己设定秘钥进行加密和解密,非常实用 using System; using System.Security.Cryptography; using System.Text; namespace DotNet.Utilities { /// <summary> /// Encrypt 的摘要说明. /// <

  • C#的3DES加密解密算法实例代码

    C#类如下: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO; namespace ConsoleApplication1{    /// <summary>    /// 加解密类    /// </summary>    public class EncryptHelper  

  • C#实现数据包加密与解密实例详解

    在很多项目中,为了安全安全考虑,需要对数据包进行加密处理,本文实例所述的即为C#加密代码,在应用开发中有很大的实用价值.说起数据包加密,其实对C#编程者来说,应该是一个基础的技巧,是进行C#程序设计人员必须要掌握的技能. C#实现加密功能的核心代码如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; usin

  • C#实现对AES加密和解密的方法

    AES简介 AES(The Advanced Encryption Standard)是美国国家标准与技术研究所用于加密电子数据的规范.它被预期能成为人们公认的加密包括金融.电信和政府数字信息的方法. AES 是一个新的可以用于保护电子数据的加密算法.明确地说,AES 是一个迭代的.对称密钥分组的密码,它可以使用128.192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据.与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据.通过分组密码返回的加密数据

  • 基于私钥加密公钥解密的RSA算法C#实现方法

    本文实例讲述了基于私钥加密公钥解密的RSA算法C#实现方法,是一种应用十分广泛的算法.分享给大家供大家参考之用.具体方法如下: 一.概述 RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一.RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价. RSA的安全性依赖于大数分解.公钥和私钥都是两个大素数( 大于 1

  • C#实现对文件进行加密解密的方法

    本文实例讲述了C#实现对文件进行加密解密的方法.分享给大家供大家参考.具体如下: using System; using System.IO; using System.Security.Cryptography; public class Example19_9 { public static void Main() { // Create a new file to work with FileStream fsOut = File.Create(@"c:\temp\encrypted.tx

  • c# 图片加密解密的实例代码

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO; namespace Net.Template.Common{/// <summary>/// 对图片的加密和解密/// </summary>public class DEncrypt4ImageHelper{public DEncr

  • C#加密解密类实例程序

    前两年写的东西,现在整理一下发出来!以前公司需要做WebService,并且对WebService的SoapHeader进行加密,所以就写了这么个东东!使用这个类,需要密钥管理!为了保证数据的安全性往往要对数据进行加密,但是加密的缺点之一,就是影响程序的运行效率,所以,当时我的思路是只对用户的登录信息(用户名,密码)进行加密!数据用明文传输,用户信息验证没有通过的情况下, 不进行数据传输.实际在网络通讯中,使用密钥匙的方式并非无懈可击,如果黑客可以捕捉到用密钥加密的,用户验证信息,然后,做个模拟

  • PHP加密解密类实例代码

    关键代码如下所示: <?php function i_array_column($input, $columnKey, $indexKey=null){ if(!function_exists('array_column')){ $columnKeyIsNumber = (is_numeric($columnKey))?true:false; $indexKeyIsNull = (is_null($indexKey))?true :false; $indexKeyIsNumber = (is_n

  • PHP实现加强版加密解密类实例

    本文实例讲述了PHP实现加强版加密解密类.分享给大家供大家参考.具体如下: <?php class Ender{ private $enkey;//加密解密用的密钥 private $rep_char='#'; //替换加密后的base64字符串中的=,因为=在有些场合是禁止使用的, //这里可以用一个允许的字符作为替换. //构造参数是密钥 public function __construct($key=''){ if(!$key){ $this->enkey=$key; } } //设置

  • PHP加密解密类实例分析

    本文实例讲述了PHP加密解密类.分享给大家供大家参考.具体分析如下: 这段代码支持 数组加密 , 密文有效期, 各种对称加密 其中参数如下: * @use ption::en($string, $key); * @param String $string 需要加密的字串 * @param String $skey 密钥 * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 * @return String 1. php代码如下: /* * -工具库-加

  • 基于php实现的php代码加密解密类完整实例

    本文实例讲述了基于php实现的php代码加密解密类.分享给大家供大家参考,具体如下: php 代码加密类,大家可以根据自己的需求进行修改,原类如下,该实例在ubuntu下测试没有问题. <?php class Encryption{ private $c='';//存储密文 private $s='',$q1,$q2,$q3,$q4,$q5,$q6;//存储生成的加密后的文件内容 //如果不设置一个值,isset会表示不存在: private $file='';//读取文件的路径 private

  • Java探索之Thread+IO文件的加密解密代码实例

    这篇文章向大家分享了几段代码,主要是关于Thread+IO文件的加密解密,下面看看具体代码: 加密启动线程 package com.hz.subsection; import java.io.File; public class enCodeFileThread extends Thread { public Files files; public File file; public File dst; public enCodeFileThread(String name,Files file

  • java中常用工具类之字符串操作类和MD5加密解密类

    java中常用的工具类之String和MD5加密解密类 我们java程序员在开发项目的是常常会用到一些工具类.今天我分享一下我的两个工具类,大家可以在项目中使用. 一.String工具类 package com.itjh.javaUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import

  • Java语言描述MD5加密工具类实例代码

    编程中经常有用到MD5加密的情况,Java语言并没有像PHP一样提供原生的MD5加密字符串的函数,需要MD5加密的时候,往往需要自己写. 代码如下: import java.security.MessageDigest; public class MD5 { //公盐 private static final String PUBLIC_SALT = "demo" ; //十六进制下数字到字符的映射数组 private final static String[] hexDigits =

  • java8版本base64加密解密的实例

    首先,先是加密,这里我使用了base64类 try { String asB64 = Base64.getEncoder().encodeToString("http://www.baidu.com".getBytes("utf-8")); System.out.println(asB64); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printSt

随机推荐