using System.Security;

using System.Security.Cryptography;
using System.IO;
using System.Runtime.InteropServices;

public byte[] HCDES(byte[] Key, byte[] Data)
{

//创建一个DES算法的加密类
DESCryptoServiceProvider MyServiceProvider = new DESCryptoServiceProvider();
MyServiceProvider.Mode = CipherMode.CBC;
MyServiceProvider.Padding = PaddingMode.None;
//从DES算法的加密类对象的CreateEncryptor方法,创建一个加密转换接口对象
//第一个参数的含义是:对称算法的机密密钥(长度为64位,也就是8个字节)
// 可以人工输入,也可以随机生成方法是:MyServiceProvider.GenerateKey();
//第二个参数的含义是:对称算法的初始化向量(长度为64位,也就是8个字节)
// 可以人工输入,也可以随机生成方法是:MyServiceProvider.GenerateIV()

//
ICryptoTransform MyTransform = MyServiceProvider.CreateEncryptor(Key, new byte[8]);

//CryptoStream对象的作用是将数据流连接到加密转换的流
MemoryStream ms = new MemoryStream();
CryptoStream MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write);
//将字节数组中的数据写入到加密流中


MyCryptoStream.Write(Data, 0, Data.Length);
//关闭加密流对象
byte[] bEncRet = new byte[8];
// Array.Copy(ms.GetBuffer(), bEncRet, ms.Length);
bEncRet = ms.ToArray(); // MyCryptoStream关闭之前ms.Length 为8, 关闭之后为16

MyCryptoStream.FlushFinalBlock();
MyCryptoStream.Close();
byte[] bTmp = ms.ToArray();
ms.Close();


// return bEncRet;
return bTmp;// 
}

public byte[] MAC_CBC(byte[] MacData)
{
int iGroup = 0;
byte[] bKey = HexStringToByteArray(textBoxKey.Text);

byte[] bIV = HexStringToByteArray(textBoxIV.Text);

byte[] bTmpBuf1 = new byte[8];
byte[] bTmpBuf2 = new byte[8];

// init

Array.Copy(bIV, bTmpBuf1, 8);

if ((MacData.Length % 8 == 0))
iGroup = MacData.Length / 8;
else
iGroup = MacData.Length / 8 + 1;

int i = 0;
int j = 0;

for ( i = 0; i < iGroup; i++)
{
Array.Copy(MacData, 8 * i, bTmpBuf2, 0, 8);
for (j = 0; j < 8; j++)
bTmpBuf1[j] = (byte)(bTmpBuf1[j] ^ bTmpBuf2[j]);
bTmpBuf2 = HCDES(bKey, bTmpBuf1);
Array.Copy(bTmpBuf2, bTmpBuf1, 8);
}

return bTmpBuf2;
}