Ejemplo n.º 1
0
//---------------------------------------------------------------------------
int OnPosGetTMK(QUEUE_LIST *pDataNode)     //获取终端主密钥,两个都返回给客户端由客户端保存到数据库,下载到母POS用的是TMK2,本服务器用TMK1
{
    thd_log(LOG_DEBUG,(char *)"OnPosGetTMK...Received Data:");
    trace_mem(LOG_DEBUG,(unsigned char *)pDataNode->Buffer,pDataNode->Length);
    unsigned char *pMSG = pDataNode->Buffer;     //MSG
    pMSG++;
    int iOffset = 0;
    int SIDLen = 0;
    char SID[51] = {0};
    SIDLen =pMSG[iOffset];
    if(SIDLen >50)     //SID最长50个字节
    {
        setCmdError(pDataNode);
        thd_log(LOG_WARNING,(char *)"OnPosGetTMK: SID Length is too long!");
        return 1;
    }
    iOffset += 1;
    memcpy(SID,&pMSG[iOffset],SIDLen);   //加密客户端只需传送SID长度和SID即可
    int TMKLen;

    char TMK1[49] = {0};
    char TMK2[49] = {0};
    char TMKCV[9] = {0};
    char OutBuf[1025] ={0}; //输出缓存
    //发送数据给加密机(0420指令) 获取TMK 并将区域主密钥2保护的密文保存到数据库 作为终端主密钥
    if(!PospGetTMK(TMK1,TMK2,&TMKLen,TMKCV,pDataNode) )
    {
        setCmdError(pDataNode);   //头尾在Pack函数中添加
        return 1;
    }
    //将获取到的数据组合到OutBuf中
    int iOutLen = 0;
    OutBuf[iOutLen] = pDataNode->Buffer[0];   //指令号CMD
    iOutLen++;
    OutBuf[iOutLen] = CMD_OK;    //执行SQL成功
    iOutLen++;
    OutBuf[iOutLen] = SIDLen;     //SID长度
    iOutLen++;
    memcpy(&OutBuf[iOutLen],SID,SIDLen) ;  //SID
    iOutLen += SIDLen;
    OutBuf[iOutLen] = TMKLen;         //终端主密钥长度
    iOutLen++;
    if(TMKLen > 48)
    {
        setCmdError(pDataNode);
        thd_log(LOG_WARNING,(char *)"OnPosGetTMK: TMK Length of POS is too long!");
        return 1;
    }
    memcpy(&OutBuf[iOutLen],TMK1,TMKLen) ;     //zmkindex保护的终端主密钥(客户端保存到数据库TMK1)
    iOutLen += TMKLen;
    memcpy(&OutBuf[iOutLen],TMK2,TMKLen) ;     //传输密钥保护的终端主密钥 (客户端保存到数据库TMK2)
    iOutLen += TMKLen;
    memset(pDataNode->Buffer,0,1024);
    memcpy(pDataNode->Buffer, OutBuf, iOutLen);
    pDataNode->Length = iOutLen ;
    thd_log(LOG_DEBUG,(char *)"OnPosGetTMK, Output Buffer Data:");
    trace_mem(LOG_DEBUG,(unsigned char *)pDataNode->Buffer,iOutLen);
   // thd_log("Output Buffer Data: %d",iOutLen);
    return 1;
}
Ejemplo n.º 2
0
int onGetZMK(QUEUE_LIST *pDataNode)     //传输密钥,通过几个密钥分量合成一个密钥并将此索引号的密钥存到加密机作为成员行的区域主密钥
{
    thd_log(LOG_DEBUG,(char *)"onGetZMK...Received Data:");
    trace_mem(LOG_DEBUG,(unsigned char *)pDataNode->Buffer,pDataNode->Length);
    unsigned char *pMSG = pDataNode->Buffer;     //MSG
    pMSG++;

    char OutBuf[1024];   // 输出缓存
    memset(OutBuf, 0, sizeof(OutBuf));
    if(!PospGetTransKey(pDataNode))
    {
        setCmdError(pDataNode);  //返回给客户端的数据不需要再加头和尾
        return 1;
    }
    int iOutLen = 0;
    memcpy(&OutBuf[iOutLen],&pDataNode->Buffer[0] ,1);    //指令号CMD
    iOutLen++;
    OutBuf[iOutLen] = CMD_OK;        //执行SQL成功
    iOutLen++;
    memset(pDataNode->Buffer,0,1024);
    memcpy(pDataNode->Buffer, OutBuf, iOutLen);
    pDataNode->Length = iOutLen ;
    thd_log(LOG_DEBUG,(char *)"onGetZMK, Output Buffer Data:");
    trace_mem(LOG_DEBUG,(unsigned char *)pDataNode->Buffer,iOutLen);
    return 1;
}
Ejemplo n.º 3
0
/** \brief
 *   磁道加密
 * \param in: tdb 磁道数据
 * \param in: key 磁道密钥
 * \param out: outdata 磁道加密数据
 * \return 失败返回-1,成功返回0
 */
int CTradeBase::Tdb_Encrypt(const BYTE *tdb, const BYTE *key, BYTE *outdata, int& outlen)
{
    if(!tdb || !key || !outdata)
    {
        trace_log(ERR, "Input parameter error!");
        return -1;
    }
	trace_log(DBG, "key is :");
	trace_mem(key, 16);

    char sTempTdb[256] = {0},sTmp[256]={0};
    unsigned char sTempOutData[256] = {0};
    unsigned char sTdb_bcd[128] = {0};
    unsigned char sTempOut[8] = {0};
    unsigned char sTempIn[8] = {0};
    int iLen = 0;
    int len = 0;

    len = strlen((char*)tdb);
    if(len<50)
    {/**< 二磁道 */
        sprintf(sTmp,"%02d",len);
        memcpy(sTempTdb,sTmp,2);
        memcpy(sTempTdb+2,tdb,len);
        len+=2;
    }else{/**< 3磁道 */
        sprintf(sTmp,"%04d%s",len,(char*)sTempTdb);
        memcpy(sTempTdb,sTmp,4);
        memcpy(sTempTdb+4,tdb,len);
        len+=4;
    }
    trace_log(DBG, "befor fill in: %s", sTempTdb);
    iLen = 16 * ( (len + 15) / 16 );
	for(int i = len; i < iLen; i++)
        sTempTdb[i] = '0';

    trace_log(DBG, "after fill in: %s", sTempTdb);
	Ccommon::Asc2Bcd(sTempTdb, sTdb_bcd, iLen, NL);


    for(int i = 0; i < iLen/16; i++)
    {
        memset(sTempOut, 0, 8);
        memcpy(sTempIn, sTdb_bcd+i*8, 8);
        des.THreeDes(sTempIn,key, sTempOut,ENCRYPT,TWO_3DES);
        memcpy(sTempOutData+i*8, sTempOut, 8);
    }
	trace_mem(sTempOutData, iLen/2);
    memcpy(outdata, sTempOutData, iLen/2);
    outlen = iLen/2;

    return 0;
}
Ejemplo n.º 4
0
/************************************************************************
函数功能:EnTrackData(加密银行端磁道数据)
参数说明: cRcvCode[in] 受理机构号
           cSndCode[in] 接入机构号
          cInData[in] 待处理数据
          cOutData[out] 处理后的数据
          iDataLen[in/out] 待处理数据长度/处理后的数据长度
返回值:  true 成功,false 失败
************************************************************************/
bool EnCryptComm::EnTrackData(char * cMercId, char * cTermId,
                 const unsigned char * cInData,
                 unsigned char * cOutData, int &iDataLen)
{
    unsigned char Buffer[1024]={0};
    unsigned iLen = 0, iTmpLen = 0;
    /**< CMD */
    Buffer[iLen++]=0x62;
    Buffer[iLen++] =1;

    /**< 受理机构号 */
    memset(&Buffer[iLen], ' ', 20);
    memcpy((char*)&Buffer[iLen], cMercId, strlen(cMercId));
    iLen += 20;

    /**< 接入机构号 */
    memset(&Buffer[iLen], ' ', 16);
    memcpy((char*)&Buffer[iLen], cTermId, strlen(cTermId));
    iLen += 16;
	/**< 初始向量*/
		memset(&Buffer[iLen], 0x00, 8);
    iLen += 8;

    /**< 加解密标志 */
    Buffer[iLen++] = 1;

	/**< 算法标识 */
    Buffer[iLen++] = 0;

    /**< 加解密数据 */
    iTmpLen = (iDataLen+7) /8 * 8 ;
    Buffer[iLen++]=iTmpLen/256;
    Buffer[iLen++] = iTmpLen%256;
    memcpy(&Buffer[iLen], cInData, iDataLen);
    iLen += iTmpLen;

		trace_log(DBG,"Buffer_enctdb len:%d",iLen);
    trace_mem(Buffer,iLen);

    if(!GetDataFromHsm(Buffer, iLen))
    {
        trace_log(ERR, "EnTrackData call GetDataFromHsm return false.");
        return false;
    }

    iLen = Buffer[LEN_MER_TERM+3]*256 + Buffer[LEN_MER_TERM+4];
    memcpy(cOutData, Buffer+LEN_MER_TERM+3+2, iLen);
    iDataLen = iLen;
    trace_log(DBG,"EnTrackData cOutData LEN=%d",iDataLen);
    trace_mem(cOutData,(iDataLen>100 ? 100 :iDataLen));
    return true;
}
Ejemplo n.º 5
0
/**< 跟第三方系统进行通信 */
int CTradeBase::DoSendAndRcv(unsigned char *ReqBuf, int ReqLen,unsigned char *RepBuf, int *RepLen, int TimeOut,char* errDesc)
{
    trace_log(DBG, "SndBuf len:%d",ReqLen);
    trace_mem(ReqBuf, ReqLen);
    SocketClient client;
    return client.SendToHost(ReqBuf,ReqLen,RepBuf,*RepLen,g_Cfg.CupHost.cIp,g_Cfg.CupHost.iPort,40,errDesc);
}
Ejemplo n.º 6
0
void DualTask(void* pData)
{
    QUEUE_LIST* pNode=(QUEUE_LIST*)pData;
    struct timeval tvBegin, tvEnd;
    gettimeofday(&tvBegin, NULL);   //计算数据在系统的处理时间
    int ret = SockDataProc(pNode);
    if(0 == ret)
    {
        trace_mem(pNode->Buffer, pNode->Length);
        bool bRet = FeedbackClient(pNode->SrvrPort, pNode->PeerSockId, pNode->Buffer, pNode->Length);
        if (!bRet)
            trace_log(ERR,"FeedbackClient failed. PeerSockId[%d]", pNode->PeerSockId);
        else
            trace_log(DBG,"FeedbackClient success. PeerSockId[%d]", pNode->PeerSockId);
    }
    trace_log(DBG,"SockDataProc return[%d]", ret);

    gettimeofday(&tvEnd, NULL);
    trace_log(DBG, "Port[%d] Peer[%d] transaction END! Elapsed: %d(ms)",pNode->SrvrPort, pNode->PeerSockId, diff_tv(&tvBegin, &tvEnd));
    if(pNode->Buffer)
    {
        delete []pNode->Buffer;
        pNode->Buffer=NULL;
    }

    if(pNode)
    {
        delete pNode;
        pNode=NULL;
    }

}
Ejemplo n.º 7
0
/** \brief
 * 接收数据
 * \param pDesc PDESC结构体
 * \param RecBuff 接收缓存
 * \param nRecLen 接收长度
 * \return  true:成功,false:失败
 */
