转自:http://www.16aspx.com/Article/3904

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);
}
}
}
}

C#做的一个加密/解密的类的更多相关文章

  1. php加密解密功能类

    这两天突发奇想想要用php写一个对日常项目加密以及解密的功能,经过努力简单的封装了一个对php代码进行加密解密的类,一些思想也是来自于网络,初步测试用着还行,可以实现对指定项目的加密以及解密(只针对本 ...

  2. C# MD5加密解密帮助类

    /// <summary>    /// MD5加密解密帮助类    /// </summary>    public static class DESHelper    {  ...

  3. php加密解密处理类

    [PHP]代码 <?php /*=========================================================== = 版权协议: = GPL (The GN ...

  4. AES加密解密 助手类 CBC加密模式

    "; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...

  5. .Net(c#)加密解密工具类:

    /// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { #region des实 ...

  6. Base64加密解密工具类

    使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...

  7. java 加密解密工具类(实用!!!)

    最近发现了一个加密解密的好例子,很方便使用,可以作为平时开发的工具集,记录一下. package com.sh.springboottdemo2.util; import com.sun.org.ap ...

  8. des 加密解密工具类

    最近在做des的双对称加密解密,特此记录一下. des对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码 ...

  9. 加密解密工具类(Java,DES)

    一个Java版的DES加密工具类,能够用来进行网络传输数据加密,保存password的时候进行加密. import java.security.Key; import java.security.sp ...

随机推荐

  1. C#值类型以及默认值记录下

    C#的值类型有bool,byte,sbyte,decimal,double,float,int,uint,long,string等 如果我们擅长使用默认值,可以帮助我们减少带来赋值及代码编写. 比如我 ...

  2. WCF大数据量传输解决方案

    文章内容列表:1. 场景:2. 解决方案3. WCF契约与服务实现设计静态图4. WCF契约与服务实现设计详细说明6. 服务端启动服务代码:7. 客户端代码8.   WCF大数据量传输解决方案源码下载 ...

  3. Go Hello World!

    有些事应该坚持去做 当你半途而废的时候意味着你又要重新开始.那么 Golang Hello world! Java Android 新手 学习 Golang  First Day ! go 语言下载: ...

  4. [BILL WEI]stimulsoft reports DEMO自动生成模板

    stimulsoft reports是一款强大的报表开发工具,能够开发各式各样的报表. 对于初学者而言,任何报表开发,刚开始都是去模仿,熟练掌握之后,自己才能独立开发,而在报表开发实际过程中, 我们所 ...

  5. 《C程序设计语言现代方法》第5章 编程题

    1 编写一个程序,确定一个数的位数. #include <stdio.h> int main() { ; ) { cnt++; } printf("%d\n", cnt ...

  6. html总结----------------------看这个就够了

    HTML是我们学习Javaweb的第一步 很好地掌握门课是非常有必要的!下面就是我在听资深老师讲课的笔记!个人觉得非常不错!希望可以帮助到那些在学习javaweb路上的 朋友们!从今天 陆续的整理这门 ...

  7. S3C2440触摸屏驱动实例开发讲解

    出处:http://www.embeddedlinux.org.cn/html/yingjianqudong/ 一.开发环境 主  机:VMWare--Fedora 9 开发板:Mini2440--6 ...

  8. 洛谷P1126 机器人搬重物

    洛谷1126 机器人搬重物 题目描述 机器人移动学会(RMI)现在正尝试用机器人搬运物品.机器人的形状是一个直径1.6米的球.在试验阶段,机器人被用于在一个储藏室中搬运货物.储藏室是一个N*M的网格, ...

  9. Android UI开发第三十二篇——Creating a Navigation Drawer

    Navigation Drawer是从屏幕的左侧滑出,显示应用导航的视图.官方是这样定义的: The navigation drawer is a panel that displays the ap ...

  10. hdu 1754 I Hate It (splay tree伸展树)

    hdu 1754 I Hate It 其实我只是来存一下我的splay模板的..请大牛们多多指教 #include<stdio.h> #include<string.h> #i ...