mod_AccessAuth.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  1. #include "stdafx.h"
  2. #include "SpBase.h"
  3. #include "mod_AccessAuth.h"
  4. #include "RVCComm.h"
  5. #include "comm.h"
  6. #include "access_basefun.h"
  7. #include "DeviceBaseClass.h"
  8. #include <fileutil.h>
  9. #include <iniutil.h>
  10. #include <cmath>
  11. #include "TokenKeeper_client_g.h"
  12. using namespace TokenKeeper;
  13. #include "PinPad_client_g.h"
  14. using namespace PinPad;
  15. #ifdef RVC_OS_WIN
  16. #include "WMIDeviceQuery.h"
  17. #include <Strsafe.h>
  18. #endif
  19. #ifdef WITH_CPPRESTSDK
  20. #include "CommEntityRestful.hpp"
  21. #else
  22. #define SAFE_DELETE_HTTPCLIENT(obj) \
  23. do{if(obj != NULL) { obj->Destory(); obj = NULL; }}while(false)
  24. #endif
  25. #define KEY_SIZE 16
  26. #define BUF_SIZE 256
  27. /** TODO(gifur): expand the time to 10s*/
  28. #define DEFUALT_INVOKE_PINPAD_TIMEOUT 3000
  29. struct InitializerInitMKTask : ITaskSp {
  30. CAccessAuthFSM* m_fsm;
  31. CAccessAuthEntity* m_entity;
  32. InitializerInitMKTask(CAccessAuthFSM* fsm, CAccessAuthEntity* entity) :m_fsm(fsm), m_entity(entity) {}
  33. void Process()
  34. {
  35. CSystemStaticInfo si;
  36. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  37. CInitlizerMKReq initMKReq(1);//oiltest dev module count
  38. m_entity->SendInitMKReqACS(initMKReq);
  39. #ifdef WITH_CPPRESTSDK
  40. struct MKD_NEW1JSON
  41. {
  42. string enrolAddr;
  43. string enrolGPS;
  44. string installVersion;
  45. string ip;
  46. string machineModel;
  47. string machineType;
  48. string padDeviceID;
  49. string site;
  50. string terminalNo;
  51. JSONCONVERT2OBJECT_MEMEBER_REGISTER(enrolAddr, enrolGPS, installVersion, ip, machineModel, machineType, padDeviceID, site, terminalNo)
  52. };
  53. struct MKD_REQ2JSON
  54. {
  55. string branchNo;
  56. string kmcData;
  57. string subBankNo;
  58. JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, kmcData, subBankNo)
  59. };
  60. struct MKD_REQ3JSON
  61. {
  62. string factory;
  63. string modal;
  64. string type;
  65. string version;
  66. JSONCONVERT2OBJECT_MEMEBER_REGISTER(factory, modal, type, version)
  67. };
  68. struct MKD_REQ4JSON
  69. {
  70. string fingerPrint;
  71. string fingerPrintSM;
  72. string pinPadID;
  73. string publicKey;
  74. string reserverd;
  75. JSONCONVERT2OBJECT_MEMEBER_REGISTER(fingerPrint, fingerPrintSM, pinPadID, publicKey, reserverd)
  76. };
  77. struct MKD_REQ5JSON
  78. {
  79. int isFirstSM;
  80. int isSM;
  81. JSONCONVERT2OBJECT_MEMEBER_REGISTER(isFirstSM, isSM)
  82. };
  83. struct MKD_SMR2JSON
  84. {
  85. string branchNo;
  86. string kmcData;
  87. string subBankNo;
  88. JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, kmcData, subBankNo)
  89. };
  90. struct InstanceReqJson
  91. {
  92. MKD_NEW1JSON MKD_NEW1;
  93. MKD_REQ2JSON MKD_REQ2;
  94. std::vector<MKD_REQ3JSON> MKD_REQ3;
  95. MKD_REQ4JSON MKD_REQ4;
  96. MKD_REQ5JSON MKD_REQ5;
  97. MKD_SMR2JSON MKD_SMR2;
  98. JSONCONVERT2OBJECT_MEMEBER_REGISTER(MKD_NEW1, MKD_REQ2, MKD_REQ3, MKD_REQ4, MKD_REQ5, MKD_SMR2)
  99. } instanceReq;
  100. instanceReq.MKD_NEW1.enrolAddr = initMKReq.MKD_NEW1.enrolAddr;
  101. instanceReq.MKD_NEW1.enrolGPS = initMKReq.MKD_NEW1.enrolGPS;
  102. instanceReq.MKD_NEW1.installVersion = initMKReq.MKD_NEW1.installVersion;
  103. instanceReq.MKD_NEW1.ip = initMKReq.MKD_NEW1.ip;
  104. instanceReq.MKD_NEW1.machineModel = initMKReq.MKD_NEW1.machineModel;
  105. instanceReq.MKD_NEW1.machineType = initMKReq.MKD_NEW1.machineType;
  106. instanceReq.MKD_NEW1.padDeviceID = initMKReq.MKD_NEW1.padDeviceID;
  107. instanceReq.MKD_NEW1.site = initMKReq.MKD_NEW1.site;
  108. instanceReq.MKD_NEW1.terminalNo = initMKReq.MKD_NEW1.terminalNo;
  109. instanceReq.MKD_REQ2.branchNo = initMKReq.MKD_REQ2.branchNo;
  110. instanceReq.MKD_REQ2.kmcData = initMKReq.MKD_REQ2.kmcData;
  111. instanceReq.MKD_REQ2.subBankNo = initMKReq.MKD_REQ2.subBankNo;
  112. for (int i = 0; i < initMKReq.iReq3Count; ++i) {
  113. MKD_REQ3JSON item;
  114. item.type = initMKReq.MKD_REQ3[i]->type;
  115. item.modal = initMKReq.MKD_REQ3[i]->modal;
  116. item.factory = initMKReq.MKD_REQ3[i]->factory;
  117. item.version = initMKReq.MKD_REQ3[i]->version;
  118. instanceReq.MKD_REQ3.push_back(item);
  119. }
  120. instanceReq.MKD_REQ4.fingerPrint = initMKReq.MKD_REQ4.fingerPrint;
  121. instanceReq.MKD_REQ4.fingerPrintSM = initMKReq.MKD_REQ4.fingerPrintSM;
  122. instanceReq.MKD_REQ4.pinPadID = initMKReq.MKD_REQ4.pinPadID;
  123. instanceReq.MKD_REQ4.publicKey = initMKReq.MKD_REQ4.publicKey;
  124. instanceReq.MKD_REQ4.reserverd = initMKReq.MKD_REQ4.reserverd;
  125. instanceReq.MKD_REQ5.isFirstSM = initMKReq.MKD_REQ5.isFirstSM;
  126. instanceReq.MKD_REQ5.isSM = initMKReq.MKD_REQ5.isSM;
  127. instanceReq.MKD_SMR2.branchNo = initMKReq.MKD_SMR2.branchNo;
  128. instanceReq.MKD_SMR2.subBankNo = initMKReq.MKD_SMR2.subBankNo;
  129. instanceReq.MKD_SMR2.kmcData = initMKReq.MKD_SMR2.kmcData;
  130. struct InstanceAnsJson
  131. {
  132. string TMK;
  133. string TPK;
  134. string EDK;
  135. string index;
  136. string reserved;
  137. JSONCONVERT2OBJECT_MEMEBER_REGISTER(TMK, TPK, EDK, index)
  138. JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("tmk", "tpk", "edk", "index")
  139. } instanceAns;
  140. HttpClientResponseResult result;
  141. HttpClientRequestConfig config(HttpRequestMethod::POST, m_entity->GetInitUrl().GetData());
  142. config.SetChildUri("/api/initmk");
  143. SP::Module::Restful::FulfillRequestJsonBody(&config, instanceReq);
  144. RestfulClient client = RestfulClient::getInstance();
  145. config.PreDo();
  146. client.Do(&config, &result);
  147. if (result.ResponseOK()) {
  148. Dbg("InitializerInitMKTask Connect Success.");
  149. SP::Module::Restful::CommResponseJson responseStatus;
  150. SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
  151. if (!responseStatus.IsOperatedOK()) {
  152. Dbg("update wk failed: %s", responseStatus.errorMsg.c_str());
  153. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, responseStatus.errorMsg.c_str());
  154. }
  155. else {
  156. if (m_entity->HasPinPad()) {
  157. const bool testResult = SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, instanceAns);
  158. Dbg("ExtractDataFromDebranchResponse returned: %d", testResult);
  159. if (m_entity->LoadKeysToPinPadACS(instanceAns.TMK, instanceAns.TPK, instanceAns.EDK, instanceAns.index) == Error_Succeed) {
  160. m_entity->EndInitMK(Error_Succeed, "");
  161. }
  162. else {
  163. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "加载秘钥到密码键盘失败");//,待完善细化错误码oiltest
  164. }
  165. }
  166. else {
  167. m_entity->EndInitMK(Error_Succeed, "");
  168. }
  169. }
  170. }
  171. else {
  172. Dbg("post wk failed: %s", result.WhatError().c_str());
  173. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, result.WhatError().c_str());
  174. }
  175. #else
  176. IHttpFunc* client;
  177. client = create_http(m_fsm->HttpsLogCallBack);
  178. initMKReq.m_bTransCode = false;
  179. CInitlizerMKRet initMKRet;
  180. initMKReq.m_url = m_entity->GetInitUrl();
  181. initMKReq.m_url += "/api/initmk";
  182. bool ret = client->Post(initMKReq, initMKRet);
  183. Dbg("code=%d", initMKRet.m_sysCode);
  184. if (ret) {
  185. Dbg("InitializerInitMKTask Connect Success.");
  186. if (initMKRet.m_userCode.compare(ACS_SUCCESS)) {
  187. Dbg("update wk failed: %s", initMKRet.m_errMsg.c_str());
  188. std::string errStr("#ACS#");
  189. errStr += initMKRet.m_errMsg;
  190. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, errStr.c_str());
  191. SAFE_DELETE_HTTPCLIENT(client);
  192. return;
  193. }
  194. if (m_entity->HasPinPad()) {
  195. if (m_entity->LoadKeysToPinPadACS(initMKRet.data.TMK, initMKRet.data.TPK, initMKRet.data.EDK, initMKRet.data.index) == Error_Succeed)
  196. m_entity->EndInitMK(Error_Succeed, "");
  197. else
  198. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "加载秘钥到密码键盘失败");//,待完善细化错误码oiltest
  199. }
  200. else
  201. m_entity->EndInitMK(Error_Succeed, "");
  202. }
  203. else {
  204. Dbg("UpdateWKTask Connect Failed.");
  205. }
  206. SAFE_DELETE_HTTPCLIENT(client);
  207. #endif //WITH_CPPRESTSDK
  208. }
  209. };
  210. typedef struct _REG_TZI_FORMAT
  211. {
  212. LONG Bias;
  213. LONG StandardBias;
  214. LONG DaylightBias;
  215. SYSTEMTIME StandardDate;
  216. SYSTEMTIME DaylightDate;
  217. } REG_TZI_FORMAT;
  218. void CAccessAuthSession::Handle_Regist(SpOnewayCallContext<AccessAuthService_Regist_Info>::Pointer ctx)
  219. {
  220. m_pEntity->Regist();
  221. }
  222. void CAccessAuthSession::Handle_Unregist(SpOnewayCallContext<AccessAuthService_Unregist_Info>::Pointer ctx)
  223. {
  224. m_pEntity->Unregist(ctx->Info.nReason, ctx->Info.nWay);
  225. }
  226. void CAccessAuthSession::Handle_InitDev(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer ctx)
  227. {
  228. m_pEntity->InitDevice(ctx);
  229. }
  230. void CAccessAuthSession::Handle_UpdateWK(SpOnewayCallContext<AccessAuthService_UpdateWK_Info>::Pointer ctx)
  231. {
  232. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI("UpdateWK")("call Handle_UpdateWK");
  233. m_pEntity->UpdateWK();
  234. }
  235. void CAccessAuthSession::Handle_SyncTime(SpOnewayCallContext<AccessAuthService_SyncTime_Info>::Pointer ctx)
  236. {
  237. m_pEntity->SyncTime();
  238. }
  239. void CAccessAuthSession::Handle_InitializeNew(SpReqAnsContext<AccessAuthService_InitializeNew_Req, AccessAuthService_InitializeNew_Ans>::Pointer ctx)
  240. {
  241. DbgWithLink(LOG_LEVEL_INFO, ctx->link.checkEmpty() ? LOG_TYPE_SYSTEM : LOG_TYPE_USER).setAPI("StartInitializeNew")("Handle_InitializeNew");
  242. m_pEntity->m_ctx = ctx;
  243. m_pEntity->m_strUserID = ctx->Req.strUserID.GetData();
  244. m_pEntity->m_strPassword = ctx->Req.strPassword.GetData();
  245. m_pEntity->BeginInitMKACS();
  246. }
  247. void CAccessAuthEntity::OnStarted()
  248. {
  249. //设置时区为北京标准时区
  250. if (!SetLocalTimeZoneByKeyName("China Standard Time", FALSE))
  251. {
  252. m_FSM.doWarnMsg(ERR_ACCESSAUTH_SETTIMEZONE,GetOutPutStr("%s%s","设置时区错误","False").c_str());
  253. }
  254. m_FSM.Init(this);
  255. CSimpleStringA strErrMsg;
  256. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  257. memset(&m_info,0, sizeof(CSystemStaticInfo));
  258. auto rc = GetFunction()->GetSystemStaticInfo(m_info);
  259. if (rc != Error_Succeed)
  260. {
  261. strErrMsg = "HasPinPad()=>GetSystemStaticInfo() fail";
  262. SetAuthErrMsg((const char*)strErrMsg);
  263. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
  264. GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str(), strErrMsg.GetData());
  265. }
  266. }
  267. void CAccessAuthEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext)
  268. {
  269. ErrorCodeEnum Error = Error_Succeed;
  270. pTransactionContext->SendAnswer(Error) ;
  271. }
  272. void CAccessAuthEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext)
  273. {
  274. m_FSM.PostExitEvent();
  275. pTransactionContext->SendAnswer(Error_Succeed);
  276. }
  277. void CAccessAuthEntity::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
  278. {
  279. }
  280. // 开始准入
  281. ErrorCodeEnum CAccessAuthEntity::Regist()
  282. {
  283. m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartRegist));
  284. return Error_Succeed;
  285. }
  286. // 重新准入
  287. ErrorCodeEnum CAccessAuthEntity::Reregist()
  288. {
  289. //m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartReregist));
  290. return Error_Succeed;
  291. }
  292. // 准入退出
  293. ErrorCodeEnum CAccessAuthEntity::Unregist(int nReason, int nWay)
  294. {
  295. /*FSMEvent *pEvent = new FSMEvent(CAccessAuthFSM::Event_StartUnregist);
  296. pEvent->param1 = nReason;
  297. pEvent->param2 = nWay;
  298. m_FSM.PostEventFIFO(pEvent);*/
  299. return Error_Succeed;
  300. }
  301. DWORD CAccessAuthEntity::SyncTime()
  302. {
  303. return m_FSM.SyncTime();
  304. }
  305. ErrorCodeEnum CAccessAuthEntity::PushTerminalStage(char cNewStage, DWORD dwNewStageTime, char cOldStage, DWORD dwOldStageTime)
  306. {
  307. Dbg("on PushTerminalStage, cNewStage: %c", cNewStage);
  308. /*CAccessAuthFSM::ReportStateEvent *pEvent = new CAccessAuthFSM::ReportStateEvent(cNewStage, dwNewStageTime, cOldStage, dwOldStageTime);
  309. m_FSM.PostEventFIFO(pEvent);*/
  310. return Error_Succeed;
  311. }
  312. // KMC初始化
  313. DWORD CAccessAuthEntity::InitKMC()
  314. {
  315. return Error_Succeed;
  316. }
  317. // 获取WK更新请求包
  318. // @nAlgFlag: 1:3des only; 2: sm4 only; 3: both 3des and sm4
  319. ErrorCodeEnum CAccessAuthEntity::GetKmcWKUpdateData(char *pBuf, int &nLen, int nAlgFlag)
  320. {
  321. return Error_Succeed;
  322. }
  323. DWORD CAccessAuthEntity::ParseWKUpdateResult(char *pBuf, int nLen, int nAlgFlag)
  324. {
  325. return Error_Succeed;
  326. }
  327. CSimpleStringA CAccessAuthEntity::GetKMCLastErrMsg()
  328. {
  329. return "";
  330. }
  331. ErrorCodeEnum CAccessAuthEntity::ReleaseKMC()
  332. {
  333. return Error_Succeed;
  334. }
  335. // 加载新WK
  336. DWORD CAccessAuthEntity::LoadPinPadWK(bool bSM)
  337. {
  338. Dbg("load sm key to pinpad...");
  339. CSimpleString strErrMsg;
  340. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  341. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  342. DWORD rc = pPinPad->Connect();
  343. if (rc == Error_Succeed)
  344. {
  345. PinPadService_LoadKeysSM_Req req = {};
  346. req.smflag = 1;
  347. req.initializeflag = true;
  348. if (m_bGetKMCKey) {
  349. Dbg("使用云接口更新KMC密钥");
  350. req.masterkey = m_TMK.c_str();
  351. req.workingkey1 = m_TPK.c_str();
  352. req.workingkey2 = m_EDK.c_str();
  353. req.reserved3 = m_index.c_str();
  354. }
  355. else {
  356. strErrMsg = "更新KMC密钥失败";
  357. SetAuthErrMsg((const char*)strErrMsg);
  358. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
  359. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_KMC_NULL,
  360. GetOutPutStr("%s%s", "m_bGetKMCKey", "False").c_str());
  361. rc = ERR_ACCESSAUTH_GET_KMC_NULL;
  362. return rc;
  363. }
  364. if (req.initializeflag) Dbg("initializeflag is true");
  365. else Dbg("initializeflag is false");
  366. Dbg("req.smflag=%d", req.smflag);
  367. Dbg("req.masterkey=%s", req.masterkey.GetData());
  368. Dbg("req.workingkey1=%s", req.workingkey1.GetData());
  369. Dbg("req.workingkey2=%s", req.workingkey2.GetData());
  370. Dbg("req.reserved3=%s", req.reserved3.GetData());
  371. PinPadService_LoadKeysSM_Ans ans = {};
  372. rc = pPinPad->LoadKeysSM(req, ans, 30000);
  373. if (rc == Error_Succeed)
  374. Dbg("load sm key to pinpad succ");
  375. else
  376. {
  377. strErrMsg = "加载SM密钥到PinPad失败";
  378. SetAuthErrMsg((const char*)strErrMsg);
  379. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
  380. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD,
  381. GetOutPutStr("%s%08x%s%s", "LoadKeysSM", rc, "strErrMsg", strErrMsg.GetData()).c_str());
  382. rc = ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD;
  383. }
  384. pPinPad->GetFunction()->CloseSession();
  385. }
  386. else
  387. {
  388. strErrMsg = "连接PinPad实体失败";
  389. SetAuthErrMsg((const char*)strErrMsg);
  390. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
  391. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  392. GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
  393. rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
  394. //@test 没连接成功调用此接口释放
  395. pPinPad->SafeDelete();
  396. }
  397. return rc;
  398. }
  399. DWORD CAccessAuthEntity::LoadKeysToPinPadNew(string TMK, string TPK, string EDK, string index)
  400. {
  401. LOG_FUNCTION();
  402. Dbg("load sm key to pinpad...");
  403. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  404. DWORD rc = pPinPad->Connect();
  405. if (rc == Error_Succeed)
  406. {
  407. PinPadService_LoadKeysSM_Req req = {};
  408. req.initializeflag = true;
  409. req.smflag = 1;
  410. Dbg("使用云接口获取的KMC密钥");
  411. req.masterkey = TMK.c_str();
  412. req.workingkey1 = TPK.c_str();
  413. req.workingkey2 = EDK.c_str();
  414. req.reserved3 = index.c_str();
  415. if (req.initializeflag) Dbg("initializeflag is true");
  416. else Dbg("initializeflag is false");
  417. Dbg("req.smflag=%d", req.smflag);
  418. Dbg("req.masterkey=%s", req.masterkey.GetData());
  419. Dbg("req.workingkey1=%s", req.workingkey1.GetData());
  420. Dbg("req.workingkey2=%s", req.workingkey2.GetData());
  421. Dbg("req.reserved3=%s", req.reserved3.GetData());
  422. PinPadService_LoadKeysSM_Ans ans = {};
  423. rc = pPinPad->LoadKeysSM(req, ans, 30000);
  424. if (rc == Error_Succeed)
  425. Dbg("load sm key to pinpad succ");
  426. else
  427. {
  428. SetAuthErrMsg("加载SM密钥到PinPad失败");
  429. m_FSM.doWarnMsg(ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD,
  430. GetOutPutStr("%s%08x%s%s", "LoadKeys", rc, "strErrMsg", "加载SM密钥到PinPad失败").c_str());
  431. rc = ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD;
  432. }
  433. pPinPad->GetFunction()->CloseSession();
  434. }
  435. else
  436. {
  437. SetAuthErrMsg("连接PinPad实体失败");
  438. m_FSM.doWarnMsg(ERR_INITIALIZER_CONNECT_PINPAD,
  439. GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
  440. rc = ERR_INITIALIZER_CONNECT_PINPAD;
  441. pPinPad->SafeDelete();
  442. }
  443. return rc;
  444. }
  445. // 将16进制字符串转成BYTE数据
  446. bool CAccessAuthEntity::HexStrToByteArray(const char* pHex, BYTE *pBuf, int *pBufLen)
  447. {
  448. int nHexLen = strlen(pHex);
  449. if (nHexLen %2 != 0)
  450. {
  451. Dbg("error hex string length");
  452. return false;
  453. }
  454. if (nHexLen /2 > *pBufLen)
  455. {
  456. Dbg("not enough buf length");
  457. return false;
  458. }
  459. for(int i=0; i<nHexLen; i++)
  460. {
  461. BYTE b =0;
  462. char ch1 = pHex[i];
  463. if (ch1 >='0' && ch1<='9')
  464. b = ch1 - '0';
  465. else if (ch1 >='A' && ch1 <='F')
  466. b = ch1 - 'A' + 10;
  467. else
  468. {
  469. Dbg("invalid hex string");
  470. return false;
  471. }
  472. if (i %2 ==0)
  473. {
  474. pBuf[i/2] = b;
  475. }
  476. else
  477. {
  478. pBuf[i/2] = pBuf[i/2] << 4 | b;
  479. }
  480. }
  481. *pBufLen = nHexLen / 2;
  482. return true;
  483. }
  484. string CAccessAuthEntity::ByteArrayToHexStr(BYTE *pBuf, int nBufLen)
  485. {
  486. char szBuf[1024];
  487. memset(szBuf, 0, sizeof(szBuf));
  488. for(int i=0; i<nBufLen; i++)
  489. {
  490. BYTE b1 = (pBuf[i] >> 4) & 0x0F;
  491. BYTE b2 = pBuf[i] & 0x0F;
  492. if (b1 <= 9)
  493. szBuf[i*2] = '0' + b1;
  494. else
  495. szBuf[i*2] = 'A' + b1 - 10;
  496. if (b2 <= 9)
  497. szBuf[i*2+1] = '0' + b2;
  498. else
  499. szBuf[i*2+1] = 'A' + b2 - 10;
  500. }
  501. return szBuf;
  502. }
  503. // 调用密码键盘加密
  504. DWORD CAccessAuthEntity::EncryptDataWithPinPad(const CBlob &raw, CBlob &enc)
  505. {
  506. #ifdef IGNORE_PINPAD
  507. enc.Alloc(raw.m_iLength);
  508. memcpy(enc.m_pData, raw.m_pData, raw.m_iLength);
  509. return Error_Succeed;
  510. #else
  511. CSimpleStringA strErrMsg;
  512. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  513. PinPadService_EncryptDataSM_Req req = {};
  514. PinPadService_EncryptDataSM_Ans ans = {};
  515. req.data = ByteArrayToHexStr((BYTE*)raw.m_pData, raw.m_iLength).c_str();
  516. Dbg("begin encrpyt data with pinpad");
  517. PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
  518. DWORD rc = pPinPad->Connect();
  519. if (rc == Error_Succeed)
  520. {
  521. rc = pPinPad->EncryptDataSM(req, ans, 10000);
  522. if (rc == Error_Succeed)
  523. Dbg("encrypt data with pinpad succ: [%s]", (const char*)ans.ciphertext);
  524. else
  525. {
  526. strErrMsg = "调用PinPad实体中的EncryptData方法加密数据失败";
  527. SetAuthErrMsg((const char *)strErrMsg);
  528. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  529. GetOutPutStr("%s%08x%s%s", "EncryptData", rc, "strErrMsg", strErrMsg).c_str());
  530. rc = ERR_ACCESSAUTH_FROM_PINPAD;
  531. }
  532. pPinPad->GetFunction()->CloseSession();
  533. }
  534. else
  535. {
  536. strErrMsg = "连接PinPad实体失败";
  537. SetAuthErrMsg((const char *)strErrMsg);
  538. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  539. GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
  540. rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
  541. pPinPad->SafeDelete();
  542. }
  543. if (rc != Error_Succeed)
  544. return rc;
  545. BYTE buf[512];
  546. int nLen = 512;
  547. memset(buf, 0, 512);
  548. if (!HexStrToByteArray((const char*)ans.ciphertext, buf, &nLen))
  549. {
  550. strErrMsg = "加密数据转化十六进制失败";
  551. SetAuthErrMsg((const char *)strErrMsg);
  552. m_FSM.doWarnMsg(ERR_ACCESSAUTH_HEX_TO_BYTE,
  553. GetOutPutStr("%s%s%s%s", "HexStrToByteArray", "False", "strErrMsg", strErrMsg).c_str());
  554. return ERR_ACCESSAUTH_HEX_TO_BYTE;
  555. }
  556. enc.Alloc(nLen);
  557. memcpy(enc.m_pData, buf, nLen);
  558. return Error_Succeed;
  559. #endif
  560. }
  561. // 生成临时SM2密钥对
  562. DWORD CAccessAuthEntity::CreateSM2KeyPair(CBlob &pubKey, CBlob &priKey)
  563. {
  564. int nPubKeyLen = 256;
  565. int nPriKeyLen = 256;
  566. pubKey.Alloc(nPubKeyLen);
  567. priKey.Alloc(nPriKeyLen);
  568. if (!::CreateSM2KeyPair((BYTE*)(pubKey.m_pData), &nPubKeyLen, (BYTE*)(priKey.m_pData), &nPriKeyLen))
  569. {
  570. SetAuthErrMsg("创建SM2密钥对失败");
  571. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  572. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR,
  573. GetOutPutStr("%s%s","CreateRsaKeyPair","False").c_str(), "创建SM2密钥对失败");
  574. return ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR;
  575. }
  576. pubKey.Resize(nPubKeyLen);
  577. priKey.Resize(nPriKeyLen);
  578. return Error_Succeed;
  579. }
  580. // 保存到令牌管理实体中
  581. DWORD CAccessAuthEntity::SaveSM2KeyPair(const CBlob &pubKey, const CBlob &priKey)
  582. {
  583. LOG_FUNCTION();
  584. CSimpleStringA strErrMsg;
  585. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  586. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  587. DWORD rc = pTokenServiceClient->Connect();
  588. if (rc != Error_Succeed)
  589. {
  590. strErrMsg = "连接令牌管理实体失败";
  591. SetAuthErrMsg((const char *)strErrMsg);
  592. rc = ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE;
  593. m_FSM.doWarnMsg(rc,
  594. GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", strErrMsg).c_str());
  595. pTokenServiceClient->SafeDelete();
  596. }
  597. else
  598. {
  599. TokenService_SetKeyPair_Req req;
  600. req.pub_key = pubKey;
  601. req.pri_key = priKey;
  602. TokenService_SetKeyPair_Ans ans;
  603. rc = pTokenServiceClient->SetKeyPair(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
  604. pTokenServiceClient->GetFunction()->CloseSession();
  605. if (rc != Error_Succeed)
  606. {
  607. strErrMsg = "保存密钥对失败";
  608. SetAuthErrMsg((const char *)strErrMsg);
  609. rc = ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_KEYS;
  610. m_FSM.doWarnMsg(rc,
  611. GetOutPutStr("%s%08X%s%s", "SetKeyPair", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  612. }
  613. else
  614. Dbg("set sm2 key pair succ");
  615. }
  616. return rc;
  617. }
  618. ErrorCodeEnum CAccessAuthEntity::SaveTokenAndSharedSK(const CBlob &token, const CBlob &sharedSK)
  619. {
  620. LOG_FUNCTION();
  621. CSimpleStringA strErrMsg;
  622. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  623. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  624. ErrorCodeEnum rc = pTokenServiceClient->Connect();
  625. if (rc != Error_Succeed)
  626. {
  627. strErrMsg = "连接令牌管理实体失败";
  628. SetAuthErrMsg((const char *)strErrMsg);
  629. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE,
  630. GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  631. pTokenServiceClient->SafeDelete();
  632. }
  633. else
  634. {
  635. TokenService_SetToken_Req req = {};
  636. req.token = token;
  637. TokenService_SetToken_Ans ans;
  638. rc = pTokenServiceClient->SetToken(req, ans, 5000);
  639. if (rc == Error_Succeed)
  640. Dbg("save token succ, token: [%s]", ByteArrayToHexStr((BYTE*)token.m_pData, token.m_iLength).c_str());
  641. else
  642. {
  643. strErrMsg = "保存令牌失败";
  644. SetAuthErrMsg((const char *)strErrMsg);
  645. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_TOKEN,
  646. GetOutPutStr("%s%08X%s%s", "SetToken", rc,"strErrMsg", strErrMsg).c_str());
  647. }
  648. TokenService_SetSharedSK_Req req2 = {};
  649. req2.ssk = sharedSK;
  650. TokenService_SetSharedSK_Ans ans2 = {};
  651. rc = pTokenServiceClient->SetSharedSK(req2, ans2, 5000);
  652. if (rc == Error_Succeed)
  653. Dbg("save shared session key succ");
  654. else
  655. {
  656. strErrMsg = "保存会话密钥失败";
  657. SetAuthErrMsg((const char *)strErrMsg);
  658. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_SHAREKEY,
  659. GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  660. }
  661. pTokenServiceClient->GetFunction()->CloseSession();
  662. }
  663. return rc;
  664. }
  665. bool CAccessAuthEntity::HasPinPad()
  666. {
  667. CSimpleStringA strErrMsg;
  668. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  669. //oilyang@20210514
  670. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  671. {
  672. Dbg("MachineType[%s], not exist pinpad", m_info.strMachineType);
  673. return false;
  674. }
  675. else if (stricmp(m_info.strMachineType, "RVC.PAD") == 0) // Pad机型
  676. {
  677. // 根据PinPad实体状态确定是否连接密码键盘
  678. bool bPinPadExist = false;
  679. auto pPinPadClient = new PinPadService_ClientBase(this);
  680. if (pPinPadClient->Connect() != Error_Succeed)
  681. {
  682. Dbg("connect PinPad fail, assume no pinpad");
  683. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  684. GetOutPutStr("%s%s", "连接pinpad错误", "False").c_str());
  685. pPinPadClient->SafeDelete();
  686. }
  687. else
  688. {
  689. PinPadService_GetDevInfo_Req req = {};
  690. PinPadService_GetDevInfo_Ans ans = {};
  691. auto rc = pPinPadClient->GetDevInfo(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
  692. if (rc != Error_Succeed)
  693. {
  694. strErrMsg = "PinPad::GetDevInfo() fail";
  695. SetAuthErrMsg((const char *)strErrMsg);
  696. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  697. GetOutPutStr("%s%08X", "来自pinpad的错误", rc).c_str(), strErrMsg.GetData());
  698. }
  699. else
  700. {
  701. Dbg("PinPad::GetDevInfo() return state: %d", ans.state);
  702. bPinPadExist = ans.state != DEVICE_STATUS_NOT_READY;
  703. }
  704. pPinPadClient->GetFunction()->CloseSession();
  705. }
  706. pPinPadClient = NULL;
  707. return bPinPadExist;
  708. }
  709. else
  710. {
  711. // 其它VTM机型,全部有内置密码键盘
  712. return true;
  713. }
  714. }
  715. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  716. // 由当前已初始化的密钥文件决定,兼容旧版本终端
  717. int CAccessAuthEntity::GetPinPadCapability()
  718. {
  719. int nCapability = 0;
  720. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  721. return nCapability;
  722. PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
  723. auto rc = pPinPad->Connect();
  724. if (rc == Error_Succeed)
  725. {
  726. PinPadService_QueryFunc_Req req;
  727. PinPadService_QueryFunc_Ans ans;
  728. rc = pPinPad->QueryFunc(req,ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
  729. if (rc == Error_Succeed)
  730. {
  731. nCapability = ans.reserved1;
  732. Dbg("QueryFunc from pinpad succ, nCapability[%d]", nCapability);
  733. }
  734. else
  735. {
  736. SetAuthErrMsg("从PinPad获取主密钥类型失败");
  737. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  738. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  739. GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
  740. }
  741. pPinPad->GetFunction()->CloseSession();
  742. }
  743. else
  744. {
  745. SetAuthErrMsg("连接PinPad实体失败");
  746. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  747. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  748. GetOutPutStr("%s%08X%s%s", "Connect", rc,"AuthErrMsg", "连接PinPad实体失败").c_str());
  749. pPinPad->SafeDelete();
  750. }
  751. return nCapability;
  752. }
  753. void CAccessAuthEntity::printPasswdError(){
  754. string strErrMsg = "密钥集丢失,请重新初始化密钥!";
  755. SetAuthErrMsg(strErrMsg.c_str());
  756. GetFunction()->SetSysVar("AuthErrMsg", strErrMsg.c_str(), true);
  757. m_FSM.doWarnMsg( ERROR_ACCESSAUTH_OPENCRYPTCONTEXT, strErrMsg.c_str(),true, strErrMsg);
  758. }
  759. int Char2Int(char * ch) {
  760. int num = 0;
  761. for (int i = 0;i < strlen(ch);i++) {
  762. num += ((int)(ch[i] - '0')) * pow((float)10, (float)(strlen(ch) - i - 1));
  763. }
  764. return num;
  765. }
  766. bool CAccessAuthEntity::SaveAuthKey(BYTE *pKey)
  767. {
  768. LOG_FUNCTION();
  769. //m_nAuthVersion = nAuthVer;
  770. memset(m_AuthSessionKey, 0, 140);
  771. CSimpleString runInfoPath, iniPath;
  772. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  773. if (rc != Error_Succeed) {
  774. Dbg("GetPath runinfo error=%d.", rc);
  775. return false;
  776. }
  777. char privateKey[BUF_SIZE] = { 0 };
  778. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
  779. //runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  780. #ifdef RVC_OS_WIN
  781. GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, runInfoPath.GetData());
  782. #else
  783. Dbg("path ex:%s", iniPath.GetData());
  784. char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
  785. strcpy(privateKey, tmp);
  786. delete tmp;
  787. #endif // RVC_OS_WIN
  788. if (strlen(privateKey) <= 0) {
  789. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  790. char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
  791. strcpy(privateKey, tmp2);
  792. delete tmp2;
  793. if (strlen(privateKey) <= 0)
  794. {
  795. printPasswdError();
  796. return false;
  797. }
  798. }
  799. Dbg("privateKey=%s,%d", privateKey, strlen(privateKey));
  800. int decodedPrivateKeyLen;
  801. char* pDecodedPrivateKey = Hex2Str(privateKey, decodedPrivateKeyLen);
  802. Dbg("decodedPrivateKeyLen=%d", decodedPrivateKeyLen);
  803. char pDecryptPrivateKey[BUF_SIZE] = { 0 };
  804. int decryprtLen = BUF_SIZE;
  805. if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
  806. Dbg("DecWithSM4_ECB decrypt privateKey error.");
  807. printPasswdError();
  808. delete[] pDecodedPrivateKey;
  809. return false;
  810. }
  811. delete[] pDecodedPrivateKey;
  812. //添加调试信息
  813. char* pEncPriKey = Str2Hex((char*)pDecryptPrivateKey, decryprtLen);
  814. Dbg("DecWithSM4_ECB succeess.privateKey=%s", pEncPriKey);
  815. delete pEncPriKey;
  816. char pPlainKey[KEY_SIZE];
  817. int plainKeyLen = KEY_SIZE;
  818. char pKeyLen[4] = { 0 };
  819. memcpy(pKeyLen, pKey, 4);
  820. int kenLen = Char2Int(pKeyLen);
  821. Dbg("kenLen=%d", kenLen);
  822. char* pEncodeKey = Str2Hex((char*)pKey, kenLen + 4);
  823. Dbg("pEncodeKey=%s", pEncodeKey);
  824. delete pEncodeKey;
  825. char* key = new char[kenLen + 1];
  826. memset(key, 0, kenLen + 1);
  827. memcpy(key, pKey + 4, kenLen);
  828. if (!DecWithSM2PriKey((BYTE*)key, kenLen, (BYTE*)pPlainKey, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  829. Dbg("使用私钥解密失败!");
  830. printPasswdError();
  831. return false;
  832. }
  833. Dbg("使用私钥解密成功");
  834. if (plainKeyLen != KEY_SIZE) {
  835. Dbg("私钥解密后的会话密钥长度不等于16!");
  836. }
  837. memcpy(m_AuthSessionKey, pPlainKey, KEY_SIZE);
  838. return true;
  839. }
  840. static BYTE* ConvertHexStrToBytes(const char *pszStr)
  841. {
  842. if (pszStr == NULL || strlen(pszStr) == 0)
  843. return NULL;
  844. int nLen = strlen(pszStr) / 2;
  845. BYTE *pRet = (BYTE*)malloc(nLen);
  846. memset(pRet, 0, nLen);
  847. for (int i = 0; i < nLen; i++)
  848. {
  849. int nTmp(0);
  850. if (sscanf(&pszStr[i * 2], "%2X", &nTmp) != 1)
  851. {
  852. free(pRet);
  853. return NULL;
  854. }
  855. pRet[i] = (BYTE)nTmp;
  856. }
  857. return pRet;
  858. }
  859. // 使用准入会话密钥加密
  860. ErrorCodeEnum CAccessAuthEntity::EncryptDataWithSessionKey(const CBlob &raw, CBlob &enc)
  861. {
  862. LOG_FUNCTION();
  863. //assert(m_nAuthVersion ==2);
  864. //这里不需要delete,由CBlob析构函数去执行
  865. BYTE* pEncData = new BYTE[1024];
  866. int pEncDataSize = 1024;
  867. Dbg("pEncDataSize=%d", pEncDataSize);
  868. char* pPlainInfo = Str2Hex((char*)raw.m_pData, raw.m_iLength);
  869. Dbg("raw data=%s,raw.m_iLength=%d", pPlainInfo, raw.m_iLength);
  870. delete[] pPlainInfo;
  871. //char *sessionKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  872. char sessionKey[KEY_SIZE] = { 0 };
  873. memcpy(sessionKey,m_AuthSessionKey,KEY_SIZE);
  874. char* tmpKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  875. Dbg("sessionKey=%s", tmpKey);
  876. delete[] tmpKey;
  877. if (!EncWithSM4_ECB((BYTE*)sessionKey, (BYTE*)(raw.m_pData), raw.m_iLength, pEncData, &pEncDataSize)) {
  878. Dbg("会话密钥加密准入信息失败!");
  879. return Error_Unexpect;
  880. }
  881. enc.Attach(pEncData,pEncDataSize);
  882. char* tmp = Str2Hex((char*)pEncData, pEncDataSize);
  883. Dbg("pEncData=%s,%d", tmp, pEncDataSize);
  884. delete[] tmp;
  885. tmp = Str2Hex((char*)enc.m_pData, enc.m_iLength);
  886. Dbg("EncWithSM4_ECB data=%s,%d", tmp, enc.m_iLength);
  887. delete[] tmp;
  888. return Error_Succeed;
  889. }
  890. bool CAccessAuthEntity::GetMD5Hash(const char *pStr, BYTE md5[16])
  891. {
  892. return false;
  893. }
  894. static char* ConvertBytesToHexStr(BYTE *pBuf, int nLen)
  895. {
  896. char *pRet = (char*)malloc(nLen * 2 + 1);
  897. memset(pRet, 0, nLen * 2 + 1);
  898. char *p = pRet;
  899. for (int i = 0; i < nLen; i++)
  900. {
  901. BYTE b = pBuf[i];
  902. BYTE l = (b >> 4) & 0x0F;
  903. if (l >= 10)
  904. *p = l - 10 + 'A';
  905. else
  906. *p = l + '0';
  907. p++;
  908. BYTE r = b & 0x0F;
  909. if (r >= 10)
  910. *p = r - 10 + 'A';
  911. else
  912. *p = r + '0';
  913. p++;
  914. }
  915. return pRet;
  916. }
  917. bool CAccessAuthEntity::GetTerminalFingerPrint(BYTE *pBuf, int &nBufLen)
  918. {
  919. char szTmp[1024] = {};
  920. string strTmp;
  921. int nTmpBufLen = 1024;
  922. CSimpleStringA strErrMsg;
  923. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  924. CSimpleStringA strRet;
  925. #ifdef RVC_OS_WIN
  926. if (!QueryWMIDevice(Processor, "ProcessorId", szTmp, &nTmpBufLen))
  927. #else
  928. CSimpleStringA runInfoPath;
  929. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  930. if (rc != Error_Succeed) {
  931. Dbg("GetPath runinfo error=%d.", rc);
  932. return false;
  933. }
  934. runInfoPath += SPLIT_SLASH_STR "runcfg";
  935. if (!get_cpu_id_by_system(strTmp, runInfoPath.GetData()))
  936. #endif // RVC_OS_WIN
  937. {
  938. strErrMsg = CSimpleStringA::Format("查询CPU ID失败,请重启机器并重新初始化");
  939. SetAuthErrMsg((const char *)strErrMsg);
  940. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  941. GetOutPutStr("%s%s", "Processor", "False").c_str());
  942. return false;
  943. }
  944. #ifdef RVC_OS_WIN
  945. strRet = szTmp;
  946. nTmpBufLen = 1024;
  947. memset(szTmp, 0, sizeof(szTmp));
  948. if (!QueryWMIDevice(BaseBoard, "SerialNumber", szTmp, &nTmpBufLen))
  949. #else
  950. Dbg("cpu id: %s", strTmp.c_str());
  951. strRet = strTmp.c_str();
  952. strTmp.clear();
  953. if (!get_board_serial_by_system(strTmp, runInfoPath.GetData()))
  954. #endif // RVC_OS_WIN
  955. {
  956. strErrMsg = CSimpleStringA::Format("查询主板序列号失败, 请重启机器并重新初始化");
  957. SetAuthErrMsg((const char *)strErrMsg);
  958. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  959. GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
  960. return false;
  961. }
  962. strRet += "|";
  963. #ifdef RVC_OS_WIN
  964. strRet += szTmp;
  965. nTmpBufLen = 1024;
  966. memset(szTmp, 0, sizeof(szTmp));
  967. if (!QueryWMIDevice(DiskDrive, "SerialNumber", szTmp, &nTmpBufLen))
  968. #else
  969. Dbg("baseboard sn: %s", strTmp.c_str());
  970. strRet += strTmp.c_str();
  971. vector<string> disk;
  972. int errCode = 0;
  973. if (!get_disk_serial_by_system(disk, errCode, runInfoPath.GetData()))
  974. #endif // RVC_OS_WIN
  975. {
  976. Dbg("get_disk_serial_by_system errCode:%d", errCode);
  977. strErrMsg = CSimpleStringA::Format("查询磁盘序列号失败, 请重启机器并重新初始化");
  978. SetAuthErrMsg((const char*)strErrMsg);
  979. m_FSM.doWarnMsg(ERR_INITIALIZER_GET_DISKDRIVE_ID,
  980. GetOutPutStr("%s%s", "DiskDrive", "False").c_str());
  981. return false;
  982. }
  983. strRet += "|";
  984. #ifdef RVC_OS_WIN
  985. strRet += szTmp;
  986. #else
  987. strTmp = "";
  988. vector<string>::iterator it = disk.begin();
  989. while (it != disk.end()) {
  990. strTmp += *it;
  991. it++;
  992. }
  993. Dbg("harddisk sn: %s", strTmp.c_str());
  994. strRet += strTmp.c_str();
  995. #endif // RVC_OS_WIN
  996. Dbg("device info: [%s]", (const char*)strRet);
  997. BYTE sm3[32] = { 0 };
  998. if(!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())),strRet.GetLength(),sm3))
  999. {
  1000. strErrMsg = "get sm3 hash as fingerprint fail";
  1001. SetAuthErrMsg((const char *)strErrMsg);
  1002. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  1003. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char *)strErrMsg);
  1004. return false;
  1005. }
  1006. if (nBufLen < 32)
  1007. {
  1008. //Dbg("buf len is too small");
  1009. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, "buf len is too small fail");
  1010. return false;
  1011. }
  1012. nBufLen = 32;
  1013. memcpy(pBuf, sm3, nBufLen);
  1014. char *pszSM3 = ConvertBytesToHexStr(sm3, nBufLen);
  1015. Dbg("fringerprint: [%s]", pszSM3);
  1016. free(pszSM3);
  1017. return true;
  1018. }
  1019. // 生成SM2密钥对,并导出公钥
  1020. bool CAccessAuthEntity::GetTerminalPublicKey(BYTE *pBuf, int &nBufLen)
  1021. {
  1022. CSimpleString runInfoPath, iniPath;
  1023. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  1024. if (rc != Error_Succeed) {
  1025. Dbg("GetPath runinfo error=%d.", rc);
  1026. return false;
  1027. }
  1028. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
  1029. //runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  1030. char publicKey[BUF_SIZE] = { 0 };
  1031. #ifdef RVC_OS_WIN
  1032. GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, runInfoPath.GetData());
  1033. #else
  1034. char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
  1035. strcpy(publicKey, tmp);
  1036. delete tmp;
  1037. #endif // RVC_OS_WIN
  1038. if (strlen(publicKey) <= 0) {
  1039. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  1040. char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
  1041. strcpy(publicKey, tmp2);
  1042. delete tmp2;
  1043. if (strlen(publicKey) <= 0)
  1044. {
  1045. Dbg("读取公钥失败,公钥长度小于等于零!");
  1046. printPasswdError();
  1047. return false;
  1048. }
  1049. }
  1050. Dbg("publickey=%s,%d",publicKey,strlen(publicKey));
  1051. char* pDecodedPublickey = Hex2Str(publicKey,nBufLen);
  1052. Dbg("pDecodedPublickey=[%s],len=%d", pDecodedPublickey, nBufLen);
  1053. memcpy(pBuf, pDecodedPublickey, nBufLen);
  1054. Dbg("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
  1055. delete[] pDecodedPublickey;
  1056. return true;
  1057. }
  1058. // 生成RSA密钥对,并导出公钥
  1059. bool CAccessAuthEntity::GetTerminalPublicKey(BYTE *pBuf, int &nBufLen,string &pubkey)
  1060. {
  1061. LOG_FUNCTION();
  1062. CSimpleString runInfoPath;
  1063. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  1064. if (rc != Error_Succeed) {
  1065. Dbg("GetPath runinfo error=%d.",rc);
  1066. return false;
  1067. }
  1068. runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR;
  1069. /*if (!boost::filesystem::exists(runInfoPath.GetData())) {
  1070. boost::filesystem::create_directories(runInfoPath.GetData());
  1071. }*/
  1072. #ifdef RVC_OS_WIN
  1073. DWORD dwAttr = GetFileAttributes(runInfoPath.GetData());
  1074. if (dwAttr == 0xFFFFFFFF) //目录不存在则创建
  1075. {
  1076. if (!CreateDirectory(runInfoPath.GetData(), NULL))
  1077. #else
  1078. if(!dir_is_exist(runInfoPath.GetData()))
  1079. {
  1080. if(dir_create(runInfoPath.GetData()) != 0)
  1081. #endif
  1082. {
  1083. Dbg("Create %s dir failed!", runInfoPath.GetData());
  1084. }
  1085. }
  1086. Dbg("Dir=%s", runInfoPath.GetData());
  1087. //CSimpleString runFile = runInfoPath + GetEntityName();
  1088. CSmartPointer<IConfigInfo> pConfig;
  1089. rc = GetFunction()->OpenConfig(Config_Run, pConfig);
  1090. if (rc != Error_Succeed) {
  1091. Dbg("OpenConfig Config_Run error=%d.", rc);
  1092. return false;
  1093. }
  1094. CSimpleString publicKey;
  1095. rc = pConfig->ReadConfigValue("TerminalPD","PublicKey",publicKey);
  1096. if (rc != Error_Succeed || publicKey.IsNullOrEmpty()) {
  1097. Dbg("ReadConfig publicKey error=%d or publicKey is NULL.", rc);
  1098. BYTE btPublicKey[BUF_SIZE] = { 0 }, btPrivateKey[BUF_SIZE] = { 0 };
  1099. int iPublicKeyLen = sizeof(btPublicKey);
  1100. int iPrivateKeyLen = sizeof(btPrivateKey);
  1101. if (!::CreateSM2KeyPair(btPublicKey, &iPublicKeyLen, btPrivateKey, &iPrivateKeyLen)) {
  1102. Dbg("Create SM2 key pair error.");
  1103. return false;
  1104. }
  1105. Dbg("iPublicKeyLen=%d,iPrivateKeyLen=%d", iPublicKeyLen, iPrivateKeyLen);
  1106. Dbg("[btPublicKey=%s]", (char*)btPublicKey);
  1107. char* pEncode = Str2Hex((char*)btPublicKey,iPublicKeyLen);
  1108. Dbg("pEncode=%s,%d", pEncode,strlen(pEncode));
  1109. //尝试解码
  1110. /*int pDecodeLen = 0;
  1111. char* pDecode = Hex2Str(pEncode,pDecodeLen);
  1112. Dbg("pDecode=%s", pDecode);
  1113. Dbg("pDecodeLen=%d", pDecodeLen);
  1114. char *ret = Str2Hex(pDecode, pDecodeLen);
  1115. Dbg("ret=%s,%d", ret, strlen(ret));
  1116. if (strcmp(ret, pEncode)!=0) {
  1117. Dbg("No");
  1118. return false;
  1119. }
  1120. Dbg("Yes");
  1121. delete[] pDecode;
  1122. delete[] ret;*/
  1123. rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", pEncode);
  1124. assert(rc == Error_Succeed);
  1125. pubkey = pEncode;
  1126. Dbg("write public key success.");
  1127. BYTE pCryptPrivateKey[BUF_SIZE] = { 0 };
  1128. int cryptPrivateKeyLen = BUF_SIZE;
  1129. if (!EncWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", btPrivateKey, iPrivateKeyLen, pCryptPrivateKey, &cryptPrivateKeyLen)) {
  1130. Dbg("sm4 crypt privateKey error.");
  1131. rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
  1132. delete[] pEncode;
  1133. return false;
  1134. }
  1135. Dbg("sm4 encrypt pri key success.");
  1136. Dbg("cryptPrivateKeyLen=%d", cryptPrivateKeyLen);
  1137. char* pEncodedCryptPrivateKey = Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
  1138. Dbg("encode pri key success.");
  1139. rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", pEncodedCryptPrivateKey);
  1140. if (rc != Error_Succeed) {
  1141. rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
  1142. delete[] pEncodedCryptPrivateKey;
  1143. return false;
  1144. }
  1145. Dbg("write pri key success.");
  1146. publicKey = pEncode;
  1147. delete[] pEncode;
  1148. delete[] pEncodedCryptPrivateKey;
  1149. }
  1150. else
  1151. {
  1152. pubkey = publicKey;
  1153. }
  1154. Dbg("PublicKey: %s(%d)", publicKey.GetData(), publicKey.GetLength());
  1155. char *pDecode = Hex2Str(publicKey.GetData(),nBufLen);
  1156. memcpy(pBuf, pDecode, nBufLen);
  1157. Dbg("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
  1158. return true;
  1159. }
  1160. DWORD CAccessAuthEntity::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer &ctx)
  1161. {
  1162. return m_FSM.InitDevice(ctx);
  1163. }
  1164. //oilyang@20210510 嵌入"bool CAccessAuthEntity::HasPinPad()"的逻辑
  1165. // 返回1:只有PinPadID;2:只有DeviceID;3:两者都有;0:没有;-1表示失败
  1166. int CAccessAuthEntity::GetPinPadIDAndDeviceID(CSimpleStringA &strPinPadID, CSimpleStringA &strDeviceID, bool& bHasPinPad)
  1167. {
  1168. bHasPinPad = false;
  1169. CSimpleStringA strErrMsg;
  1170. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  1171. //oilyang@20210514
  1172. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  1173. return 0;
  1174. int nRet = -1;
  1175. auto pPinPadClient = new PinPadService_ClientBase(this);
  1176. bool bPinPadID = false;
  1177. bool bDeviceID = false;
  1178. bool bVendor = false;
  1179. bool bBluetooth = false;
  1180. CSimpleStringA strVendor;
  1181. CSimpleStringA strBluetoothID;
  1182. CSimpleStringA strPID;
  1183. CSimpleStringA strMID;
  1184. bHasPinPad = true;
  1185. auto rc = 0;
  1186. if ( (rc = pPinPadClient->Connect()) == Error_Succeed)
  1187. {
  1188. PinPadService_GetDevInfo_Req req = {};
  1189. PinPadService_GetDevInfo_Ans ans = {};
  1190. rc = pPinPadClient->GetDevInfo(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
  1191. if (rc == Error_Succeed) {
  1192. if (ans.state == DEVICE_STATUS_NORMAL) {
  1193. nRet = 0;
  1194. Dbg("pinpad model: %s", (const char*)ans.model);
  1195. // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
  1196. // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
  1197. CSimpleStringA str = ans.model;
  1198. if (!str.IsNullOrEmpty())
  1199. {
  1200. auto arr = str.Split('#');
  1201. if (arr.GetCount() > 0)
  1202. {
  1203. for (int i = 0; i < arr.GetCount(); i++)
  1204. {
  1205. auto arr2 = arr[i].Split('=');
  1206. if (arr2.GetCount() != 2)
  1207. continue;
  1208. //if (arr2[0] == "PID")
  1209. if(!strnicmp((LPCTSTR)arr2[0], "PID", strlen("PID")))
  1210. {
  1211. strPID = arr2[1];
  1212. if (!strPID.IsNullOrEmpty())
  1213. bPinPadID = true;
  1214. }
  1215. //else if (arr2[0] == "MID")
  1216. else if(!strnicmp((LPCTSTR)arr2[0], "MID", strlen("MID")))
  1217. {
  1218. strMID = arr2[1];
  1219. if (!strMID.IsNullOrEmpty())
  1220. bDeviceID = true;
  1221. }
  1222. //else if (arr2[0] == "Vendor")
  1223. else if(!strnicmp((LPCTSTR)arr2[0], "Vendor", strlen("Vendor")))
  1224. {
  1225. strVendor = arr2[1];
  1226. if (!strVendor.IsNullOrEmpty())
  1227. bVendor = true;
  1228. }
  1229. else if (!strnicmp((LPCTSTR)arr2[0], "FWBID", strlen("FWBID")))
  1230. {
  1231. strBluetoothID = arr2[1];
  1232. Dbg("strBluetoothID=%s", strBluetoothID);
  1233. if (!strBluetoothID.IsNullOrEmpty())
  1234. bBluetooth = true;
  1235. }
  1236. }
  1237. }
  1238. }
  1239. }
  1240. else
  1241. {
  1242. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1243. bHasPinPad = false;
  1244. Dbg("pinpad not exist, state: %d", ans.state);
  1245. }
  1246. }
  1247. else
  1248. {
  1249. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1250. bHasPinPad = false;
  1251. strErrMsg = "调用PinPad实体的GetDevInfo方法失败";
  1252. SetAuthErrMsg((const char *)strErrMsg);
  1253. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  1254. GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg ).c_str());
  1255. }
  1256. pPinPadClient->GetFunction()->CloseSession();
  1257. }
  1258. else
  1259. {
  1260. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1261. bHasPinPad = false;
  1262. strErrMsg = "连接PinPad实体失败";
  1263. SetAuthErrMsg((const char *)strErrMsg);
  1264. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  1265. GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
  1266. pPinPadClient->SafeDelete();
  1267. }
  1268. pPinPadClient = NULL;
  1269. if (bPinPadID)
  1270. {
  1271. if (bVendor)
  1272. strPinPadID = strVendor + "_" + strPID;
  1273. else
  1274. strPinPadID = strPID;
  1275. nRet += 1;
  1276. }
  1277. if (bDeviceID)
  1278. {
  1279. if (bVendor)
  1280. strDeviceID = strVendor + "_" + strMID;
  1281. else
  1282. strDeviceID = strMID;
  1283. if (bBluetooth)
  1284. strDeviceID = strDeviceID + "_" + strBluetoothID;
  1285. nRet += 2;
  1286. }
  1287. else if (bBluetooth)
  1288. {
  1289. strDeviceID = strDeviceID + "_" + strBluetoothID;
  1290. nRet += 2;
  1291. }
  1292. return nRet;
  1293. }
  1294. bool CAccessAuthEntity::HasCkCodeFlg()
  1295. {
  1296. CSimpleStringA strErrMsg;
  1297. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  1298. //oilyang@20210514
  1299. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  1300. {
  1301. Dbg("MachineType is [%s], not exist pinpad entity", m_info.strMachineType);
  1302. return false;
  1303. }
  1304. auto pPinPadClient = new PinPadService_ClientBase(this);
  1305. bool bCheckCode = false;
  1306. CSimpleStringA strSpeficiCM;
  1307. if (pPinPadClient->Connect() == Error_Succeed)
  1308. {
  1309. PinPadService_GetDevInfo_Req req = {};
  1310. PinPadService_GetDevInfo_Ans ans = {};
  1311. auto rc = pPinPadClient->GetDevInfo(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
  1312. if (rc == Error_Succeed)
  1313. {
  1314. if (ans.state == DEVICE_STATUS_NORMAL)
  1315. {
  1316. Dbg("pinpad model: %s", (const char*)ans.model);
  1317. // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
  1318. // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
  1319. CSimpleStringA str = ans.model;
  1320. if (!str.IsNullOrEmpty())
  1321. {
  1322. auto arr = str.Split('#');
  1323. if (arr.GetCount() > 0)
  1324. {
  1325. for (int i = 0; i < arr.GetCount(); i++)
  1326. {
  1327. auto arr2 = arr[i].Split('=');
  1328. if (arr2.GetCount() != 2)
  1329. continue;
  1330. if(!strnicmp((LPCTSTR)arr2[0], "CM", strlen("CM")))
  1331. {
  1332. strSpeficiCM = arr2[1];
  1333. if (strSpeficiCM.GetLength() > 3 && _strnicmp(strSpeficiCM, "V2.0", strlen("V2.0")) == 0)
  1334. {
  1335. //Support checkcode, then operate checkcode routine..
  1336. bCheckCode = true;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. else
  1344. {
  1345. Dbg("pinpad not exist, state: %d", ans.state);
  1346. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  1347. GetOutPutStr("%s%d", "密码键盘异常,请检查。ans.state", ans.state).c_str());
  1348. }
  1349. }
  1350. else
  1351. {
  1352. strErrMsg = "调用PinPad实体(GetDevInfo)失败";
  1353. SetAuthErrMsg((const char *)strErrMsg);
  1354. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  1355. GetOutPutStr("%s%08X", "GetDevInfo", rc).c_str(), strErrMsg.GetData());
  1356. }
  1357. pPinPadClient->GetFunction()->CloseSession();
  1358. }
  1359. else
  1360. {
  1361. strErrMsg = "连接PinPad实体失败";
  1362. SetAuthErrMsg((const char *)strErrMsg);
  1363. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  1364. GetOutPutStr("%s%s", "连接pinpad错误, strErrMsg", strErrMsg).c_str());
  1365. pPinPadClient->SafeDelete();
  1366. }
  1367. pPinPadClient = NULL;
  1368. return bCheckCode? true:false;
  1369. }
  1370. wstring CAccessAuthEntity::ANSIToUnicode(const string& str)
  1371. {
  1372. int len = 0;
  1373. len = str.length();
  1374. int unicodeLen = ::MultiByteToWideChar(CP_ACP,
  1375. 0,
  1376. str.c_str(),
  1377. -1,
  1378. NULL,
  1379. 0);
  1380. wchar_t * pUnicode;
  1381. pUnicode = new wchar_t[unicodeLen+1];
  1382. memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
  1383. ::MultiByteToWideChar( CP_ACP,
  1384. 0,
  1385. str.c_str(),
  1386. -1,
  1387. (LPWSTR)pUnicode,
  1388. unicodeLen);
  1389. wstring rt;
  1390. rt = (wchar_t*)pUnicode;
  1391. delete pUnicode;
  1392. return rt;
  1393. }
  1394. //China Standard Time
  1395. BOOL CAccessAuthEntity::SetLocalTimeZoneByKeyName(const TCHAR* szTimeZoneKeyName, BOOL isDaylightSavingTime)
  1396. {
  1397. #ifdef RVC_OS_WIN
  1398. HKEY hKey;
  1399. LONG ErrorCode;
  1400. TCHAR szSubKey[256];
  1401. TCHAR szStandardName[32];
  1402. TCHAR szDaylightName[32];
  1403. REG_TZI_FORMAT regTZI;
  1404. DWORD dwByteLen;
  1405. // 检测入口参数
  1406. if ((szTimeZoneKeyName == NULL) || (strlen(szTimeZoneKeyName) == 0))
  1407. {
  1408. // 时区标识符不能为空
  1409. return FALSE;
  1410. }
  1411. StringCchCopy(szSubKey, 256, TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"));
  1412. StringCchCat(szSubKey, 256, szTimeZoneKeyName);
  1413. ErrorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_QUERY_VALUE, &hKey);
  1414. if (ErrorCode != ERROR_SUCCESS)
  1415. {
  1416. Dbg("RegOpenKeyEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time fail");
  1417. return FALSE;
  1418. }
  1419. // 标准名
  1420. dwByteLen = sizeof(szStandardName);
  1421. ErrorCode = RegQueryValueEx(hKey, TEXT("Std"), NULL, NULL, reinterpret_cast<LPBYTE>(&szStandardName), &dwByteLen);
  1422. if (ErrorCode != ERROR_SUCCESS)
  1423. {
  1424. RegCloseKey(hKey);
  1425. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Std fail");
  1426. return FALSE;
  1427. }
  1428. // 夏时制名
  1429. dwByteLen = sizeof(szDaylightName);
  1430. ErrorCode = RegQueryValueEx(hKey, TEXT("Dlt"), NULL, NULL, reinterpret_cast<LPBYTE>(&szDaylightName), &dwByteLen);
  1431. if (ErrorCode != ERROR_SUCCESS)
  1432. {
  1433. RegCloseKey(hKey);
  1434. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Dlt fail");
  1435. return FALSE;
  1436. }
  1437. // 时区信息
  1438. dwByteLen = sizeof(regTZI);
  1439. ErrorCode = RegQueryValueEx(hKey, TEXT("TZI"), NULL, NULL, reinterpret_cast<LPBYTE>(&regTZI), &dwByteLen);
  1440. RegCloseKey(hKey);
  1441. if ((ErrorCode != ERROR_SUCCESS) || (dwByteLen > sizeof(regTZI)))
  1442. {
  1443. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\TZI fail");
  1444. return FALSE;
  1445. }
  1446. // 开启权限
  1447. HANDLE hToken;
  1448. TOKEN_PRIVILEGES tkp;
  1449. BOOL isOK;
  1450. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken))
  1451. {
  1452. Dbg("OpenProcessToken Standard Time\\Dlt fail");
  1453. return FALSE;
  1454. }
  1455. LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &tkp.Privileges[0].Luid);
  1456. tkp.PrivilegeCount = 1;
  1457. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1458. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1459. if (GetLastError() != ERROR_SUCCESS)
  1460. {
  1461. CloseHandle(hToken);
  1462. Dbg("AdjustTokenPrivileges fail");
  1463. return FALSE;
  1464. }
  1465. // 设置新时区
  1466. DYNAMIC_TIME_ZONE_INFORMATION tzi;
  1467. tzi.Bias = regTZI.Bias;
  1468. tzi.StandardDate = regTZI.StandardDate;
  1469. tzi.StandardBias = regTZI.StandardBias;
  1470. tzi.DaylightDate = regTZI.DaylightDate;
  1471. tzi.DaylightBias = regTZI.DaylightBias;
  1472. tzi.DynamicDaylightTimeDisabled = !isDaylightSavingTime;
  1473. wcscpy(tzi.StandardName, ANSIToUnicode(szStandardName).c_str());
  1474. wcscpy(tzi.DaylightName, ANSIToUnicode(szDaylightName).c_str());
  1475. wcscpy(tzi.TimeZoneKeyName, ANSIToUnicode(szTimeZoneKeyName).c_str());
  1476. isOK = SetDynamicTimeZoneInformation(&tzi); // 设置动态时区
  1477. if (!isOK)
  1478. {
  1479. Dbg("SetDynamicTimeZoneInformation fail");
  1480. }
  1481. // 关闭权限
  1482. tkp.Privileges[0].Attributes = 0;
  1483. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1484. CloseHandle(hToken);
  1485. return isOK;
  1486. #else
  1487. //temporarily not relased at linux
  1488. return TRUE;
  1489. #endif // RVC_OS_WIN
  1490. }
  1491. int CAccessAuthEntity::ConvertStr2Byte(string input, BYTE* output, int outputLen) {
  1492. if (input.size() > outputLen) return 1;
  1493. for (int i = 0;i < input.size();i++) {
  1494. output[i] = input[i];
  1495. }
  1496. return 0;
  1497. }
  1498. int CAccessAuthEntity::GetOrSetIsFirstSM(int type) {
  1499. CSmartPointer<IConfigInfo> pConfig;
  1500. int isFirst = 0;
  1501. auto rc = GetFunction()->OpenConfig(Config_Run, pConfig);
  1502. if (rc != Error_Succeed) {
  1503. Dbg("OpenConfig Config_Run error=%d.", rc);
  1504. return isFirst;
  1505. }
  1506. CSimpleStringA sIsFirst;
  1507. if (type == 0) {
  1508. return 0;//oilyang@20211208 这个逻辑没有存在的必要了
  1509. rc = pConfig->ReadConfigValue("SM", "IsFirst", sIsFirst);
  1510. if (rc != Error_Succeed || sIsFirst.IsNullOrEmpty()) {
  1511. rc = pConfig->WriteConfigValue("SM", "IsFirst", "Yes");
  1512. if (rc != Error_Succeed) {
  1513. Dbg("WriteConfigValue Config_Run SM IsFirst error.");
  1514. return isFirst;
  1515. }
  1516. isFirst = 1;
  1517. }
  1518. else if (sIsFirst == "Yes") {
  1519. isFirst = 1;
  1520. }
  1521. else
  1522. isFirst = 0;
  1523. return isFirst;
  1524. }
  1525. else {
  1526. rc = pConfig->WriteConfigValue("SM", "IsFirst", "No");
  1527. if (rc != Error_Succeed) {
  1528. Dbg("WriteConfigValue Config_Run SM IsFirst error.");
  1529. return isFirst;
  1530. } else {
  1531. isFirst = 1;
  1532. }
  1533. return isFirst;
  1534. }
  1535. }
  1536. bool CAccessAuthEntity::IsMachineTypeConfigurePinPad(CSimpleStringA strMachineType)
  1537. {
  1538. // 回单打印机、卡库、简化版
  1539. if (strMachineType.IsStartWith("RPM", true) || strMachineType.IsStartWith("RVC.CardStore", true)
  1540. || strMachineType.IsStartWith("RVC.IL", true))
  1541. {
  1542. return false;
  1543. }
  1544. else
  1545. return true;
  1546. }
  1547. void CAccessAuthEntity::UpdateWK()
  1548. {
  1549. m_FSM.UpdateWK();
  1550. }
  1551. void CAccessAuthEntity::BeginInitMKACS()
  1552. {
  1553. LOG_FUNCTION();
  1554. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  1555. int nCapability = GetPinPadCapability();
  1556. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("BeginInitMKACS")("pinpad capability: %d", nCapability);
  1557. CSmartPointer<IConfigInfo> spConfig;
  1558. ErrorCodeEnum Error = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1559. if (Error_Succeed == Error)
  1560. {
  1561. Error = spConfig->ReadConfigValue("AccessAuthorization", "HostInitUrl", m_strInitUrl);
  1562. if (Error_Succeed == Error)
  1563. {
  1564. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("BeginLoginACS")("get InitUrl=%s from CenterSetting.ini", m_strInitUrl.GetData());
  1565. }
  1566. else
  1567. {
  1568. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("BeginLoginACS")("get InitUrl from CenterSetting.ini failed");
  1569. return;
  1570. }
  1571. }
  1572. CSmartPointer<InitializerInitMKTask> initUpdateWKTask = new InitializerInitMKTask(&this->m_FSM, this);
  1573. GetFunction()->PostThreadPoolTask(initUpdateWKTask.GetRawPointer());
  1574. }
  1575. ErrorCodeEnum CAccessAuthEntity::LoadKeysToPinPadACS(string TMK, string TPK, string EDK, string index)
  1576. {
  1577. LOG_FUNCTION();
  1578. //获取私钥
  1579. CSmartPointer<IConfigInfo> pConfigRun;
  1580. auto rc = GetFunction()->OpenConfig(Config_Run, pConfigRun);
  1581. if (rc != Error_Succeed) {
  1582. Dbg("OpenConfig Config_Run error=%d.", rc);
  1583. return Error_Unexpect;
  1584. }
  1585. CSimpleStringA csPrivateKey("");
  1586. pConfigRun->ReadConfigValue("TerminalPD", "PrivateKey", csPrivateKey);
  1587. Dbg("privateKey len:%d", csPrivateKey.GetLength());
  1588. int decodedPrivateKeyLen;
  1589. char* pDecodedPrivateKey = Hex2Str(csPrivateKey.GetData(), decodedPrivateKeyLen);
  1590. Dbg("decodedPrivateKeyLen=%d", decodedPrivateKeyLen);
  1591. char pDecryptPrivateKey[BUF_SIZE] = { 0 };
  1592. int decryprtLen = BUF_SIZE;
  1593. if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
  1594. Dbg("DecWithSM4_ECB decrypt privateKey error.");
  1595. delete[] pDecodedPrivateKey;
  1596. return Error_Unexpect;
  1597. }
  1598. delete[] pDecodedPrivateKey;
  1599. Dbg("DecWithSM4_ECB succeess.len:%d.", decryprtLen);
  1600. char pPlainTMK[BUF_SIZE], pPlainTPK[BUF_SIZE], pPlainEDK[BUF_SIZE];
  1601. memset(pPlainTMK, 0, BUF_SIZE);
  1602. memset(pPlainTPK, 0, BUF_SIZE);
  1603. memset(pPlainEDK, 0, BUF_SIZE);
  1604. int plainKeyLen = BUF_SIZE;
  1605. char* pxx = new char[1024];
  1606. memset(pxx, 0, 1024);
  1607. HexBuf2StrBuf((BYTE*)pDecryptPrivateKey, &pxx, decryprtLen);
  1608. PBYTE pBt = new BYTE[512];
  1609. memset(pBt, 0, 512);
  1610. StrBuf2HexBuf(TMK.c_str(), &pBt);
  1611. if (!DecWithSM2PriKey(pBt, TMK.size() / 2, (BYTE*)pPlainTMK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  1612. Dbg("使用私钥解密TMK失败!");
  1613. return Error_Unexpect;
  1614. }
  1615. //char* pEncodeTPK = MyBase64::Str2Hex(TPK.c_str(), TPK.size());
  1616. PBYTE pTPK = new BYTE[512];
  1617. memset(pTPK, 0, 512);
  1618. int len = StrBuf2HexBuf(TPK.c_str(), &pTPK);
  1619. plainKeyLen = BUF_SIZE;
  1620. Dbg("001,len:%d", len);
  1621. if (!DecWithSM2PriKey(pTPK, TPK.size() / 2, (BYTE*)pPlainTPK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  1622. Dbg("使用私钥解密TPK失败!");
  1623. //delete[]pEncodeTPK;
  1624. return Error_Unexpect;
  1625. }
  1626. //char* pEncodeEDK = MyBase64::Str2Hex(EDK.c_str(), EDK.size());
  1627. PBYTE pEDK = new BYTE[512];
  1628. memset(pEDK, 0, 512);
  1629. StrBuf2HexBuf(EDK.c_str(), &pEDK);
  1630. plainKeyLen = BUF_SIZE;
  1631. if (!DecWithSM2PriKey(pEDK, EDK.size() / 2, (BYTE*)pPlainEDK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  1632. Dbg("使用私钥解密EDK失败!");
  1633. //delete[]pEncodeEDK;
  1634. return Error_Unexpect;
  1635. }
  1636. Dbg("解密秘钥成功");
  1637. //加载到密码键盘
  1638. Dbg("load sm key to pinpad...");
  1639. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  1640. rc = pPinPad->Connect();
  1641. if (rc == Error_Succeed)
  1642. {
  1643. PinPadService_LoadKeysSM_Req req = {};
  1644. req.initializeflag = true;
  1645. req.smflag = 1;
  1646. Dbg("使用云接口获取的KMC密钥");
  1647. req.masterkey = pPlainTMK;
  1648. req.workingkey1 = pPlainTPK;
  1649. req.workingkey2 = pPlainEDK;
  1650. req.reserved3 = index.c_str();
  1651. if (req.initializeflag) Dbg("initializeflag is true");
  1652. else Dbg("initializeflag is false");
  1653. Dbg("req.smflag=%d", req.smflag);
  1654. Dbg("req.masterkey=%s", req.masterkey.GetData());
  1655. Dbg("req.workingkey1=%s", req.workingkey1.GetData());
  1656. Dbg("req.workingkey2=%s", req.workingkey2.GetData());
  1657. Dbg("req.reserved3=%s", req.reserved3.GetData());
  1658. PinPadService_LoadKeysSM_Ans ans = {};
  1659. rc = pPinPad->LoadKeysSM(req, ans, 30000);
  1660. if (rc == Error_Succeed)
  1661. Dbg("load sm key to pinpad succ");
  1662. else
  1663. {
  1664. Dbg("load sm key to pinpad failed.");
  1665. return Error_Unexpect;
  1666. //SetAuthErrMsg("加载SM密钥到PinPad失败");
  1667. //doWarnMsg(ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD,
  1668. // GetOutPutStr("%s%08x%s%s", "LoadKeys", rc, "strErrMsg", "加载SM密钥到PinPad失败").c_str());
  1669. //rc = ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD;
  1670. }
  1671. pPinPad->GetFunction()->CloseSession();
  1672. }
  1673. else
  1674. {
  1675. Dbg("oiltest connect to pinpad failed.");
  1676. return Error_Unexpect;
  1677. }
  1678. return Error_Succeed;
  1679. }
  1680. bool CAccessAuthEntity::SendInitMKReqACS(CInitlizerMKReq& initMKReq)
  1681. {
  1682. LOG_FUNCTION();
  1683. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  1684. //auto pEntity = ((CInitializerEntity*)m_pEntity);
  1685. // 如果有外置PinPad,则需要初始化主密钥
  1686. if (HasPinPad())
  1687. {
  1688. CSmartPointer<IConfigInfo> pConfig;
  1689. DWORD rc = pFunc->OpenConfig(Config_CenterSetting, pConfig);
  1690. if (rc != Error_Succeed)
  1691. {
  1692. LogWarn(Severity_Middle, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
  1693. GetOutPutStr("%s%08X%s%s", "OpenConfig", rc, "File", "Config_CenterSetting").c_str());
  1694. rc = ERR_INITIALIZER_READ_WRITE_FILE;
  1695. return rc;
  1696. }
  1697. CSimpleStringA strSubBankNo, strBranchNo;
  1698. rc = pConfig->ReadConfigValue("Initializer", "SubBankNo", strSubBankNo);
  1699. if (rc == Error_Succeed)
  1700. rc = pConfig->ReadConfigValue("Initializer", "BranchNo", strBranchNo);
  1701. if (rc != Error_Succeed)
  1702. {
  1703. LogWarn(Severity_Low, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
  1704. GetOutPutStr("%s%08X%s%s", "ReadConfigValue", rc, "File", "SubBankNo & BranchNo").c_str());
  1705. rc = ERR_INITIALIZER_READ_WRITE_FILE;
  1706. return rc;
  1707. }
  1708. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  1709. int nCapability = GetPinPadCapability();
  1710. Dbg("pinpad capability: %d", nCapability);
  1711. //gui console中,用户桌面,蓝牙多合一绑定时的初始化会重置kmc密钥,自动初始化不会重置密钥,自动初始化的目的仅用在非国密
  1712. //版本到国密版本的升级无缝切换
  1713. //if (m_bHandWork && !m_afterSMIsFirst) {
  1714. if (false) {//oiltest@20211113
  1715. Dbg("初始化开始重置密钥。。。");
  1716. if (nCapability == 1 || nCapability == 3)
  1717. {
  1718. // support des key
  1719. initMKReq.MKD_REQ2.branchNo = strSubBankNo;
  1720. initMKReq.MKD_REQ2.subBankNo = strBranchNo;
  1721. }
  1722. if (nCapability == 2 || nCapability == 3)
  1723. {
  1724. // support sm key
  1725. initMKReq.MKD_SMR2.branchNo = strSubBankNo;
  1726. initMKReq.MKD_SMR2.subBankNo = strBranchNo;
  1727. }
  1728. }
  1729. }
  1730. else
  1731. {
  1732. Dbg("has no pinpad, not need init MK");
  1733. }
  1734. bool bHasPinPad = false;
  1735. CSimpleStringA strPinPadID = "", strDeviceID = "";
  1736. int nRet = GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, bHasPinPad);
  1737. Dbg("GetPinPadIDAndDeviceID ret: %d, PinPadID: %s, DeviceID: %s", nRet, (const char*)strPinPadID, (const char*)strDeviceID);
  1738. // 从系统获取设备信息和硬件信息
  1739. // 变长结构初始化
  1740. char buf2[512];
  1741. memset(buf2, 0, 512);
  1742. CSystemStaticInfo si;
  1743. pFunc->GetSystemStaticInfo(si);
  1744. initMKReq.MKD_NEW1.terminalNo = si.strTerminalID;
  1745. initMKReq.MKD_NEW1.installVersion = si.InstallVersion.ToString();
  1746. if (nRet == 2 || nRet == 3) {
  1747. initMKReq.MKD_NEW1.padDeviceID = strDeviceID;
  1748. }
  1749. initMKReq.MKD_NEW1.machineType = si.strMachineType;
  1750. initMKReq.MKD_NEW1.site = si.strSite;
  1751. BYTE xIP[64] = {};
  1752. #ifdef RVC_OS_WIN
  1753. hostent* ent = gethostbyname(NULL);
  1754. if (ent && ent->h_addr_list[0] != NULL)
  1755. {
  1756. int i = 0;
  1757. for (; ent->h_addr_list[i] != NULL; ++i)
  1758. {
  1759. struct in_addr* in = (struct in_addr*)ent->h_addr_list[i];
  1760. if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
  1761. break;
  1762. }
  1763. if (ent->h_addr_list[i] == NULL)
  1764. i = 0;
  1765. auto in = (struct in_addr*)ent->h_addr_list[i];
  1766. sprintf(xIP, "%d.%d.%d.%d", in->S_un.S_un_b.s_b1, in->S_un.S_un_b.s_b2, in->S_un.S_un_b.s_b3, in->S_un.S_un_b.s_b4);
  1767. initMKReq.MKD_NEW1.ip = xIP;
  1768. Dbg("ip:%s", xIP);
  1769. }
  1770. #else
  1771. char ip[32] = { 0 };
  1772. if (getIPFromLinux(ip)) Dbg("Get IP From Linux Error ex.");
  1773. else {
  1774. if (ip2byte(ip, xIP)) Dbg("Ip 2 Byte Error");
  1775. else {
  1776. for (int i = 0; i < 4; i++) {
  1777. Dbg("ip[%d]=%d", i, xIP[i]);
  1778. }
  1779. char strIP[64];
  1780. memset(strIP, 0, 64);
  1781. sprintf(strIP, "%d.%d.%d.%d", xIP[0], xIP[1], xIP[2], xIP[3]);
  1782. initMKReq.MKD_NEW1.ip = strIP;
  1783. }
  1784. }
  1785. #endif //RVC_OS_WIN
  1786. initMKReq.MKD_NEW1.enrolGPS = "00000A4500000A4E";//oiltmp
  1787. initMKReq.MKD_NEW1.enrolAddr = si.strEnrolAddr;
  1788. initMKReq.MKD_REQ3[0]->modal = "";
  1789. initMKReq.MKD_REQ3[0]->factory = "";
  1790. initMKReq.MKD_REQ3[0]->type = "";
  1791. initMKReq.MKD_REQ3[0]->version = "";
  1792. BYTE fingerPrint[32] = { 0 };
  1793. int nBufLen = sizeof(fingerPrint);
  1794. if (!GetTerminalFingerPrint(fingerPrint, nBufLen))
  1795. {
  1796. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT,
  1797. GetOutPutStr("%s%s", "GetTerminalFingerPrint", "False").c_str());
  1798. return ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT;
  1799. }
  1800. string xFingerPrint = ConvertBytesToHexStr(fingerPrint, nBufLen);
  1801. initMKReq.MKD_REQ4.fingerPrint = xFingerPrint.substr(0, 32);
  1802. initMKReq.MKD_REQ4.fingerPrintSM = xFingerPrint.substr(32, 64);
  1803. BYTE xPublicKey[148];
  1804. nBufLen = sizeof(xPublicKey);
  1805. Dbg("开始获取公钥。。。");
  1806. memset(xPublicKey, 0, nBufLen);
  1807. Dbg("nBufLen=%d", nBufLen);
  1808. if (!GetTerminalPublicKey(xPublicKey, nBufLen, initMKReq.MKD_REQ4.publicKey))
  1809. {
  1810. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_PUBKEY,
  1811. GetOutPutStr("%s%s", "GetTerminalPublicKey", "False").c_str());
  1812. return ERR_INITIALIZER_GET_TERMINAL_PUBKEY;
  1813. }
  1814. if (nRet == 1 || nRet == 3)
  1815. //strncpy(req4.PinPadID, (const char*)strPinPadID, sizeof(req4.PinPadID) - 1);
  1816. initMKReq.MKD_REQ4.pinPadID = strPinPadID;
  1817. //国密改造
  1818. initMKReq.MKD_REQ5.isFirstSM = GetOrSetIsFirstSM(0);
  1819. initMKReq.MKD_REQ5.isSM = 1;
  1820. Dbg("rinitMKReq.MKD_REQ5.isFirstSM=%d", initMKReq.MKD_REQ5.isFirstSM);
  1821. return true;
  1822. }
  1823. void CAccessAuthEntity::EndInitMK(DWORD rc, const char *pszErrMsg)
  1824. {
  1825. LOG_FUNCTION();
  1826. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("EndInitMK")("EndInitMK:rc:%d,errMsg:%s", rc, pszErrMsg);
  1827. GetFunction()->KillTimer(22);
  1828. m_strLastErrMsg = pszErrMsg;
  1829. if (rc != Error_Succeed)
  1830. {
  1831. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_INIT_MK,
  1832. GetOutPutStr("%s%08X%s%s", "EndInitMK", rc,"pszErrMsg", pszErrMsg).c_str());
  1833. GetFunction()->ShowFatalError(pszErrMsg);
  1834. }
  1835. else
  1836. {
  1837. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("EndInitMK")("初始化成功。。。");
  1838. }
  1839. m_eErrNum = rc;
  1840. bool bSuc = rc == Error_Succeed;
  1841. // 通知UI窗口
  1842. if (m_ctx != NULL) {
  1843. Dbg("success");
  1844. m_ctx->Ans.Errcode = rc;
  1845. m_ctx->Ans.ErrMsg = m_strLastErrMsg;
  1846. m_ctx->Answer(Error_Succeed);
  1847. }
  1848. }
  1849. SP_BEGIN_ENTITY_MAP()
  1850. SP_ENTITY(CAccessAuthEntity)
  1851. SP_END_ENTITY_MAP()