bool ClientYinLian::RecvData(PDESC pDesc,unsigned char* RecBuff,int& nRecLen)
{
    try{
        int bytes_left;
        int bytes_read;
        unsigned char* ptr=RecBuff;

        bytes_left=nRecLen;
        while(bytes_left>0)
        {
            bytes_read = read(pDesc->socket_desc,ptr,bytes_left);
            trace_log(DBG,"cIp[%s],nPort[%d] socket[%d] start read bytes_read[%d] ",pDesc->cIp,pDesc->nPort,pDesc->socket_desc,bytes_read);
            if(bytes_read < 0)
            {
                if(errno==EINTR) {
                    bytes_read=0;
                }else if(errno==EAGAIN){
                    bytes_read=0;
                    break;
                } else {/**< 通讯异常 */
                    pDesc->bConn=false;
                    if(pDesc->socket_desc) {
											close(pDesc->socket_desc);
										}
                    pDesc->socket_desc=0;
                    nConn--;
                    nRecLen=0;
                    trace_log(ERR,"cIp[%s],nPort[%d] socket read err",pDesc->cIp,pDesc->nPort);
                    return false;
                }
            } else if(bytes_read==0){
                if(bytes_left == nRecLen)//< 服务器断开
                {
                    pDesc->bConn=false;
                    if(pDesc->socket_desc) {
											close(pDesc->socket_desc);
										}
                    pDesc->socket_desc=0;
                    nConn--;
                    nRecLen=0;
                    trace_log(ERR,"cIp[%s],nPort[%d] socket read err:%d[%s]",pDesc->cIp,pDesc->nPort,errno,strerror(errno));
                    return false;
                }
                break;
            }

            bytes_left -= bytes_read;
            trace_log(DBG,"RecvData:");
            trace_mem(ptr,bytes_read);
            ptr += bytes_read;
        }

        nRecLen-=bytes_left;
        pDesc->tIdle=time(0);
        return true;
    } catch(...){
        trace_log(ERR,"Error in ClientYinLian::RecvData()");
        return false;
    }
}
Ejemplo n.º 8
0
/************************************************************************
函数功能:CalculateMac(计算mac)--快钱
参数说明: cRcvCode[in] 受理机构号
          cSndCode[in] 接入机构号
          ucMab[in] 用于mac签名的数据
          iMabLen[in] 数据长度
          ucMac[out] mac值
返回值:  true 成功,false 失败
************************************************************************/
bool EnCryptComm::CalculateMac(char * cMercId, char * cTermId, const unsigned char * ucMab,
     int iMabLen, unsigned char * ucMac,int nFlag)
 {

	unsigned char ucTmpMab[1024]={0};

	memcpy(ucTmpMab, ucMab, iMabLen);
	int nMabLen = (iMabLen+7)/8*8;
	for(int i = iMabLen; i < nMabLen; i++)
		ucTmpMab[i] = 0x00;

	unsigned char Buffer[1024*2]={0};
	unsigned vLen = 0;

	/**< CMD */
	if(1==nFlag) {
        Buffer[vLen++] = 0x68;
  } else {
		Buffer[vLen++] = 0x61;
	}
	Buffer[vLen++] =1;

	 /**< 受理机构号 */
	memset(&Buffer[vLen], ' ', 20);
	memcpy((char*)&Buffer[vLen], cMercId, strlen(cMercId));
	vLen += 20;

	/**< 接入机构号 */
	memset(&Buffer[vLen], ' ', 16);
	memcpy((char*)&Buffer[vLen], cTermId, strlen(cTermId));
	vLen += 16;

	/**< MAC计算方式*/
	memset(&Buffer[vLen], 0x01, 1);
	vLen += 1;

	/**< 初始向量*/
	memset(&Buffer[vLen], 0x00, 8);
	vLen += 8;

	/**< MAB */
	Buffer[vLen++] = nMabLen/256;
	Buffer[vLen++] = nMabLen%256;
	memcpy((char*)&Buffer[vLen], ucTmpMab, nMabLen);
	vLen += nMabLen;

	if(!GetDataFromHsm(Buffer, vLen))
	{
		trace_log(ERR, "DesMac call GetDataFromHsm return false.");
		return false;
	}

	unsigned char ucMacTmp[9]={0};
	memcpy(ucMacTmp, Buffer+LEN_MER_TERM+3, 4);/**< 取前4个字节 */
	BcdToAsc(ucMac,ucMacTmp,4);
  trace_log(DBG,"CalculateMac ucMac LEN=%d",8);
  trace_mem(ucMac,8);
	return true;
}
Ejemplo n.º 9
0
/** \brief
 *   计算mab
 * \param in: pData TRADEDATA结构指针
 * \param in: obj8583 8583包
 * \param out: bMac 8字节
 * \return 失败返回非0,成功返回0
 */
int CTradeBase::GenMacData( TRADEDATA * pData,CUPS8583 obj8583,BYTE* bMac)
{
    int nLenMab=0,nLen=0;
    BYTE bMak[17]={0},bTmp[8]={0},bOut[8]={0};
    BYTE bMab[1024];
    nLenMab=BuildMab(obj8583,bMab);
	if(bSoftEncrypt)
    {
        /**< 软计算 */
        nLen=8*((nLenMab+7)/8);
        for(int i=nLenMab;i<nLen;i++)
            bMab[i]=0x00;
        Ccommon::Asc2Bcd(pData->bMacKey,bMak,  32);
        memcpy(bTmp,bMab,8);
        for(int i=0;i<nLen/8;i++)
        {
            des.DesEncrypt(ENCRYPT,bTmp,bMak,bOut);
            trace_log(DBG," EnDES: %d",i);
            trace_mem(bOut,8);
            if(i<nLen/8-1)
            {
                for( int j = 0;  j< 8 ; j++ )
                {
                    bTmp[j] = bOut[j] ^ bMab[(i+1)*8+j];
                }
            }
        }
        des.DesEncrypt(DECRYPT,bOut,bMak+8,bTmp);
        trace_log(DBG," DeDES:");
        trace_mem(bTmp,8);
        des.DesEncrypt(ENCRYPT,bTmp,bMak,bMac);
        trace_log(DBG," EnDES: ");
        trace_mem(bMac,8);
    }else{
         /**< 硬计算 */
        if(!cryptComm.CalculateMac(pData->RcvBrchCode,pData->SndBrchCode,bMab, nLenMab,bMac))
        {
            trace_log(ERR, "Get mac failed!");
            return RET_PACK;
        }
    }
    return 0;

}
Ejemplo n.º 10
0
/**< 跟第三方系统进行通信 */
int CTradeBase::DoSendAndRcv(unsigned char *ReqBuf, int ReqLen,unsigned char *RepBuf, int *RepLen, int TimeOut,char* errDesc)
{
    trace_log(DBG, "SndBuf len:%d",ReqLen);
    trace_mem(ReqBuf, ReqLen);
#ifndef USE_LONG_CONN
    SocketClient client;
    return client.SendToHost(ReqBuf,ReqLen,RepBuf,*RepLen,g_Cfg.CupHost[0].Host,g_Cfg.CupHost[0].Port,40,errDesc);
#else
	return 0;
#endif
}
Ejemplo n.º 11
0
/** \brief
 * 接收数据
 * \param pDesc PSIMPLEX_DESC结构体
 * \param RecBuff 接收缓存
 * \param nRecLen 接收长度
 * \return  true:成功,false:失败
 */
bool SimplexSock::RecvData(PSIMPLEX_DESC pDesc,unsigned char* RecBuff,int& nRecLen)
{
    try{
        int bytes_left;
        int bytes_read;
        unsigned char* ptr=RecBuff;

        bytes_left=nRecLen;
        while(bytes_left>0)
        {
            bytes_read=read(pDesc->socket_Recdesc,ptr,bytes_left);
            trace_log(DBG,"cIp[%s],nPort[%d] socket[%d] start read bytes_read[%d] ",pDesc->cIp,pDesc->nPort,pDesc->socket_Recdesc,bytes_read);
            if(bytes_read<0)
            {
                if(errno==EINTR)
                {
                    bytes_read=0;
                }else if(errno==EAGAIN){
                    bytes_read=0;
                    break;
                }else{/**< 通讯异常 */
                    //pDesc->nMask=0;
					pDesc->nRcvConnStatus = 0;
                    nRecLen=0;
                    trace_log(ERR,"cIp[%s],nPort[%d] socket read err",pDesc->cIp,pDesc->nPort);
                    return false;
                }
            }else if(bytes_read==0){
                if(bytes_left==nRecLen)/**< 服务器断开 */
                {
                    //pDesc->nMask=0;
					pDesc->nRcvConnStatus = 0;
                    nRecLen=0;
                    trace_log(ERR,"cIp[%s],nPort[%d] socket read err",pDesc->cIp,pDesc->nPort);
                    return false;
                }
                break;
            }
            bytes_left-=bytes_read;
            trace_log(DBG,"RecvData:");
            trace_mem(ptr,bytes_read);
            ptr+=bytes_read;
        }

        nRecLen-=bytes_left;
        pDesc->tRecIdle=time(0);
        return true;
    }catch(...){
        trace_log(ERR,"Error in ClientYinLian::RecvData()");
        return false;
    }
}
Ejemplo n.º 12
0
/*int CTradegetmainkey::GetMainCrypt(SAConnection *pSaconn,const BYTE *data,const BYTE* key, int nDataLen,TRADEDATA * pData)
{

	if(!data || nDataLen <= 0)
	{
		trace_log(ERR, "Input paramedter error!");
		return -1;
	}
	BYTE p[16+1] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
	BYTE temp_data[128] = {0};
	BYTE tkek[17] = {0};	//pin 密钥
	int nKeyLen = 16;  //密钥长度
    trace_log(DBG,"data Len:%d",nDataLen);


    //获取pin密钥明文
    memset((char *)temp_data,0x00,sizeof((char *)temp_data));
    memcpy( temp_data,data, 16);
    trace_log(DBG, "kek_data:");
    trace_mem(temp_data, 16);
	des.THreeDes(temp_data,key,tkek,DECRYPT,TWO_3DES);
	des.THreeDes(temp_data+8,key,tkek+8,DECRYPT,TWO_3DES);
    trace_log(DBG, "kek:");
    trace_mem(tkek, 16);
	memset((char *)temp_data,0x00,sizeof((char *)temp_data));
	des.THreeDes(p,tkek,temp_data,ENCRYPT,TWO_3DES);
	if(memcmp(temp_data,data+16,4) != 0) return 1;
	Ccommon::Hex2Str(tkek,(char *)pData->bMainKey,nKeyLen);

	return 0;
}*/
int CTradegetmainkey::GetMainCrypt(SAConnection *pSaconn,const BYTE *data,const BYTE* key, int nDataLen,TRADEDATA * pData)
{

	if(!data || nDataLen <= 0)
	{
		trace_log(ERR, "Input paramedter error!");
		return -1;
	}
	//BYTE p[16+1] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
	BYTE temp_data[128+1] = {0};
	BYTE temp_data1[128+1]={0};
	BYTE temp_data2[128+1]={0};
	BYTE temp_equal[16+1]={0};
	BYTE tkek[17] = {0};	//pin 密钥
	int nKeyLen = 16;  //密钥长度
    trace_log(DBG,"data Len:%d",nDataLen);


    //获取pin密钥明文
    memset((char *)temp_data,0x00,sizeof((char *)temp_data));
    memcpy( temp_data,data, 16);
    trace_log(DBG, "temp_data:");
    trace_mem(temp_data, 16);
	//des.THreeDes(temp_data,key,tkek,DECRYPT,TWO_3DES);
	//des.THreeDes(temp_data+8,key,tkek+8,DECRYPT,TWO_3DES);
    //res解密62域,用klk和C端密钥
	/*rsa_init(&rsa,RSA_PKCS_V15, 0 );
	rsa_gen_key(&rsa,NULL,NULL,1024,65537);
	rsa_public(&rsa,temp_data,temp_data1);*/
	memcpy(temp_data2,temp_data1,16);//取解密后饿前16字节
	des.THreeDes(temp_data2,tkek,temp_equal,ENCRYPT,TWO_3DES);
	des.THreeDes(temp_data2+8,tkek,temp_equal+8,ENCRYPT,TWO_3DES);//与16个0x00 进行3des加密
    trace_log(DBG, "kek:");
    trace_mem(tkek, 16);
    if(memcmp(temp_equal,data+16,4) != 0) return 1;//检查checkvalue
	Ccommon::Hex2Str(temp_data2,(char *)pData->bMainKey,nKeyLen);

	return 0;
}
Ejemplo n.º 13
0
/** \brief
 *   计算mab
 * \param in: pData TRADEDATA结构指针
 * \param in: obj8583 8583包
 * \param out: bMac 8字节
 * \return 失败返回非0,成功返回0
 */
int CTradeBase::GenMacData( TRADEDATA * pData,BYTE* bMabTmp,int bMabLen,BYTE* bMac)
{
    int nLenMab=0,nLen=0;
	int inum = 0;
    BYTE bMak[17]={0},bTmp[8]={0},bOut[8]={0},bMakTemp[8+1] = {0};
    BYTE bMab[1024],temp1[32] = {0},temp2[32] = {0};
    //nLenMab=BuildMab(obj8583,bMab);
    nLenMab = bMabLen;
    memcpy(bMab,bMabTmp,bMabLen);
	trace_log(DBG, "bMab,pData->RcvBrchCode:%s,pData->SndBrchCode:%s",pData->RcvBrchCode,pData->SndBrchCode);
	trace_mem(bMabTmp, bMabLen);
	if(bSoftEncrypt)
    {
        /**< 软计算 */
        nLen=8*((nLenMab+7)/8);
        for(int i=nLenMab;i<nLen;i++)
            bMab[i]=0x00;
		inum = nLen/8;
        Ccommon::Asc2Bcd((char *)pData->bMacKey,bMak,  32);
		memcpy(bMakTemp,bMak,8);
        memcpy(bTmp,bMab,8);
		for(int j = 1;j<inum;j++)
	    {
	        memset(bOut,0,8);
	        memcpy(bOut,bMab+j*8,8);
	        Ccommon::ExclusiveOR(bTmp,bOut,bTmp,8);
	    }
		BcdToAsc(temp1, bTmp, 16);
		memcpy(temp2,temp1,8);
		memset(bTmp,0x00,sizeof(bTmp));
		des.DesEncrypt(ENCRYPT, temp2, bMakTemp, bTmp);
		Ccommon::ExclusiveOR(bTmp,bTmp,temp1+8,8);
		memset(temp1,0x00,sizeof(temp1));
		des.DesEncrypt(ENCRYPT, bTmp, bMakTemp, temp1);
		BcdToAsc(temp2, temp1, 16);
		memcpy(bMac,temp2,8);
    }else{
         /**< 硬计算 */

        if(!cryptComm.CalculateMac(pData->RcvBrchCode,
                    pData->SndBrchCode,bMab, nLenMab,bMac))
        {
            trace_log(ERR, "Get mac failed!");
            return RET_PACK;
        }
    }
    return 0;

}
Ejemplo n.º 14
0
/** \brief
 *   构造mab
 * \param in: obj8583
 * \param out: bMab
 * \return 失败返回-1,成功返回bMab的长度
 * 备注:顺序不能更改
 */
int CTradeBase::BuildMab(CUPS8583 obj8583,BYTE* bMab )
{
    const int maxLen = 512;
    BYTE tempBuff[512] = {0};
    int len = 0, totalLen = 0;
    const int aField[10] = {2, 3, 4, 11, 12, 13, 49, 38, 39, 41};/**< 数组的秩序不能更改*/

	for(unsigned int i = 0; i < sizeof(aField)/sizeof(int); i++)
    {
        if(obj8583.FieldExist(aField[i]))
        {
            len = obj8583.GetValueByHex(aField[i], tempBuff, maxLen);
            trace_log(DBG, "field%d len:%d", aField[i], len);
            trace_mem(tempBuff, len);

            memcpy(bMab + totalLen, tempBuff, len);
            totalLen += len;
        }
    }

    trace_log(DBG, "mab len:%d",totalLen);
    trace_mem(bMab, totalLen);
    return totalLen;
}
Ejemplo n.º 15
0
/************************************************************************
函数功能:SetWorkKey(重置密钥)
参数说明: cRcvCode[in] 受理机构号
          cSndCode[in] 接入机构号
          ucWorkKey[in] 银联下发的工作密钥
          iWKLen[in] 密钥总长度
          iKeyType[in] 密钥类型
返回值:  true 成功,false 失败
************************************************************************/
bool EnCryptComm::SetWorkKey(char * cRcvCode, char * cSndCode, unsigned char * ucWorkKey, int iWKLen, int iKeyCnt)
{

    unsigned char Buffer[1024]={0};
    unsigned vLen = 0;

    /**< CMD */
    Buffer[vLen++] = 0x60;  /**< 快钱更新工作密钥 */
    Buffer[vLen++] =1;		//机构接入

	/**< 受理机构号 */
    memset(&Buffer[vLen], ' ', 20);
    memcpy((char*)&Buffer[vLen], cRcvCode, strlen(cRcvCode));
    vLen += 20;

    /**< 接入机构号 */
    memset(&Buffer[vLen], ' ', 16);
    memcpy((char*)&Buffer[vLen], cSndCode, strlen(cSndCode));
    vLen += 16;

	/**< 工作密钥 */
	Buffer[vLen++]=iWKLen;				//密钥总长度

	Buffer[vLen++]=16;
	memcpy(Buffer+vLen,ucWorkKey,16);
	vLen+=16;
	Buffer[vLen++]=4;
	memcpy(Buffer+vLen,ucWorkKey+16,4);
	vLen+=4;

	Buffer[vLen++]=8;
	memcpy(Buffer+vLen,ucWorkKey+20,8);
	vLen+=8;
	Buffer[vLen++]=4;
	memcpy(Buffer+vLen,ucWorkKey+28,4);
	vLen+=4;

    trace_log(DBG,"Buffer_workkey len:%d",vLen);
    trace_mem(Buffer,vLen);

    if(!GetDataFromHsm(Buffer, vLen))
		{
			trace_log(ERR, "SetWorkKey call GetDataFromHsm return false.");
			return false;
		}
    return true;
}
Ejemplo n.º 16
0
/************************************************************************
函数功能:SetWorkKey(设置快钱工作密钥)
参数说明: cRcvCode[in] 受理机构号
          cSndCode[in] 接入机构号
          ucWorkKey[in] 银联下发的工作密钥
          iWKLen[in] 密钥总长度
          iKeyCnt[in] 下发密钥个数
返回值:  true 成功,false 失败
************************************************************************/
bool EnCryptComm::SetWorkKey(char * cMercId, char * cTermId, unsigned char * ucWorkKey, int iWKLen, int iKeyCnt)
{

    unsigned char Buffer[1024]={0};
    unsigned vLen = 0;

    /**< CMD */
    Buffer[vLen++] = 0x60;  /**< 盛付通更新工作密钥 */
    Buffer[vLen++] =0;

	//此处有可能会换成商户号和终端号
     /**< 受理机构号 */
    memset(&Buffer[vLen], ' ', 20);
    memcpy((char*)&Buffer[vLen], cMercId, strlen(cMercId));
    vLen += 20;

    /**< 接入机构号 */
    memset(&Buffer[vLen], ' ', 16);
    memcpy((char*)&Buffer[vLen], cTermId, strlen(cTermId));
    vLen += 16;

   /**< 工作密钥 */
    Buffer[vLen++]=iWKLen;
    int nKey=0,nCheck=0;
    nKey=16;
    nCheck=4;
	for(int i=0;i<iKeyCnt ;i++)
	{
	    Buffer[vLen++] = nKey;
        memcpy(Buffer + vLen, ucWorkKey+(nKey+nCheck)*i, nKey);
		vLen += nKey;
		Buffer[vLen++] = nCheck;
	    memcpy(Buffer + vLen, ucWorkKey+nKey+(nKey+nCheck)*i, nCheck);
	    vLen+=nCheck;
	}

    trace_log(DBG,"Buffer_workkey len:%d",vLen);
    trace_mem(Buffer,vLen);

    if(!GetDataFromHsm(Buffer, vLen))
    {
        trace_log(ERR, "SetWorkKey call GetDataFromHsm return false.");
        return false;
    }
    return true;
}
Ejemplo n.º 17
0
/**从线程池收到的终端请求数据*/
int OnFromTerm(QUEUE_LIST *pDataNode)
{
    try
    {
        int ret;
        Dataprocess dataProcess;

        trace_mem(pDataNode->Buffer, pDataNode->Length);
        ms_delay(20);
        /**< 交易消息类型解包 */
        ret = dataProcess.Unpack(pDataNode->Buffer, pDataNode->Length);
        /**< 交易消息类型的业务处理*/
        if(ret==0)
        {
            trace_log(DBG, "Unpack package  success");
            //数据处理
            ret = dataProcess.Process();
            if(ret==0)
            {
                trace_log(DBG, "Trade process success");
            }else if(ret==-2){
                return -1;
            }else trace_log(DBG, "Trade process failed");

        }
        /**< 交易消息类型打包*/
        unsigned int iOutLen=ONE_PACKSIZE;
        ret = dataProcess.Pack(pDataNode->Buffer, iOutLen);
        pDataNode->Length=iOutLen;
        if(ret!=0)
        {
            trace_log(ERR, "pack package failed");
            return -1;
        }
        trace_log(DBG, "Pack package success");
        //if(dataProcess.myData.tradeType==POS_CONSUME)/**< 为了冲正的测试 */
        //{
        //  return -1;
        //}
        return 0;
    }catch(...){
        return -1;
    }
}
Ejemplo n.º 18
0
/** \brief
 *获取工作密钥(软解密获取)
 * \param in: data 48域数据
 * \param in:key  区域主密钥
 *\param in:nDataLen  48域数据长度
 *\param out:pData  工作密钥存放在TRADEDATA体
 * \return 成功为0,失败非0
 *
 */
int CTradeLogin::GetWorkCrypt(const BYTE *data,const BYTE* key, int nDataLen,TRADEDATA * pData)
{
	if(!data || nDataLen <= 0)
	{
		trace_log(ERR, "Input paramedter error!");
		return -1;
	}

	BYTE temp_data[128] = {0},tmpKey[64]={0};
	BYTE tpk[17] = {0};	//pin 密钥
	BYTE tak[17] = {0};	//mac 密钥
	BYTE tdk[17] = {0};	//磁道 密钥
	int nKeyLen = 16;  //密钥长度
    trace_log(DBG,"data Len:%d",nDataLen);
    if(nDataLen >= 165)
	{
	    //获取磁道密钥明文
	    memcpy( temp_data,(data+5), 32);
	    trace_log(DBG, "TrackKey_data:");
        trace_mem(temp_data, 32);
        Ccommon::Asc2Bcd((char*)temp_data,tmpKey,32);
        des.THreeDes(tmpKey,key,tdk,DECRYPT,TWO_3DES);
        des.THreeDes(tmpKey+8,key,tdk+8,DECRYPT,TWO_3DES);
        trace_log(DBG, "TrackKey:");
        trace_mem(tdk, nKeyLen);
        Ccommon::Hex2Str(tdk,pData->bTdkKey,nKeyLen);

        //获取pin密钥明文
	    memcpy( temp_data,(data+5+55), 32);
	    trace_log(DBG, "pinkey_data:");
        trace_mem(temp_data, 32);
        Ccommon::Asc2Bcd((char*)temp_data,tmpKey,32);
        des.THreeDes(tmpKey,key,tpk,DECRYPT,TWO_3DES);
        des.THreeDes(tmpKey+8,key,tpk+8,DECRYPT,TWO_3DES);
        trace_log(DBG, "pinkey:");
        trace_mem(tpk, nKeyLen);
        Ccommon::Hex2Str(tpk,pData->bPinKey,nKeyLen);

        //获取MAc密钥明文
	    memcpy( temp_data,(data+5+55*2), 32);
	    trace_log(DBG, "mackey_data:");
        trace_mem(temp_data, 32);
        Ccommon::Asc2Bcd((char*)temp_data,tmpKey,32);
        des.THreeDes(tmpKey,key,tak,DECRYPT,TWO_3DES);
        des.THreeDes(tmpKey+8,key,tak+8,DECRYPT,TWO_3DES);
        trace_log(DBG, "mackey:");
        trace_mem(tak, nKeyLen);
        Ccommon::Hex2Str(tak,pData->bMacKey,nKeyLen);
	}
	return 0;
}
Ejemplo n.º 19
0
/**************************************************************
函数名称: GetDataFromHsm
函数功能: 连接加密机从其获取数据
入口参数: pMsgBuffer[in/out]:发送或返回的数据中的MSG
           iLen[in/out]:发送或返回数据的长度
相关调用:
返 回 值: true成功, false失败
**************************************************************/
bool EnCryptComm::GetDataFromHsm(unsigned char *pMsgBuffer, unsigned & iLen)
{
    unsigned char cmd = pMsgBuffer[0], Buffer[1024]={0};
    unsigned sLen;//发送数据长度
    sLen = iLen + 7;
    memcpy(Buffer, &sLen, 2);//LC
    Buffer[2]=0xF1;//INS
    Buffer[3]=0;//SEQ
    //CR默认为0
    memcpy(&Buffer[6], pMsgBuffer, iLen);//MSG
    Buffer[sLen-1] = CalcSum(Buffer, sLen - 1);//CRC
    char errDesc[512]={0};
    unsigned char cRecBuf[1024]={0};
    int recLen=0;
    SocketClient client;
    int iErrorCode=client.SendToHost(Buffer,sLen,cRecBuf,recLen,g_Cfg.EncHost.Host, g_Cfg.EncHost.Port,20,errDesc);
    if(0==iErrorCode)
    {
    	trace_log(DBG, "recv from enchost");
		trace_mem(cRecBuf, recLen);
        if(cRecBuf[recLen-1] == CalcSum(cRecBuf, recLen - 1) && cRecBuf[6] == cmd && cRecBuf[8] == CMD_OK)
        {//校验值正确,与原命令字相同,返回码为成功
            if(memcmp(pMsgBuffer+2, cRecBuf+9, LEN_MERCHNO+LEN_TERMINO)!=0)//+LEN_TERMINO
            {//比较商户号与终端号
                trace_log(DBG, "The return data from encryptor is not match!!");
                return false;
            }
            memcpy(pMsgBuffer, cRecBuf+6, recLen-7);//去掉LC,INS,SEQ,CR,CRC
            iLen = recLen-7;
            trace_log(DBG,"GetDataFromHsm->iLen=%d",iLen);
            return true;
        }
        else
        {
            trace_log(ERR, "GetDataFromHsm else CalcSum  %d", recLen);
            return false ;
        }
    }else{
        trace_log(ERR,errDesc);
        return false;
    }
}
Ejemplo n.º 20
0
bool EnCryptComm::SetMainKey(char * cMercId, char * cTermId, unsigned char * ucWorkKey, int iWKLen)
{

    unsigned char Buffer[1024]={0};
    unsigned vLen = 0;

    /**< CMD */
    Buffer[vLen++] = 0x70;  /**< 盛付通更新终端主密钥 */
    Buffer[vLen++] =0;

	
     /**渠道商户号*/
    memset(&Buffer[vLen], ' ', 20);
    memcpy((char*)&Buffer[vLen], cMercId, strlen(cMercId));
    vLen += 20;

    /**渠道终端号*/
    memset(&Buffer[vLen], ' ', 16);
    memcpy((char*)&Buffer[vLen], cTermId, strlen(cTermId));
    vLen += 16;

   /**终端主密钥*/
    Buffer[vLen++]=16;
    memcpy((char*)&Buffer[vLen], ucWorkKey, 16);
	vLen += 16;
	Buffer[vLen++]=4;
    memcpy((char*)&Buffer[vLen], ucWorkKey+16, 4);
	vLen += 4;

    trace_log(DBG,"Buffer_workkey len:%d",vLen);
    trace_mem(Buffer,vLen);

    if(!GetDataFromHsm(Buffer, vLen))
    {
        trace_log(ERR, "SetWorkKey call GetDataFromHsm return false.");
        return false;
    }
    return true;
}
Ejemplo n.º 21
0
/** \brief
 * 发送数据
 * \param pDesc PSIMPLEX_DESC结构体
 * \param RecBuff 发送缓存
 * \param nRecLen 发送长度
 * \return  true:成功,false:失败
 */
bool SimplexSock::SndData(PSIMPLEX_DESC pDesc,unsigned char* ucSnd,int nSndSize)
{
    try{
        int bytes_left=0;
        int written_bytes=0;
        unsigned char* ptr=ucSnd;

        bytes_left=nSndSize;
        while(bytes_left>0)
        {
            written_bytes=write(pDesc->socket_Snddesc,ptr,bytes_left);
            if(written_bytes<=0) /* 出错了*/
            {
                trace_log(DBG,"errno[%d]",errno);
                if(errno==EINTR) /* 中断错误 我们继续写*/
                {
                    written_bytes=0;
                }else{             /* 其他错误 没有办法,只好撤退了*/
                    //pDesc->nMask=0;
					pDesc->nSndConnStatus=0;
                    trace_log(ERR,"cIp[%s],nPort[%d] socket write err",pDesc->cIp,pDesc->nPort);
                    return false;
                }
            }
            trace_log(DBG,"s:%d...",written_bytes);
            trace_mem(ptr,written_bytes);
            bytes_left-=written_bytes;
            ptr+=written_bytes;     /* 从剩下的地方继续写  */
        }
        pDesc->tSndIdle=time(0);
        return true;

    }catch(...){
        trace_log(ERR,"Error in ClientYinLian::SndData()");
        return false;
    }
}
Ejemplo n.º 22
0
//CMD_EXECSQL
//远程客户端请求执行SQL
//请求: [B0: 协议字] [B1:是否需要返回结果集] [B2~B5: 请求的起始记录号] [B6~B9: 最大返回的记录数] [B10~Bn: SQL语句]
//响应: [B0: 协议字] [B1: 执行结果0|1] [B2: 是否还有后续数据0|1] [B3..Bn: CDS结果集]
int OnExecSQL(QUEUE_LIST *pDataNode)
{
#ifdef _SUPPORT_CLITR   //支持客户端事务连接
    if (NULL != pDataNode->psaConn)
    {
        SAConnection *p = pDataNode->pCliTr->getCliTrConn(pDataNode->SrvrPort, pDataNode->PeerSockId);
        if (p) pDataNode->psaConn = p;
    }
#endif
    //报文(MSG)
    unsigned char *p = pDataNode->Buffer;
    p++;

    int iStartRecNo, iMaxCount, iSqlLen;
    bool bNeedReturnData = (*p == 1);
    p++;
    P2DW(iStartRecNo, p);
    p += 4;
    P2DW(iMaxCount, p);
    p += 4;
    P2W(iSqlLen, p);
    p += 2;
    if (iSqlLen > 8 * ONE_PACKSIZE)
    {
        setCmdError(pDataNode);
        return 1;
    }

    unsigned char *pSQL = (unsigned char *) GetMem(iSqlLen + 1);
    memcpy(pSQL, p, iSqlLen);
    pSQL[iSqlLen] = 0;

    thd_log(LOG_DEBUG,"Execute SQL: %s", pSQL);
    SACommand saCmd;
    try{
        saCmd.setConnection(pDataNode->psaConn);
        saCmd.setCommandText(_TSA(pSQL));
        saCmd.Execute();
    }
    catch(SAException &x)
    {
        thd_log( LOG_ERROR,(char *)"SQLAPI Exception %s", _T(x.ErrText()));
        setCmdError(pDataNode);
        return 1;
    }
    p = &pDataNode->Buffer[1];
    int iOutLen = 1;
    *p++ = CMD_OK;                                  //执行SQL成功
    iOutLen++;
    *p++ = 0x0;
    iOutLen++;

    //不需要返回数据
    if (!bNeedReturnData)
    {
        //m_pDataNode->psaConn->Commit();
        int rowUpd = saCmd.RowsAffected();          //更新的记录数
        W2P(p, rowUpd);
        iOutLen += 2;
        pDataNode->Length = iOutLen;
        FreeMem(pSQL);
        return 1;
    }

    bool bHasNext = false;
    p += 2;
    //返回数据
    int iRet = CopyDataSet(&bHasNext, p, ALL_PACKSIZE, &saCmd, iStartRecNo, iMaxCount);
    p -= 2;
    W2P(p, iRet);                                   //记录集大小
    if (bHasNext) pDataNode->Buffer[2] = 0x1;       //存在未返回记录
    iOutLen += 2 + iRet;
    pDataNode->Length = iOutLen;

    thd_log(LOG_DEBUG,"cdsfmt2 len = %d",pDataNode->Length);
    trace_mem( LOG_DEBUG,pDataNode->Buffer, pDataNode->Length);

    FreeMem(pSQL);
    return 1;
}
Ejemplo n.º 23
0
int CTradeLogin::DoTrade(SAConnection *saConn, void * pNode)
{

    if(saConn == NULL || pNode == NULL)
    {
        trace_log(ERR, "Paramter error!");
        return RET_SYSEXP;
    }
    trace_log(DBG,"-----Login-----");
    /********************pack********************/
    unsigned int g_nChnBatchNo;
    unsigned int g_nChnVouchNo;
    TRADEDATA * pData = (TRADEDATA *)pNode;
    /**< 获取流水号批次号及是否需要签到 */
	if(0 != COperateDB::GetChannelInfo(saConn, pData))
    {
        return RET_SYSEXP;
    }

    /**<处理流水号  */
    g_nChnVouchNo=atoi(pData->VouchNo);
    g_nChnBatchNo=atoi(pData->BatchNo);
    if(g_nChnVouchNo < 999999 && g_nChnVouchNo > 0)
    {
        g_nChnVouchNo++;
    }else{
        g_nChnVouchNo = 1;
        if(g_nChnBatchNo<999999)
        {
            g_nChnBatchNo++;
        }else g_nChnBatchNo=1;
    }
    sprintf(pData->BatchNo, "%06d", g_nChnBatchNo);
    sprintf(pData->VouchNo, "%06d", g_nChnVouchNo);

      /**< 回存流水号和批次号 */
    if(0 != COperateDB::SaveChannelInfo(saConn, pData))
    {
        trace_log(ERR, "DoGetVouchNo fail.");
        return RET_SYSEXP;
    }
    trace_log(DBG,"BatchNo:%s-----VouchNo:%s",pData->BatchNo,pData->VouchNo);
	if(!pData->bIsLogin) return 0;  //不需要签到时直接返回

    int iFieldDataLen = 0;
    bool bFlag = true;
    BYTE bFieldData[64] = {0};
    BYTE bKeyData[200] = {0};

    TRADEDATA pTmpData;
    memcpy(&pTmpData, pData, sizeof(TRADEDATA));
    pTmpData.TransData.HeadData.RTradeType = POS_SIGN;
    pTmpData.TransData.HeadData.nLFlowID = 0;

    CUPS8583 sndObj;
    //0消息类型
    bFlag &= sndObj.SetValueByStr(0, "0800");
    //3 处理码
    bFlag &= sndObj.SetValueByStr(3, "990000");
    //流水号
    bFlag &= sndObj.SetValueByStr(11, pTmpData.VouchNo);
    //NII
    bFlag &= sndObj.SetValueByStr(24, "009");
	//32 受理机构代码
	bFlag &= sndObj.SetValueByStr(32, pTmpData.RcvBrchCode);
    //33 发送机构代码
    if(strlen(pData->SndBrchCode) > 0)
        bFlag &= sndObj.SetValueByStr(33, pTmpData.SndBrchCode);
    //42	受卡方标识码
    bFlag &= sndObj.SetValueByStr(42, pTmpData.TransData.HeadData.arrRMerchNo);
    //61	自定义域
    sprintf((char *)bFieldData, "%s%s", pTmpData.BatchNo, "001");
    bFlag &= sndObj.SetValueByStr(61, (char *)bFieldData);
   /**< 插入交易记录 */
    /*if(COperateDB::MyBeforeInsertDB(saConn, &pTmpData))
    {
        trace_log(ERR, "MyBeforeInsertDB(login in) return failed!");
        return 	RET_SYSEXP;
    }*/
     /**< 模拟返回数据 */
    bFlag &= sndObj.SetValueByStr(39, "00");

    bFlag &= sndObj.SetValueByHex(48,ucFiled48,165);
    /**< 打包 */
    unsigned char SndBuf[PACK_MAXLEN]={0};
    unsigned iSndLen = sizeof(SndBuf);
    bFlag &= sndObj.Pack(SndBuf, iSndLen);
    if(!bFlag)
    {
        trace_log(ERR, "Pack right CUPS8583 fail!");
        return RET_PACK;
    }
    SetMsgHead(SndBuf, iSndLen, pData);/**<  设置报文头*/
    /********************communication********************/
    unsigned char RcvBuf[PACK_MAXLEN]={0};
    int iRcvLen = sizeof(RcvBuf);
    trace_log(DBG,"login SndBuf len[%d]:",iSndLen);
    trace_mem(SndBuf,iSndLen);
    /*char errDesc[512]={0};
    SocketClient client;
    if(0 !=  client.SendToHost(SndBuf,(int)iSndLen,RcvBuf,iRcvLen,g_Cfg.CupHost[0].Host,(int)g_Cfg.CupHost[0].Port,30,errDesc))
    {
        trace_log(ERR, errDesc);
        return RET_SYSEXP;
    }*/
    memcpy(RcvBuf,SndBuf,iSndLen);
    iRcvLen=iSndLen;
    trace_log(DBG,"login RcvBuf len[%d]:",iRcvLen);
    trace_mem(RcvBuf, iRcvLen);
    /********************unpack********************/
    CUPS8583 rcvObj;
    if(1 != rcvObj.UnPack(RcvBuf, iRcvLen))
    {
        trace_log(ERR, "unpack right CUPS8583 error!");
        return RET_UNPACK;
    }

    memset(bFieldData, 0, sizeof(bFieldData));
    /*iFieldDataLen = rcvObj.GetValueByStr(13, (char*)bFieldData, sizeof(bFieldData));
    if(iFieldDataLen <= 0)
    {
        trace_log(ERR, "GetValueByStr failed!(Field13)");
        return RET_MSGERR;
    }*/

    iFieldDataLen = rcvObj.GetValueByStr(39, pTmpData.TransData.HeadData.RspCode,sizeof(pTmpData.TransData.HeadData.RspCode));

    if(memcmp(pTmpData.TransData.HeadData.RspCode,"00",2)==0)
    {
        /**< 快钱下发的流水号和批次号 */
        iFieldDataLen = rcvObj.GetValueByHex(48, bKeyData, sizeof(bKeyData));
        if(iFieldDataLen >0)
        {
            if(bSoftEncrypt)
            {
                /**< 软加密 */
                trace_log(DBG, "filed48 len is %d, content is:",iFieldDataLen);
                trace_mem(bKeyData, iFieldDataLen);
                trace_log(DBG,"bAreakey");
                trace_mem(bAreakey,16);
                int nResult=GetWorkCrypt(bKeyData,bAreakey,iFieldDataLen,pData);
                if(nResult)
                {
                  trace_log(ERR, "check value failed!nResult = %d", nResult);
                  return RET_MSGERR;
                }

            }else{
                /**< 硬件加密 */
                char cWorkKey[256]={0},cTemp[256]={0};
                memcpy(cTemp,bKeyData+5+55,32);
                memcpy(cTemp+32,bKeyData+39+55,16);
                memcpy(cTemp+48,bKeyData+5+110,32);
                memcpy(cTemp+80,bKeyData+39+110,16);
                memcpy(cTemp+96,bKeyData+5,32);
                memcpy(cTemp+128,bKeyData+39,16);
                Ccommon::Asc2Bcd(cTemp,(BYTE*)cWorkKey,(32+16)*3);
                trace_log(DBG,"cWorkKeyLen = %d", (32+16)*3/2);
                trace_mem((unsigned char *)cWorkKey, (32+16)*3/2);
                if(!cryptComm.SetWorkKey(pTmpData.SndBrchCode,pTmpData.RcvBrchCode,(BYTE*) cWorkKey, (32+16)*3/2, 3))
                {
                    trace_log(ERR,"Set bank work key fail!");
                    return RET_RELOGIN;
                }
            }

        }else{
            trace_log(DBG,"sign in success ,Field[39]=%s",pTmpData.TransData.HeadData.RspCode);
            return RET_RELOGIN;
        }
        if(0 != COperateDB::UpdateTermalState(saConn, bFieldData, &pTmpData))
            return RET_SYSEXP;
    }else{
        trace_log(ERR, "login in  failed!");
        return RET_SYSEXP;
    }

    /*if(COperateDB::MyAfterUpdateDB(saConn, &pTmpData, (char)ST_SUCCESS, "00","成功"))
    {
        trace_log(ERR, "MyAfterUpdateDB (login in) return failed!");
        return RET_SYSEXP;
    }*/
    trace_log(DBG,"sign in success");
    return RET_SUCCESS;
}
Ejemplo n.º 24
0
/**< 解包 */
int Dataprocess::Unpack(unsigned char *PackageIn, unsigned int InLen)
{
    try
	{
        int iRet;
        memcpy(ucRecBuffer,PackageIn,InLen);		//for 冲正存储转发
        nRecDataLen	=	InLen;
        
		// 解包
        iRet = pMsg8583recv->UnPack(PackageIn, InLen);
        if(iRet != 1)
        {
            trace_log(ERR, "UnPack package failed!");
            pMsg8583recv->SetValueByStr(39,"30");			//报文格式错误
            pMsg8583recv->SetValueByStr(56,"报文格式错误");
            return -1;
        }
        trace_log(NML, "UnPack package success!");

        if(0 != GetFieldValue())
		{
			return -1;
		}
	
        // 校验MAC
        if(pMsg8583recv->FieldExist(64))
        {
            unsigned char 	Mac[16];
            unsigned char *	pMab 	= PackageIn + LENOFFSET + MSGTPDULEN + MSGHEADLEN;
            int 			MabLen 	= (int)InLen - LENOFFSET - MSGTPDULEN - MSGHEADLEN - MACLEN;

            trace_mem(pMab, MabLen);
            EnCrypt enCrypt;
            bool enc_ret = enCrypt.CalculateMac((char *)myData.cCardAccepCode, (char *)myData.cCardAccepTerm, pMab, MabLen, Mac);
            if( enc_ret )
            {
                if(memcmp(pMab + MabLen, Mac, MACLEN) != 0)
                {
                    trace_log(ERR, "check mac  error");
                    trace_mem(pMab + MabLen, MACLEN);
                    trace_mem(Mac, MACLEN);
                    pMsg8583recv->SetValueByStr(39,"A0");//MAC校验错误
                    pMsg8583recv->SetValueByStr(56,"MAC校验错误");//MAC校验错误
                    return -1;
                }
                trace_log(NML, "check mac success!");
            }
			else
			{
                trace_log(ERR, "check mac  failed");
                pMsg8583recv->SetValueByStr(39,"A0");//MAC校验错误
                pMsg8583recv->SetValueByStr(56,"MAC校验错误2");//MAC校验错误
                return -1;
            }
        }
        return 0;
    }
	catch(...)
	{
        trace_log(SYS, "Error in Dataprocess::UnPack");
        pMsg8583recv->SetValueByStr(39,"ZZ");//交易失败
        pMsg8583recv->SetValueByStr(56,"System Exception:UpPack err");
        return -1;
    }
}
Ejemplo n.º 25
0
/** \brief
 * 解包处理
 * \param pBuff 缓存数据
 * \param  nWrite 写数据位置
 * \param  nRead 读数据位置
 * \return TRUE 成功,false 失败
 */
