using System; using System.Collections.Generic; using System.Linq;usingSystem.Text; using System.IO; using System.Security.Cryptography; namespace Rare.Card.Libary.Security {///<summary> ///构造一个对称算法,使用3Des加密 ///如果当前的Key属性为NULL,可调用GenerateKey方法以创建新的随机Key。 ///如果当前的IV属性为NULL,可调用GenerateIV方法以创建新的随机IV ///</summary> public class CryptoTripleDes {//加密矢量 private static byte[] IV={0xB0,0xA2,0xB8,0xA3,0xDA,0xCC,0xDA,0xCC};///<summary> ///使用指定的128字节的密钥对8字节数组进行3Des加密 ///</summary> ///<paramname="keys">密钥,16字节,128位</param> ///<paramname="values">要加密的数组</param> ///<returns>已加密的数组</returns> public static byte[] CreateEncryptByte(byte[] keys,byte[] values) { TripleDESCryptoServiceProvider tdsc=newTripleDESCryptoServiceProvider();//指定密匙长度,默认为192位 tdsc.KeySize=128;//使用指定的key和IV(加密向量) tdsc.Key=keys; tdsc.IV=IV;//加密模式,偏移 tdsc.Mode=CipherMode.ECB; tdsc.Padding=PaddingMode.None;//进行加密转换运算 ICryptoTransfor mct=tdsc.CreateEncryptor();//8很关键,加密结果是8字节数组 byte[]results=ct.TransformFinalBlock(values,0,8);returnresults; }///<summary> ///使用指定的128字节的密钥对字符串(8位)进行3Des加密///</summary> ///<paramname="strKey"></param> ///<paramname="strValue"></param> ///<returns></returns> public static byte[] CreateEncryptString(string strKey,string strValue) { TripleDESCryptoServiceProvider tdsc=newTripleDESCryptoServiceProvider(); byte[] results=new byte[strValue.Length]; tdsc.KeySize=128; if(!string.IsNullOrEmpty(strKey)) { tdsc.Key=Encoding.UTF8.GetBytes(strKey); } tdsc.IV=IV; using(ICryptoTransfor mct=tdsc.CreateDecryptor()) {byte[]byt=Encoding.UTF8.GetBytes(strValue); results=ct.TransformFinalBlock(byt,0,8); }return results; } ///<summary> ///对加密字符串进行解密///</summary> ///<paramname="keys">密匙</param> ///<paramname="values">已加密字符串</param> ///<returns>解密结果</returns> public static byte[] CreateDescryptByte(byte[]keys,byte[]values) { TripleDESCryptoServiceProvider tdsc=newTripleDESCryptoServiceProvider();//指定密匙长度,默认为192位 tdsc.KeySize=128;//使用指定的key和IV(加密向量) tdsc.Key=keys; tdsc.IV=IV;//加密模式,偏移 tdsc.Mode=CipherMode.ECB; tdsc.Padding=PaddingMode.None;//进行加密转换运算 ICryptoTransformct=tdsc.CreateDecryptor();//8很关键,加密结果是8字节数组 byte[]results=ct.TransformFinalBlock(values,0,8); return results; } } }
使用3DES加密算法对数据进行加密C#类
2015-08-30 22:42:27 来源: 网友分享