文档库 最新最全的文档下载
当前位置:文档库 › 3DES加密与解密

3DES加密与解密

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

namespace Rare.Card.Libary.Security
{
///


/// 构造一个对称算法,使用3Des加密
///如果当前的 Key 属性为 NULL,可调用 GenerateKey 方法以创建新的随机 Key。
///如果当前的 IV 属性为 NULL,可调用 GenerateIV 方法以创建新的随机 IV
///

public class CryptoTripleDes
{
//加密矢量
private static byte[] IV = { 0xB0, 0xA2, 0xB8, 0xA3, 0xDA, 0xCC, 0xDA, 0xCC };
///
/// 使用指定的128字节的密钥对8字节数组进行3Des加密
///

/// 密钥,16字节,128位
/// 要加密的数组
/// 已加密的数组
public static byte[] CreateEncryptByte(byte[] keys, byte[] values)
{
TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();
//指定密匙长度,默认为192位
tdsc.KeySize = 128;
//使用指定的key和IV(加密向量)
tdsc.Key = keys;
tdsc.IV = IV;
//加密模式,偏移
tdsc.Mode = CipherMode.ECB;
tdsc.Padding = PaddingMode.None;
//进行加密转换运算
ICryptoTransform ct = tdsc.CreateEncryptor();
//8很关键,加密结果是8字节数组
byte[] results = ct.TransformFinalBlock(values, 0, 8);

return results;
}
///
/// 使用指定的128字节的密钥对字符串(8位)进行3Des加密
///

///
///
///
public static byte[] CreateEncryptString(string strKey, string strValue)
{
TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();
byte[] results = new byte[strValue.Length];
tdsc.KeySize = 128;
if (!string.IsNullOrEmpty(strKey))
{
tdsc.Key = Encoding.UTF8.GetBytes(strKey);
}
tdsc.IV = IV;
using (ICryptoTransform ct = tdsc.CreateDecryptor())
{
byte[] byt = Encoding.UTF8.GetBytes(strValue);
results = ct.TransformFinalBlock(byt, 0, 8);
}
return results;
}
///
/// 对加密字符串进行解密
///

/// 密匙
/// 已加密字符串
/// 解密结果
public static byte[] CreateDescryptByte(byte[] keys, byte[] values)
{
Tripl

eDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();

//指定密匙长度,默认为192位
tdsc.KeySize = 128;
//使用指定的key和IV(加密向量)
tdsc.Key = keys;
tdsc.IV = IV;
//加密模式,偏移
tdsc.Mode = CipherMode.ECB;
tdsc.Padding = PaddingMode.None;
//进行加密转换运算
ICryptoTransform ct = tdsc.CreateDecryptor();
//8很关键,加密结果是8字节数组
byte[] results = ct.TransformFinalBlock(values, 0, 8);

return results;
}
}
}

相关文档
相关文档 最新文档