bool SimplexSock::UpPack(const unsigned char* pBuff,int nWrite,int& nRead)
{
    try{
        char cPreData[5]={0};
        unsigned char ucBuff[4096]={0};
        int nIsoLen=0,nLeave=0,nRight=0;
        int nReadTmp=0;
        int nRes=0;
        while(1)
        {
           nLeave=nWrite>=nRead?(nWrite- nRead ):(nSglRead*16 - nRead +nWrite);
           if(nLeave<4)
           {
               return true;
           }
           nReadTmp=nRead;

           /**< 报文长度 */
           nRight=nSglRead*16-nReadTmp;
           if(nRight<4)
           {
                memcpy(cPreData,pBuff+nReadTmp,nRight);
                nReadTmp=4-nRight;
                memcpy(cPreData+nRight,pBuff,nReadTmp);
           }else{
                memcpy(cPreData,pBuff+nReadTmp,4);
                nReadTmp+=4;
           }
            nIsoLen=atoi(cPreData);
            if(0==nIsoLen)
            {
                nRead=nReadTmp;
                return true;
            }
           /**< 8583包的长度错误 */
           if(nIsoLen<46||nIsoLen>1892)
           {
               trace_log(ERR,"nIsoLen[%d] no between[46,1892]",nIsoLen);
               return false;
           }

            /**< 报文 */
           if(nLeave<nIsoLen)
           {
               return true;
           }
           nRight=nSglRead*16-nReadTmp;
           memcpy(ucBuff,cPreData,4);
           if(nRight<nIsoLen)
           {
                memcpy(ucBuff+4,pBuff+nReadTmp,nRight);
                nReadTmp=nIsoLen-nRight;
                memcpy(ucBuff+4+nRight,pBuff,nReadTmp);
           }else{
                memcpy(ucBuff+4,pBuff+nReadTmp,nIsoLen);
                nReadTmp+=nIsoLen;
           }
           /**< 解包 */
           nRead=nReadTmp;
           PRECVDATA pRecvData=new RECVDATA;
           memset(&pRecvData->checkData,0,sizeof(pRecvData->checkData));
           if(ucBuff[44]!='2'&&0!=memcmp(ucBuff+45,"0000",4))
           {
                pRecvData->iso.m_pIFF->m_pMF->iHeadLen=2*pRecvData->iso.m_pIFF->m_pMF->iHeadLen;
           }
           trace_log(DBG,"UnPack ucBuff:");
           trace_mem(ucBuff,nIsoLen+4);
           nRes=pRecvData->iso.UnPack(ucBuff, nIsoLen+4);
           if(1!=nRes)
           {
               trace_log(ERR,"UnPack iso8583 faile");
               delete pRecvData;
               pRecvData=NULL;
               return false;
           }else{
               char cTmp[64]={0};
               pRecvData->checkData.tTime=time(0);

               memset(cTmp,0,sizeof(cTmp));
               pRecvData->iso.GetValueByStr(0,cTmp,sizeof(cTmp));
               strcpy(pRecvData->checkData.cMsgType,cTmp);

               if(pRecvData->iso.FieldExist(2))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(2,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cAccount,cTmp);
               }

               if(pRecvData->iso.FieldExist(4))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(4,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cAmount,cTmp);
               }

               if(pRecvData->iso.FieldExist(7))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(7,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cTransTime,cTmp);
               }

               if(pRecvData->iso.FieldExist(11))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(11,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cTraceNo,cTmp);
               }

               if(pRecvData->iso.FieldExist(41))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(41,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cTermNo,cTmp);
               }

               if(pRecvData->iso.FieldExist(42))
               {
                   memset(cTmp,0,sizeof(cTmp));
                   pRecvData->iso.GetValueByStr(42,cTmp,sizeof(cTmp));
                   strcpy(pRecvData->checkData.cMerchNo,cTmp);
               }

               LockListRecv();
               listRecv.push_back(pRecvData);
               UnLockListRecv();
           }
        }
        return true;
    }catch(...){
        trace_log(ERR,"Error in ClientYinLian::PushToYinLian()");
        return false;
    }
}
Ejemplo n.º 26
0
/**< 拆包并处理 */
int CTradeBase::DoUnpack(SAConnection *saConn, void * pNode,unsigned char * pBuffer, unsigned & iBufLen)
{
    if(saConn == NULL || pNode == NULL || pBuffer == NULL)
    {
        trace_log(ERR, "Parameter error.");
        return RET_PROERR;
    }
    TRADEDATA * pData = (TRADEDATA *)pNode;


    trace_log(DBG,"Receive  data[%d]:",iBufLen);
    trace_mem(pBuffer, iBufLen);
    /**< 拆响应包 */
    if(1 != rcvObj.UnPack(pBuffer, iBufLen))
    {
        trace_log(ERR, "unpack CUPS8583 error!");
        if( 0==strlen(pData->TransData.HeadData.RspCode)) memcpy(pData->TransData.HeadData.RspCode,"96",2);
        if(0 != COperateDB::MyAfterUpdateDB(saConn, (TRADEDATA *)pNode, (char)ST_FAILURE,pData->TransData.HeadData.RspCode, ""))
        {
            trace_log(ERR, "Call DoUpdate fail!");
        }
        return RET_UNPACK;
    }
    /**< 取响应数据 */
    char Account[22]={0}, Amount[14]={0}, DateTime[16]={0};
    char SysNo[14]={0}, AuthCode[8]={0}, RspCode[6]={0}, cTmpData[128]={0};
    char Balance[32]={0}, ExpDate[6]={0},cLinvNo[7]={0},cTmlNo[9]={0},cMercNo[16]={0};
    unsigned char uICFiled55[256]={0};
    int  iDataLen;

    bool bNormal=true;/**< 为了校对账号、金钱、流水号、终端号、商务号是否对应*/
    if(rcvObj.FieldExist(2)&&(POS_UNCONSUME>(int)pData->TransData.HeadData.RTradeType||(int)pData->TransData.HeadData.RTradeType>=POS_PAYBACK ))
    {
        rcvObj.GetValueByStr(2 , Account, sizeof(Account));
        if(0!=strcmp(Account,pData->TransData.HeadData.Account))/**< 校对账号 */
        {
            trace_log(ERR,"recAccount[%s]!=sndAccount[%s]",Account,pData->TransData.HeadData.Account);
            bNormal=false;
        }
    }
    if(rcvObj.FieldExist(4)&&POS_QUERY!=(int)pData->TransData.HeadData.RTradeType )
    {
        rcvObj.GetValueByStr(4 , Amount, sizeof(Amount));
        if(0!=strcmp(Amount,pData->TransData.HeadData.ReqAmount)) /**< 校对金额 */
        {
            trace_log(ERR,"recAmount[%s]!=sndAmount[%s]",Amount,pData->TransData.HeadData.ReqAmount);
            bNormal=false;
        }
    }

    if(rcvObj.FieldExist(11) &&POS_UNCONSUME>(int)pData->TransData.HeadData.RTradeType &&
								POS_PAYBACK<=(int)pData->TransData.HeadData.RTradeType)
    {
        rcvObj.GetValueByStr(11,cLinvNo,sizeof(cLinvNo));
        if(0!=strcmp(cLinvNo,pData->VouchNo))         /**< 校对流水号 */
        {
            trace_log(ERR,"recLinvNo[%s]!=sndLinvNo[%s]",cLinvNo,pData->VouchNo);
            bNormal=false;
        }
    }
    if( rcvObj.FieldExist(12)&&rcvObj.FieldExist(13)) /**< 交易日期和时间 */
    {
        rcvObj.GetValueByStr(13, DateTime, sizeof(DateTime));
        rcvObj.GetValueByStr(12, DateTime+4, sizeof(DateTime)-4);
    }

    rcvObj.GetValueByStr(14, ExpDate, sizeof(ExpDate));
    if(rcvObj.FieldExist(15))rcvObj.GetValueByStr(15,pData->TransData.HeadData.SettDate,sizeof(pData->TransData.HeadData.SettDate));
    rcvObj.GetValueByStr(37, SysNo, sizeof(SysNo));
    memcpy(pData->TransData.HeadData.SysRefNo, SysNo,strlen(SysNo));
    rcvObj.GetValueByStr(38, AuthCode, sizeof(AuthCode));
    memcpy(pData->TransData.HeadData.OrigAuthCode, AuthCode,strlen(AuthCode));
    if(rcvObj.FieldExist(41) )
    {
        rcvObj.GetValueByStr(41,cTmlNo,sizeof(cTmlNo));
        if(0!=strcmp(cTmlNo,pData->TransData.HeadData.arrRTermNo)) /**< 校对终端号 */
        {
            trace_log(ERR,"recTermNo[%s]!=sndTermNo[%s]",cTmlNo,pData->TransData.HeadData.arrRTermNo);
            bNormal=false;
        }
    }
    if(rcvObj.FieldExist(42) )
    {
        rcvObj.GetValueByStr(42,cMercNo,sizeof(cMercNo));
        if(0!=strcmp(cMercNo,pData->TransData.HeadData.arrRMerchNo)) /**< 校对商务号 */
        {
            bNormal=false;
        }
    }



    if(!bNormal &&POS_QUERY!=(int)pData->TransData.HeadData.RTradeType)  /**< 为了校对账号、金钱、流水号、终端号、商务号是否对应*/
    {
        trace_log(ERR,"Check Account,monney,linv,termNo,merchNo err");
        char status = (char)ST_FAILURE;
        memcpy(RspCode,"96",2);
        memcpy(pData->TransData.HeadData.RspCode, RspCode,2);
        if(0 != COperateDB::MyAfterUpdateDB(saConn, (TRADEDATA *)pNode, status, RspCode,""))
        {
            trace_log(ERR, "DoUpdate fail!");
            return RET_SYSEXP;
        }
        return RET_SYSEXP;
    }

    if(strlen(Amount) > 0)
    {
		if(atoi(Amount))
		{
          memcpy(pData->TransData.HeadData.ReqAmount, Amount,strlen(Amount));/**< 交易金额 */
	    }
	}
	else
    {
        iDataLen = rcvObj.GetValueByStr(54, cTmpData, sizeof(cTmpData));
        if(iDataLen > 0)
        {
	        strncpy(Balance, cTmpData + strlen(cTmpData) - 12, 12);
            strncpy(pData->TransData.HeadData.ReqAmount, Balance, 12);
        }
    }

    /**<  解TLV */
    CTLVTemplet tlvObj;
    int iFlag = -1;
    iFlag = tlvObj.UnPackTLVData(pData->TransData.TlvDataLen, pData->TransData.TlvData);
    if(1 != iFlag)
    {
        trace_log(ERR, "UnPackTLVData fail.");
        return -1;
    }

    tlvObj.AddTLVItemByEnum(TAG_ACCOUNT, strlen(Account), (unsigned char *)Account);
    if(strlen(Amount) > 0)
    {
        tlvObj.AddTLVItemByEnum(TAG_AMOUNT, strlen(Amount), (unsigned char *)Amount);
    }else if(strlen(Balance) > 0){
        tlvObj.AddTLVItemByEnum(TAG_AMOUNT, strlen(Balance), (unsigned char *)Balance);
    }
    tlvObj.AddTLVItemByEnum(TAG_DATETIME, strlen(DateTime), (unsigned char *)DateTime);/**< 交易日期和时间 */
    tlvObj.AddTLVItemByEnum(TAG_SYSNO, strlen(SysNo), (unsigned char *)SysNo);
    tlvObj.AddTLVItemByEnum(TAG_AUTHNO, strlen(AuthCode), (unsigned char *)AuthCode);

    if(rcvObj.FieldExist(55) ) /**< 把相应的55域返回给pos */
    {
        iDataLen=rcvObj.GetValueByHex(55,uICFiled55,sizeof(uICFiled55));
        tlvObj.AddTLVItemByEnum(TAG_FIELD55_RSP,iDataLen,uICFiled55);
    }

    if (strlen(ExpDate) <=0 ) strncpy(ExpDate, "0000", 4);
    tlvObj.AddTLVItemByStr(TAG_EXPDATE, strlen(ExpDate), (unsigned char *)ExpDate);

   /**< 打包tlv数据 */
    pData->TransData.TlvDataLen = TLV_DATA_MAX_LEN;
    if(1 != tlvObj.PackTLVData(pData->TransData.TlvData, (unsigned &)pData->TransData.TlvDataLen ))
    {
        trace_log(ERR, "PackTLVData fail.");
        return RET_SYSEXP;
    }

    rcvObj.GetValueByStr(39, RspCode, sizeof(RspCode));
    trace_log(DBG,"Response code[%s]!", RspCode);
    memcpy(pData->TransData.HeadData.RspCode, RspCode,2);

   /**< 处理返回码及错误提示信息 */
    char status = strncmp(RspCode, "00", 2) == 0 ? (char)ST_SUCCESS : (char)ST_FAILURE;
    char cRepDesc[128]={0};
	char cRepDescbuff[128]= {0};
    if( status!=ST_SUCCESS&&rcvObj.FieldExist(44) )
    {
        rcvObj.GetValueByStr(44,cRepDescbuff,sizeof(cRepDescbuff));
		Ccommon::RemoveBeforChar((unsigned char *)cRepDesc, (unsigned char *)cRepDescbuff, 0x20, strlen(cRepDescbuff));
		trace_log(DBG, "cRepDesc = %s",cRepDesc);
        memcpy(pData->TransData.HeadData.RspDecs,cRepDesc,strlen(cRepDesc));
    }else{
        string sMapKey;
        map<string,string>::iterator itor;
        sMapKey.append(RspCode);
        itor=errorMap.find(sMapKey);
        if(itor!=errorMap.end())
        {
           strcpy(cRepDesc,itor->second.c_str());
           memcpy(pData->TransData.HeadData.RspDecs,cRepDesc,strlen(cRepDesc));
        }
    }
     /**< 更新交易记录 */
    if(0 != COperateDB::MyAfterUpdateDB(saConn, (TRADEDATA *)pNode, status, RspCode,cRepDesc))
    {
        trace_log(ERR, "DoUpdate fail!");
        memcpy(pData->TransData.HeadData.RspCode,"96",2);;
        return RET_SYSEXP;
    }

    if(!strncmp(RspCode, "63", 2)) return RET_MACERR; /**< 快钱MAC校验出错重新签到 */

    trace_log(DBG, "deal success.");
    return RET_SUCCESS;
}
Ejemplo n.º 27
0
int CTradegetmainkey::DoTrade(SAConnection *saConn, void * pNode)
{

    if(saConn == NULL || pNode == NULL)
    {
        trace_log(ERR, "Paramter error!");
        return RET_SYSEXP;
    }
    trace_log(DBG,"-----getmainkey-----");
    /********************pack********************/
    TRADEDATA * pData = (TRADEDATA *)pNode;

    int iFieldDataLen = 0;
    bool bFlag = true;
    BYTE bFieldData[64] = {0};
    BYTE bKeyData[200] = {0};
    trace_log(DBG,"pack 8583");

    TRADEDATA pTmpData;
    memcpy(&pTmpData, pData, sizeof(TRADEDATA));
    pTmpData.TransData.HeadData.RTradeType = POS_GETMAINKEY;
    pTmpData.TransData.HeadData.nLFlowID = 0;

    CUPS8583 sndObj;
    //0消息类型
    bFlag &= sndObj.SetValueByStr(0, "0820");
	 //41	受卡机终端标识码
    bFlag &= sndObj.SetValueByStr(41, pTmpData.TransData.HeadData.arrRTermNo);

    //42	受卡方标识码
    bFlag &= sndObj.SetValueByStr(42, pTmpData.TransData.HeadData.arrRMerchNo);
    //60	自定义域
    memcpy(bFieldData,"00",2);
	strcat((char *)bFieldData,(char *)pData->BatchNo);
	strcat((char *)bFieldData,(char *)"102");
    bFlag &= sndObj.SetValueByStr(60, (char *)bFieldData);
    //62域 秘钥信息
    /*BYTE fieldData62[120]={0};
    memset(fieldData62,20,15);//ip地址
    strcat((char *)fieldData62,"00000000000000000000");//sim卡号
    strcat((char *)fieldData62,"0000.00.00");
    strcat((char *)fieldData62,"0000.00.00");
    strcat((char *)fieldData62,"460");
    strcat((char *)fieldData62,"00");
    strcat((char *)fieldData62,"0000");
    strcat((char *)fieldData62,"0000");
    strcat((char *)fieldData62,"00000000000000000000000000000000");*/

    /*rsa_init(&rsa,RSA_PKCS_V15, 0 );
    rsa_gen_key(&rsa,NULL,NULL,1024,65537);
    rsa_public(&rsa,KLK,bFieldData);*/
    bFlag &=sndObj.SetValueByHex(62,bFieldData,100);
   /**< 插入交易记录 */
    if(COperateDB::MyBeforeInsertDB(saConn, &pTmpData))
    {
        trace_log(ERR, "MyBeforeInsertDB(getmainkey) return failed!");
        return 	RET_SYSEXP;
    }

    /**< 打包 */
    unsigned char SndBuf[PACK_MAXLEN]={0};
    unsigned iSndLen = sizeof(SndBuf);
    bFlag &= sndObj.Pack(SndBuf, iSndLen);
    if(!bFlag)
    {
        trace_log(ERR, "Pack right CUPS8583 fail!");
        return RET_PACK;
    }

    SetMsgHead(SndBuf, iSndLen, pData);/**<  设置报文头*/
    /********************communication********************/
    unsigned char RcvBuf[PACK_MAXLEN]={0};
    int iRcvLen = sizeof(RcvBuf);
    trace_log(DBG,"getmainkey SndBuf len:",iSndLen);
    trace_mem(SndBuf,iSndLen);
    char errDesc[512]={0};
    SocketClient client;
    if(0 !=  client.SendToHost(SndBuf,(int)iSndLen,RcvBuf,iRcvLen,g_Cfg.CupHost[0].Host,(int)g_Cfg.CupHost[0].Port,60000,errDesc))
    {
        trace_log(ERR, errDesc);
        return RET_SYSEXP;
    }
    /********************unpack********************/
	trace_log(DBG,"RcvBuf len:",iRcvLen);
    trace_mem(RcvBuf,iRcvLen);
    CUPS8583 rcvObj;
    if(1 != rcvObj.UnPack(RcvBuf, iRcvLen))
    {
        trace_log(ERR, "unpack right CUPS8583 error!");
        return RET_UNPACK;
    }

    iFieldDataLen = rcvObj.GetValueByStr(39, pTmpData.TransData.HeadData.RspCode,
                                          sizeof(pTmpData.TransData.HeadData.RspCode));
    if(iFieldDataLen != 2)
    {
        trace_log(ERR, "GetValueByStr fail!(Field39)");
        return RET_MSGERR;
    }
    if(memcmp(pTmpData.TransData.HeadData.RspCode,"00",2)==0)
    {
    	iFieldDataLen = rcvObj.GetValueByStr(62, (char *)bKeyData,sizeof(bKeyData));
        if(bSoftEncrypt)
        {
            /**< 软加密 */
            trace_log(DBG, "filed62 len is %d, content is:",iFieldDataLen);
            trace_mem(bKeyData, iFieldDataLen);
            trace_log(DBG,"bKek");
            trace_mem(bKek,16);
            int nResult=GetMainCrypt(saConn,bKeyData,bKek,iFieldDataLen,&pTmpData);
			/*拷贝密钥否则签到是密钥无法使用*/
			memcpy(pData->bMacKey,pTmpData.bMacKey,32);
			memcpy(pData->bPinKey,pTmpData.bPinKey,32);
			memcpy(pData->bTdkKey,pTmpData.bTdkKey,32);
			memcpy(pData->bMainKey,pTmpData.bMainKey,32);
            if(nResult)
            {
              trace_log(ERR, "check value failed!nResult = %d", nResult);
              return RET_MSGERR;
            }

        }
		else
		{
			if(!cryptComm.SetMainKey(pData->TransData.HeadData.arrRMerchNo,pData->TransData.HeadData.arrRTermNo,bKeyData,iFieldDataLen))
            {
                trace_log(ERR, "Call TranslatePin fail!");
                return RET_SYSEXP;
            }
		}
        if(0 != COperateDB::UpdateMainKey(saConn, &pTmpData))
            return RET_SYSEXP;
    }else{
        trace_log(ERR, "getmainkey  failed!");
        return RET_SYSEXP;
    }

    if(COperateDB::MyAfterUpdateDB(saConn, &pTmpData, (char)ST_SUCCESS, (char *)"00",(char *)"成功"))
    {
        trace_log(ERR, "MyAfterUpdateDB (getmainkey) return failed!");
        return RET_SYSEXP;
    }
    trace_log(DBG,"getmainkey success");
    return RET_SUCCESS;
}
Ejemplo n.º 28
0
int CTradeBase::SetTrack(TRADEDATA * pData, CTLVTemplet tlvObj,bool& bHasTrack )
{
    BYTE bTrack[128] = {0},bField36[128] = {0},bField35[128]={0};
    //BYTE TMPLEN[5]={0};
	char new_bTrack[128] = {0};
    BYTE partOut[256]={0};
	int iLen = 0,bTrackLen = 0;
	bool bFlag = true;

	//2磁道
	bTrackLen = tlvObj.GetTLVItemByHex(TAG_TRACK2, bTrack, sizeof(bTrack));
	trace_log(ERR,"TRACK2 length:%d",bTrackLen);
	if(bTrackLen>0)
	{
		iLen = (((bTrackLen+2)/16)+1)*16;
		trace_log(ERR, "bTrack:%s:bTrackLen:%d,RcvBrchCode:%s,SndBrchCode:%s,%d",
			bTrack,bTrackLen,pData->RcvBrchCode,pData->SndBrchCode,iLen);

		sprintf(new_bTrack,"%02d%s",bTrackLen,bTrack);
		memset(new_bTrack+bTrackLen+2,'0', iLen-bTrackLen-2);

		trace_log(ERR, "After new_bTrack:%s,len:%d",new_bTrack,strlen(new_bTrack));

		Ccommon::Asc2Bcd(new_bTrack, (unsigned char *)bField35, iLen, NL);
		iLen = iLen / 2;
		if(!cryptComm.EnTrackData(pData->RcvBrchCode,pData->SndBrchCode,bField35,partOut,iLen ))
		{
			trace_log(ERR, "Call TranslatePin fail!");
			return RET_SYSEXP;
		}

		trace_log(ERR, "After partOut:%d",iLen);
		trace_mem(partOut,iLen);

		bFlag &= sndObj.SetValueByHex(35, partOut, iLen);
	}

	memset(new_bTrack,0,128);

	//3磁道
	bTrackLen = tlvObj.GetTLVItemByHex(TAG_TRACK3, bTrack, sizeof(bTrack));
	trace_log(ERR,"TRACK3 length:%d",bTrackLen);
	if(bTrackLen>0)
	{

		iLen = (((bTrackLen+2)/16)+1)*16;
		trace_log(ERR, "bTrack:%s:bTrackLen:%d,RcvBrchCode:%s,SndBrchCode:%s,%d",
			bTrack,bTrackLen,pData->RcvBrchCode,pData->SndBrchCode,iLen);

		sprintf(new_bTrack,"%04d%s",bTrackLen,bTrack);
		memset(new_bTrack+bTrackLen+2,'0', iLen-bTrackLen-2);

		trace_log(ERR, "After new_bTrack:%s,len:%d",new_bTrack,strlen(new_bTrack));

		Ccommon::Asc2Bcd(new_bTrack, (unsigned char *)bField36, iLen, NL);
		iLen = iLen / 2;
		if(!cryptComm.EnTrackData(pData->RcvBrchCode,pData->SndBrchCode,bField36,partOut,iLen ))
		{
			trace_log(ERR, "Call TranslatePin fail!");
			return RET_SYSEXP;
		}

		trace_log(ERR, "After partOut:%d",iLen);
		trace_mem(partOut,iLen);

		bFlag &= sndObj.SetValueByHex(36, partOut, iLen);

	}

    return 0;
}
Ejemplo n.º 29
0
/** \brief
 *   设置磁道(即35、36域)
 * \param in: pData TRADEDATA结构指针
 * \param in: tlvObj tlv结构
 * \param out: bHasTrack 是否有磁道
 * \param out: bT2Data 2磁道数据
 * \return 失败返回非0,成功返回0
 */
int CTradeBase::SetTrack(TRADEDATA * pData, CTLVTemplet tlvObj,bool& bHasTrack )
{
	BYTE bTmpData[FIELD_MAXLEN] = {0},bTrack[128] = {0},bField36[128] = {0},bField35[128]={0},EncryptedData[17]={0};
	BYTE BCDdata[50]={0};
	BYTE part[9]={0},partOut[9]={0},allOut[8]={0},outpart[16]={0};
	unsigned char Ctrack2[50]={0};
	int iLen = 0,bTrackLen = 0,sLen=8;
	bool bFlag = true;
	bool bSingle=true;//奇数偶数位标识 默认 奇数\
	
	//2磁道
	bTrackLen = tlvObj.GetTLVItemByHex(TAG_TRACK2, bTrack, sizeof(bTrack));
	trace_log(DBG,"original  bTrack=");//部分加密后的数据BCD码
	trace_mem(bTrack,bTrackLen);
	if(bTrackLen%2==0)
	{
		iLen=18;
	}
	else if(bTrackLen%2==1)
	{
		iLen=17; //BCD码是奇数位
	}
	if(bTrackLen>0)
	{
		memcpy(outpart,bTrack+bTrackLen-iLen,16);
		trace_log(DBG,"outpart=");//部分加密后的数据BCD码
		trace_mem(outpart,16);
		Ccommon::AsctoBcd((const char*)outpart, (unsigned char *)EncryptedData, 16, NL,bSingle);
		if(!cryptComm.EnTrackData(pData->RcvBrchCode,pData->SndBrchCode,EncryptedData,allOut,sLen))
		{
			trace_log(ERR, "Call EnTrackData fail!");
			return RET_SYSEXP;
		}
		memset((char *)EncryptedData,0 , sizeof(EncryptedData));
		Ccommon::Hex2Str((unsigned char *)allOut,(char *)EncryptedData,sLen);
		memcpy(bTrack+bTrackLen-iLen,(char *)EncryptedData,16);
		trace_log(DBG,"Out  bTrack=");//部分加密后的数据BCD码
		trace_mem(bTrack,bTrackLen);
		bFlag &= sndObj.SetValueByStr(35,(const char *)bTrack);
	}
	
	//3磁道
	bTrackLen = tlvObj.GetTLVItemByHex(TAG_TRACK3, bTrack, sizeof(bTrack));
	if(bTrackLen%2==0)
	{
		iLen=18;
	}
	else if(bTrackLen%2==1)
	{
		iLen=17; //BCD码是奇数位
	}
	if(bTrackLen>0)
	{
		memset(part,0,sizeof(part));
		memset(partOut,0,sizeof(partOut));
		memset(bTmpData,0,sizeof(bTmpData));
		
		trace_log(DBG,"bTrackLen==%d",bTrackLen);
		memcpy(outpart,bTrack+bTrackLen-iLen,16);
		Ccommon::AsctoBcd((const char*)outpart, (unsigned char *)EncryptedData, 16, NL,bSingle);
		if(!cryptComm.EnTrackData(pData->RcvBrchCode,pData->SndBrchCode,EncryptedData,allOut,sLen))
		{
			trace_log(ERR, "Call EnTrackData fail!");
			return RET_SYSEXP;
		}
		memset((char *)EncryptedData,0 , sizeof(EncryptedData));
		Ccommon::Hex2Str((unsigned char *)allOut,(char *)EncryptedData,sLen);
		memcpy(bTrack+bTrackLen-iLen,(char *)EncryptedData,16);
		trace_log(DBG,"Out  bTrack=");//部分加密后的数据BCD码
		trace_mem(bTrack,bTrackLen);
		bFlag &= sndObj.SetValueByStr(36,(const char *)bTrack);
	}
	
	//发给加密机返回数据放36域
	return 0;
}
Ejemplo n.º 30
0
int main (int argc, char **argv)
{
	int c;

	errno = 0;

	if (argc < 2)
		usage(argv);

	if (strcmp(argv[1], "report") == 0) {
		trace_report(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "snapshot") == 0) {
		trace_snapshot(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "hist") == 0) {
		trace_hist(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "mem") == 0) {
		trace_mem(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "listen") == 0) {
		trace_listen(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "split") == 0) {
		trace_split(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "restore") == 0) {
		trace_restore(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "stack") == 0) {
		trace_stack(argc, argv);
		exit(0);
	} else if (strcmp(argv[1], "check-events") == 0) {
		const char *tracing;
		int ret;
		struct pevent *pevent = NULL;
		struct plugin_list *list = NULL;

		while ((c = getopt(argc-1, argv+1, "+hN")) >= 0) {
			switch (c) {
			case 'h':
			default:
				usage(argv);
				break;
			case 'N':
				tracecmd_disable_plugins = 1;
				break;
			}
		}
		tracing = tracecmd_get_tracing_dir();

		if (!tracing) {
			printf("Can not find or mount tracing directory!\n"
				"Either tracing is not configured for this "
				"kernel\n"
				"or you do not have the proper permissions to "
				"mount the directory");
			exit(EINVAL);
		}

		pevent = pevent_alloc();
		if (!pevent)
			exit(EINVAL);
		list = tracecmd_load_plugins(pevent);
		ret = tracecmd_fill_local_events(tracing, pevent);
		if (ret || pevent->parsing_failures)
			ret = EINVAL;
		tracecmd_unload_plugins(list, pevent);
		pevent_free(pevent);
		exit(ret);

	} else if (strcmp(argv[1], "record") == 0 ||
		   strcmp(argv[1], "start") == 0 ||
		   strcmp(argv[1], "extract") == 0 ||
		   strcmp(argv[1], "stop") == 0 ||
		   strcmp(argv[1], "stream") == 0 ||
		   strcmp(argv[1], "profile") == 0 ||
		   strcmp(argv[1], "restart") == 0 ||
		   strcmp(argv[1], "reset") == 0) {
		trace_record(argc, argv);
		exit(0);

	} else if (strcmp(argv[1], "stat") == 0) {
		trace_stat(argc, argv);
		exit(0);

	} else if (strcmp(argv[1], "options") == 0) {
		show_plugin_options();
		exit(0);
	} else if (strcmp(argv[1], "show") == 0) {
		const char *buffer = NULL;
		const char *file = "trace";
		const char *cpu = NULL;
		struct buffer_instance *instance = &top_instance;
		char cpu_path[128];
		char *path;
		int snap = 0;
		int pipe = 0;
		int show_name = 0;
		int option_index = 0;
		int stop = 0;
		static struct option long_options[] = {
			{"tracing_on", no_argument, NULL, OPT_tracing_on},
			{"current_tracer", no_argument, NULL, OPT_current_tracer},
			{"buffer_size", no_argument, NULL, OPT_buffer_size_kb},
			{"buffer_total_size", no_argument, NULL, OPT_buffer_total_size_kb},
			{"ftrace_filter", no_argument, NULL, OPT_ftrace_filter},
			{"ftrace_notrace", no_argument, NULL, OPT_ftrace_notrace},
			{"ftrace_pid", no_argument, NULL, OPT_ftrace_pid},
			{"graph_function", no_argument, NULL, OPT_graph_function},
			{"graph_notrace", no_argument, NULL, OPT_graph_notrace},
			{"cpumask", no_argument, NULL, OPT_cpumask},
			{"help", no_argument, NULL, '?'},
			{NULL, 0, NULL, 0}
		};

		while ((c = getopt_long(argc-1, argv+1, "B:c:fsp",
					long_options, &option_index)) >= 0) {
			switch (c) {
			case 'h':
				usage(argv);
				break;
			case 'B':
				if (buffer)
					die("Can only show one buffer at a time");
				buffer = optarg;
				instance = create_instance(optarg);
				if (!instance)
					die("Failed to create instance");
				break;
			case 'c':
				if (cpu)
					die("Can only show one CPU at a time");
				cpu = optarg;
				break;
			case 'f':
				show_name = 1;
				break;
			case 's':
				snap = 1;
				if (pipe)
					die("Can not have -s and -p together");
				break;
			case 'p':
				pipe = 1;
				if (snap)
					die("Can not have -s and -p together");
				break;
			case OPT_tracing_on:
				show_instance_file(instance, "tracing_on");
				stop = 1;
				break;
			case OPT_current_tracer:
				show_instance_file(instance, "current_tracer");
				stop = 1;
				break;
			case OPT_buffer_size_kb:
				show_instance_file(instance, "buffer_size_kb");
				stop = 1;
				break;
			case OPT_buffer_total_size_kb:
				show_instance_file(instance, "buffer_total_size_kb");
				stop = 1;
				break;
			case OPT_ftrace_filter:
				show_instance_file(instance, "set_ftrace_filter");
				stop = 1;
				break;
			case OPT_ftrace_notrace:
				show_instance_file(instance, "set_ftrace_notrace");
				stop = 1;
				break;
			case OPT_ftrace_pid:
				show_instance_file(instance, "set_ftrace_pid");
				stop = 1;
				break;
			case OPT_graph_function:
				show_instance_file(instance, "set_graph_function");
				stop = 1;
				break;
			case OPT_graph_notrace:
				show_instance_file(instance, "set_graph_notrace");
				stop = 1;
				break;
			case OPT_cpumask:
				show_instance_file(instance, "tracing_cpumask");
				stop = 1;
				break;
			default:
				usage(argv);
			}
		}
		if (stop)
			exit(0);
		if (pipe)
			file = "trace_pipe";
		else if (snap)
			file = "snapshot";

		if (cpu) {
			snprintf(cpu_path, 128, "per_cpu/cpu%d/%s", atoi(cpu), file);
			file = cpu_path;
		}
			
		if (buffer) {
			path = malloc(strlen(buffer) + strlen("instances//") +
				      strlen(file) + 1);
			if (path)
				die("Failed to allocate instance path %s", file);
			sprintf(path, "instances/%s/%s", buffer, file);
			file = path;
		}

		if (show_name) {
			char *name;
			name = tracecmd_get_tracing_file(file);
			printf("%s\n", name);
			tracecmd_put_tracing_file(name);
		}
		show_file(file);
		if (buffer)
			free(path);

		exit(0);
	} else if (strcmp(argv[1], "list") == 0) {
		int events = 0;
		int tracer = 0;
		int options = 0;
		int funcs = 0;
		int buffers = 0;
		int clocks = 0;
		int plug = 0;
		int plug_op = 0;
		int flags = 0;
		int show_all = 1;
		int i;
		const char *arg;
		const char *funcre = NULL;
		const char *eventre = NULL;

		for (i = 2; i < argc; i++) {
			arg = NULL;
			if (argv[i][0] == '-') {
				if (i < argc - 1) {
					if (argv[i+1][0] != '-')
						arg = argv[i+1];
				}
				switch (argv[i][1]) {
				case 'h':
					usage(argv);
					break;
				case 'e':
					events = 1;
					eventre = arg;
					show_all = 0;
					break;
				case 'B':
					buffers = 1;
					show_all = 0;
					break;
				case 'C':
					clocks = 1;
					show_all = 0;
					break;
				case 'F':
					flags |= SHOW_EVENT_FORMAT;
					break;
				case 'R':
					flags |= SHOW_EVENT_TRIGGER;
					break;
				case 'l':
					flags |= SHOW_EVENT_FILTER;
					break;
				case 'p':
				case 't':
					tracer = 1;
					show_all = 0;
					break;
				case 'P':
					plug = 1;
					show_all = 0;
					break;
				case 'O':
					plug_op = 1;
					show_all = 0;
					break;
				case 'o':
					options = 1;
					show_all = 0;
					break;
				case 'f':
					funcs = 1;
					funcre = arg;
					show_all = 0;
					break;
				default:
					fprintf(stderr, "list: invalid option -- '%c'\n",
						argv[optind][1]);
					usage(argv);
				}
			}
		}

		if (events)
			show_events(eventre, flags);

		if (tracer)
			show_tracers();

		if (options)
			show_options();

		if (plug)
			show_plugins();

		if (plug_op)
			show_plugin_options();

		if (funcs)
			show_functions(funcre);

		if (buffers)
			show_buffers();

		if (clocks)
			show_clocks();

		if (show_all) {
			printf("events:\n");
			show_events(NULL, 0);
			printf("\ntracers:\n");
			show_tracers();
			printf("\noptions:\n");
			show_options();
		}

		exit(0);

	} else if (strcmp(argv[1], "-h") == 0 ||
		   strcmp(argv[1], "help") == 0) {
		usage(argv);
	} else {
		fprintf(stderr, "unknown command: %s\n", argv[1]);
		usage(argv);
	}

	return 0;
}