📄 mac.cpp
字号:
// MAC.cpp: implementation of the CMAC class.
//
//////////////////////////////////////////////////////////////////////
//#include "stdafx.h"
#include "MAC.h"
#include "des1.h"
#include <stdlib.h>
// ------------ CMAC::GetMac() ---------------
// 功能: 计算PBOC(IC卡)规范所定义的MAC
// 参数:
// [in] key: 密钥(8字节/16字节, 由nKeyLen标识)
// [in] nKeyLen: 密钥长度标识, 1-单长密钥 2-双长密钥
// [in] input: 待计算的数据块(长度任意,不需补齐)
// [in] nLen: 数据块的长度
// [in] random: 随机数(4字节)
// [in] bRandom: 随机数使用标志, TRUE-使用随机数, FALSE-不使用随机数
// [out] MAC: MAC计算结果(4字节)
// 返值:
// <void>
// 说明: 一般交易命令和通用命令中的MAC计算, 初值为8个'0x00',此时
// 应输入bRandom为FALSE, random为NULL. PBOC规范第二部分应用
// 维护功能的交易, MAC计算的初值为4字节随机数后缀以4个'0x00',
// 这种情况下,应输入bRandom为TRUE, random中应填入随机数
void GetMac1(unsigned char key[], int nKeyLen, unsigned char input[], int nLen, unsigned char random[], int bRandom, unsigned char MAC[])
{
int nBlock,i,j;
unsigned char temp[8];
unsigned char *buf;
if (nKeyLen <1 || nKeyLen > 2)
return;
/* 初始化MAC计算初值 ==> temp*/
memset(temp, 0, sizeof(temp));
if ( 1 == bRandom )
{
memcpy(temp, random, 8 * sizeof(unsigned char));
}
else
{
if (random != NULL)
return;
}
/* 格式化输入值: 填 "80 00 00 ...", 凑8字节长度 ==> buf*/
nBlock = nLen/8 + 1; /* 总块数*/
buf = (unsigned char *)malloc(nBlock*8);
memset(buf, 0, nBlock*8*sizeof(unsigned char));
memcpy(buf, input, nLen*sizeof(unsigned char));
buf[nLen] = 0x80;
for (i=0; i<nBlock; i++)
{
/* temp .EOR. block[i] ==> temp*/
for(j=0; j<8; j++)
{
temp[j] ^= buf[i*8+j];
}
/* temp ==> DES ==> temp*/
Encrypt(temp, key, temp);
}
free(buf);
if (nKeyLen == 2)
{
Decrypt(temp, &key[8], temp);
Encrypt(temp, key, temp);
}
/* temp 左四位 ==> MAC*/
memcpy(MAC, temp, 4 * sizeof(unsigned char));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -