SDKUtil.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /**
  2. *
  3. * Licensed Property to China UnionPay Co., Ltd.
  4. *
  5. * (C) Copyright of China UnionPay Co., Ltd. 2010
  6. * All Rights Reserved.
  7. *
  8. *
  9. * Modification History:
  10. * =============================================================================
  11. * Author Date Description
  12. * ------------ ---------- ---------------------------------------------------
  13. * xshu 2014-05-28 MPI工具类
  14. * =============================================================================
  15. */
  16. package com.lightinit.hsdataportal.Unionsdk;
  17. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.CERTTYPE_01;
  18. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.CERTTYPE_02;
  19. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.POINT;
  20. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.SIGNMETHOD_RSA;
  21. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.SIGNMETHOD_SHA256;
  22. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.SIGNMETHOD_SM3;
  23. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.VERSION_5_0_0;
  24. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.VERSION_1_0_0;
  25. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.VERSION_5_1_0;
  26. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.VERSION_5_0_1;
  27. import static com.lightinit.hsdataportal.Unionsdk.SDKConstants.param_signMethod;
  28. import java.io.ByteArrayOutputStream;
  29. import java.io.File;
  30. import java.io.FileInputStream;
  31. import java.io.FileNotFoundException;
  32. import java.io.FileOutputStream;
  33. import java.io.IOException;
  34. import java.io.UnsupportedEncodingException;
  35. import java.nio.ByteBuffer;
  36. import java.nio.channels.FileChannel;
  37. import java.security.cert.X509Certificate;
  38. import java.util.HashMap;
  39. import java.util.Iterator;
  40. import java.util.Map;
  41. import java.util.Map.Entry;
  42. import java.util.Set;
  43. import java.util.TreeMap;
  44. import java.util.zip.Deflater;
  45. import java.util.zip.Inflater;
  46. /**
  47. *
  48. * @ClassName SDKUtil
  49. * @Description acpsdk工具类
  50. * @date 2016-7-22 下午4:06:18
  51. * 声明:以下代码只是为了方便接入方测试而提供的样例代码,商户可以根据自己需要,按照技术文档编写。该代码仅供参考,不提供编码,性能,规范性等方面的保障
  52. */
  53. public class SDKUtil {
  54. /**
  55. * 根据signMethod的值,提供三种计算签名的方法
  56. *
  57. * @param data
  58. * 待签名数据Map键值对形式
  59. * @param encoding
  60. * 编码
  61. * @return 签名是否成功
  62. */
  63. public static boolean sign(Map<String, String> data, String encoding) {
  64. if (isEmpty(encoding)) {
  65. encoding = "UTF-8";
  66. }
  67. String signMethod = data.get(param_signMethod);
  68. String version = data.get(SDKConstants.param_version);
  69. if (!VERSION_1_0_0.equals(version) && !VERSION_5_0_1.equals(version) && isEmpty(signMethod)) {
  70. LogUtil.writeErrorLog("signMethod must Not null");
  71. return false;
  72. }
  73. if (isEmpty(version)) {
  74. LogUtil.writeErrorLog("version must Not null");
  75. return false;
  76. }
  77. if (SIGNMETHOD_RSA.equals(signMethod)|| VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  78. if (VERSION_5_0_0.equals(version)|| VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  79. // 设置签名证书序列号
  80. data.put(SDKConstants.param_certId, CertUtil.getSignCertId());
  81. // 将Map信息转换成key1=value1&key2=value2的形式
  82. String stringData = coverMap2String(data);
  83. LogUtil.writeLog("打印排序后待签名请求报文串(交易返回11验证签名失败时可以用来同正确的进行比对):[" + stringData + "]");
  84. byte[] byteSign = null;
  85. String stringSign = null;
  86. try {
  87. // 通过SHA1进行摘要并转16进制
  88. byte[] signDigest = SecureUtil
  89. .sha1X16(stringData, encoding);
  90. LogUtil.writeLog("打印摘要(交易返回11验证签名失败可以用来同正确的进行比对):[" + new String(signDigest)+ "]");
  91. byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft(
  92. CertUtil.getSignCertPrivateKey(), signDigest));
  93. stringSign = new String(byteSign);
  94. // 设置签名域值
  95. data.put(SDKConstants.param_signature, stringSign);
  96. return true;
  97. } catch (Exception e) {
  98. LogUtil.writeErrorLog("Sign Error", e);
  99. return false;
  100. }
  101. } else if (VERSION_5_1_0.equals(version)) {
  102. // 设置签名证书序列号
  103. data.put(SDKConstants.param_certId, CertUtil.getSignCertId());
  104. // 将Map信息转换成key1=value1&key2=value2的形式
  105. String stringData = coverMap2String(data);
  106. LogUtil.writeLog("打印待签名请求报文串(交易返回11验证签名失败时可以用来同正确的进行比对):[" + stringData + "]");
  107. byte[] byteSign = null;
  108. String stringSign = null;
  109. try {
  110. // 通过SHA256进行摘要并转16进制
  111. byte[] signDigest = SecureUtil
  112. .sha256X16(stringData, encoding);
  113. LogUtil.writeLog("打印摘要(交易返回11验证签名失败可以用来同正确的进行比对):[" + new String(signDigest)+ "]");
  114. byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft256(
  115. CertUtil.getSignCertPrivateKey(), signDigest));
  116. stringSign = new String(byteSign);
  117. // 设置签名域值
  118. data.put(SDKConstants.param_signature, stringSign);
  119. return true;
  120. } catch (Exception e) {
  121. LogUtil.writeErrorLog("Sign Error", e);
  122. return false;
  123. }
  124. }
  125. } else if (SIGNMETHOD_SHA256.equals(signMethod)) {
  126. return signBySecureKey(data, SDKConfig.getConfig()
  127. .getSecureKey(), encoding);
  128. } else if (SIGNMETHOD_SM3.equals(signMethod)) {
  129. return signBySecureKey(data, SDKConfig.getConfig()
  130. .getSecureKey(), encoding);
  131. }
  132. return false;
  133. }
  134. /**
  135. * 通过传入的证书绝对路径和证书密码读取签名证书进行签名并返回签名值<br>
  136. *
  137. * @param data
  138. * 待签名数据Map键值对形式
  139. * @param encoding
  140. * 编码
  141. * @return 签名值
  142. */
  143. public static boolean signBySecureKey(Map<String, String> data, String secureKey,
  144. String encoding) {
  145. if (isEmpty(encoding)) {
  146. encoding = "UTF-8";
  147. }
  148. if (isEmpty(secureKey)) {
  149. LogUtil.writeErrorLog("secureKey is empty");
  150. return false;
  151. }
  152. String signMethod = data.get(param_signMethod);
  153. if (isEmpty(signMethod)) {
  154. LogUtil.writeErrorLog("signMethod must Not null");
  155. return false;
  156. }
  157. if (SIGNMETHOD_SHA256.equals(signMethod)) {
  158. // 将Map信息转换成key1=value1&key2=value2的形式
  159. String stringData = coverMap2String(data);
  160. LogUtil.writeLog("待签名请求报文串:[" + stringData + "]");
  161. String strBeforeSha256 = stringData
  162. + SDKConstants.AMPERSAND
  163. + SecureUtil.sha256X16Str(secureKey, encoding);
  164. String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256,
  165. encoding);
  166. // 设置签名域值
  167. data.put(SDKConstants.param_signature, strAfterSha256);
  168. return true;
  169. } else if (SIGNMETHOD_SM3.equals(signMethod)) {
  170. String stringData = coverMap2String(data);
  171. LogUtil.writeLog("待签名请求报文串:[" + stringData + "]");
  172. String strBeforeSM3 = stringData
  173. + SDKConstants.AMPERSAND
  174. + SecureUtil.sm3X16Str(secureKey, encoding);
  175. String strAfterSM3 = SecureUtil.sm3X16Str(strBeforeSM3, encoding);
  176. // 设置签名域值
  177. data.put(SDKConstants.param_signature, strAfterSM3);
  178. return true;
  179. }
  180. return false;
  181. }
  182. /**
  183. * 通过传入的签名密钥进行签名并返回签名值<br>
  184. *
  185. * @param data
  186. * 待签名数据Map键值对形式
  187. * @param encoding
  188. * 编码
  189. * @param certPath
  190. * 证书绝对路径
  191. * @param certPwd
  192. * 证书密码
  193. * @return 签名值
  194. */
  195. public static boolean signByCertInfo(Map<String, String> data,
  196. String certPath, String certPwd, String encoding) {
  197. if (isEmpty(encoding)) {
  198. encoding = "UTF-8";
  199. }
  200. if (isEmpty(certPath) || isEmpty(certPwd)) {
  201. LogUtil.writeErrorLog("CertPath or CertPwd is empty");
  202. return false;
  203. }
  204. String signMethod = data.get(param_signMethod);
  205. String version = data.get(SDKConstants.param_version);
  206. if (!VERSION_1_0_0.equals(version) && !VERSION_5_0_1.equals(version) && isEmpty(signMethod)) {
  207. LogUtil.writeErrorLog("signMethod must Not null");
  208. return false;
  209. }
  210. if (isEmpty(version)) {
  211. LogUtil.writeErrorLog("version must Not null");
  212. return false;
  213. }
  214. if (SIGNMETHOD_RSA.equals(signMethod) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  215. if (VERSION_5_0_0.equals(version) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  216. // 设置签名证书序列号
  217. data.put(SDKConstants.param_certId, CertUtil.getCertIdByKeyStoreMap(certPath, certPwd));
  218. // 将Map信息转换成key1=value1&key2=value2的形式
  219. String stringData = coverMap2String(data);
  220. LogUtil.writeLog("待签名请求报文串:[" + stringData + "]");
  221. byte[] byteSign = null;
  222. String stringSign = null;
  223. try {
  224. // 通过SHA1进行摘要并转16进制
  225. byte[] signDigest = SecureUtil
  226. .sha1X16(stringData, encoding);
  227. byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft(
  228. CertUtil.getSignCertPrivateKeyByStoreMap(certPath, certPwd), signDigest));
  229. stringSign = new String(byteSign);
  230. // 设置签名域值
  231. data.put(SDKConstants.param_signature, stringSign);
  232. return true;
  233. } catch (Exception e) {
  234. LogUtil.writeErrorLog("Sign Error", e);
  235. return false;
  236. }
  237. } else if (VERSION_5_1_0.equals(version)) {
  238. // 设置签名证书序列号
  239. data.put(SDKConstants.param_certId, CertUtil.getCertIdByKeyStoreMap(certPath, certPwd));
  240. // 将Map信息转换成key1=value1&key2=value2的形式
  241. String stringData = coverMap2String(data);
  242. LogUtil.writeLog("待签名请求报文串:[" + stringData + "]");
  243. byte[] byteSign = null;
  244. String stringSign = null;
  245. try {
  246. // 通过SHA256进行摘要并转16进制
  247. byte[] signDigest = SecureUtil
  248. .sha256X16(stringData, encoding);
  249. byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft256(
  250. CertUtil.getSignCertPrivateKeyByStoreMap(certPath, certPwd), signDigest));
  251. stringSign = new String(byteSign);
  252. // 设置签名域值
  253. data.put(SDKConstants.param_signature, stringSign);
  254. return true;
  255. } catch (Exception e) {
  256. LogUtil.writeErrorLog("Sign Error", e);
  257. return false;
  258. }
  259. }
  260. }
  261. return false;
  262. }
  263. /**
  264. * 验证签名
  265. *
  266. * @param resData
  267. * 返回报文数据
  268. * @param encoding
  269. * 编码格式
  270. * @return
  271. */
  272. public static boolean validateBySecureKey(Map<String, String> resData, String secureKey, String encoding) {
  273. LogUtil.writeLog("验签处理开始");
  274. if (isEmpty(encoding)) {
  275. encoding = "UTF-8";
  276. }
  277. String signMethod = resData.get(SDKConstants.param_signMethod);
  278. if (SIGNMETHOD_SHA256.equals(signMethod)) {
  279. // 1.进行SHA256验证
  280. String stringSign = resData.get(SDKConstants.param_signature);
  281. LogUtil.writeLog("签名原文:["+stringSign+"]");
  282. // 将Map信息转换成key1=value1&key2=value2的形式
  283. String stringData = coverMap2String(resData);
  284. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  285. String strBeforeSha256 = stringData
  286. + SDKConstants.AMPERSAND
  287. + SecureUtil.sha256X16Str(secureKey, encoding);
  288. String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256,
  289. encoding);
  290. return stringSign.equals(strAfterSha256);
  291. } else if (SIGNMETHOD_SM3.equals(signMethod)) {
  292. // 1.进行SM3验证
  293. String stringSign = resData.get(SDKConstants.param_signature);
  294. LogUtil.writeLog("签名原文:["+stringSign+"]");
  295. // 将Map信息转换成key1=value1&key2=value2的形式
  296. String stringData = coverMap2String(resData);
  297. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  298. String strBeforeSM3 = stringData
  299. + SDKConstants.AMPERSAND
  300. + SecureUtil.sm3X16Str(secureKey, encoding);
  301. String strAfterSM3 = SecureUtil
  302. .sm3X16Str(strBeforeSM3, encoding);
  303. return stringSign.equals(strAfterSM3);
  304. }
  305. return false;
  306. }
  307. /**
  308. * 验证签名
  309. *
  310. * @param resData
  311. * 返回报文数据
  312. * @param encoding
  313. * 编码格式
  314. * @return
  315. */
  316. public static boolean validate(Map<String, String> resData, String encoding) {
  317. LogUtil.writeLog("验签处理开始");
  318. if (isEmpty(encoding)) {
  319. encoding = "UTF-8";
  320. }
  321. String signMethod = resData.get(SDKConstants.param_signMethod);
  322. String version = resData.get(SDKConstants.param_version);
  323. if (SIGNMETHOD_RSA.equals(signMethod) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  324. // 获取返回报文的版本号
  325. if (VERSION_5_0_0.equals(version) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
  326. String stringSign = resData.get(SDKConstants.param_signature);
  327. LogUtil.writeLog("签名原文:["+stringSign+"]");
  328. // 从返回报文中获取certId ,然后去证书静态Map中查询对应验签证书对象
  329. String certId = resData.get(SDKConstants.param_certId);
  330. LogUtil.writeLog("对返回报文串验签使用的验签公钥序列号:["+certId+"]");
  331. // 将Map信息转换成key1=value1&key2=value2的形式
  332. String stringData = coverMap2String(resData);
  333. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  334. try {
  335. // 验证签名需要用银联发给商户的公钥证书.
  336. return SecureUtil.validateSignBySoft(CertUtil
  337. .getValidatePublicKey(certId), SecureUtil
  338. .base64Decode(stringSign.getBytes(encoding)),
  339. SecureUtil.sha1X16(stringData, encoding));
  340. } catch (UnsupportedEncodingException e) {
  341. LogUtil.writeErrorLog(e.getMessage(), e);
  342. } catch (Exception e) {
  343. LogUtil.writeErrorLog(e.getMessage(), e);
  344. }
  345. } else if (VERSION_5_1_0.equals(version)) {
  346. // 1.从返回报文中获取公钥信息转换成公钥对象
  347. String strCert = resData.get(SDKConstants.param_signPubKeyCert);
  348. // LogUtil.writeLog("验签公钥证书:["+strCert+"]");
  349. X509Certificate x509Cert = CertUtil.genCertificateByStr(strCert);
  350. if(x509Cert == null) {
  351. LogUtil.writeErrorLog("convert signPubKeyCert failed");
  352. return false;
  353. }
  354. // 2.验证证书链
  355. if (!CertUtil.verifyCertificate(x509Cert)) {
  356. LogUtil.writeErrorLog("验证公钥证书失败,证书信息:["+strCert+"]");
  357. return false;
  358. }
  359. // 3.验签
  360. String stringSign = resData.get(SDKConstants.param_signature);
  361. LogUtil.writeLog("签名原文:["+stringSign+"]");
  362. // 将Map信息转换成key1=value1&key2=value2的形式
  363. String stringData = coverMap2String(resData);
  364. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  365. try {
  366. // 验证签名需要用银联发给商户的公钥证书.
  367. boolean result = SecureUtil.validateSignBySoft256(x509Cert
  368. .getPublicKey(), SecureUtil.base64Decode(stringSign
  369. .getBytes(encoding)), SecureUtil.sha256X16(
  370. stringData, encoding));
  371. LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
  372. return result;
  373. } catch (UnsupportedEncodingException e) {
  374. LogUtil.writeErrorLog(e.getMessage(), e);
  375. } catch (Exception e) {
  376. LogUtil.writeErrorLog(e.getMessage(), e);
  377. }
  378. }
  379. } else if (SIGNMETHOD_SHA256.equals(signMethod)) {
  380. // 1.进行SHA256验证
  381. String stringSign = resData.get(SDKConstants.param_signature);
  382. LogUtil.writeLog("签名原文:["+stringSign+"]");
  383. // 将Map信息转换成key1=value1&key2=value2的形式
  384. String stringData = coverMap2String(resData);
  385. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  386. String strBeforeSha256 = stringData
  387. + SDKConstants.AMPERSAND
  388. + SecureUtil.sha256X16Str(SDKConfig.getConfig()
  389. .getSecureKey(), encoding);
  390. String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256,
  391. encoding);
  392. boolean result = stringSign.equals(strAfterSha256);
  393. LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
  394. return result;
  395. } else if (SIGNMETHOD_SM3.equals(signMethod)) {
  396. // 1.进行SM3验证
  397. String stringSign = resData.get(SDKConstants.param_signature);
  398. LogUtil.writeLog("签名原文:["+stringSign+"]");
  399. // 将Map信息转换成key1=value1&key2=value2的形式
  400. String stringData = coverMap2String(resData);
  401. LogUtil.writeLog("待验签返回报文串:["+stringData+"]");
  402. String strBeforeSM3 = stringData
  403. + SDKConstants.AMPERSAND
  404. + SecureUtil.sm3X16Str(SDKConfig.getConfig()
  405. .getSecureKey(), encoding);
  406. String strAfterSM3 = SecureUtil
  407. .sm3X16Str(strBeforeSM3, encoding);
  408. boolean result = stringSign.equals(strAfterSM3);
  409. LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
  410. return result;
  411. }
  412. return false;
  413. }
  414. /**
  415. * 将Map中的数据转换成key1=value1&key2=value2的形式 不包含签名域signature
  416. *
  417. * @param data
  418. * 待拼接的Map数据
  419. * @return 拼接好后的字符串
  420. */
  421. public static String coverMap2String(Map<String, String> data) {
  422. TreeMap<String, String> tree = new TreeMap<String, String>();
  423. Iterator<Entry<String, String>> it = data.entrySet().iterator();
  424. while (it.hasNext()) {
  425. Entry<String, String> en = it.next();
  426. if (SDKConstants.param_signature.equals(en.getKey().trim())) {
  427. continue;
  428. }
  429. tree.put(en.getKey(), en.getValue());
  430. }
  431. it = tree.entrySet().iterator();
  432. StringBuffer sf = new StringBuffer();
  433. while (it.hasNext()) {
  434. Entry<String, String> en = it.next();
  435. sf.append(en.getKey() + SDKConstants.EQUAL + en.getValue()
  436. + SDKConstants.AMPERSAND);
  437. }
  438. return sf.substring(0, sf.length() - 1);
  439. }
  440. /**
  441. * 兼容老方法 将形如key=value&key=value的字符串转换为相应的Map对象
  442. *
  443. * @param result
  444. * @return
  445. */
  446. public static Map<String, String> coverResultString2Map(String result) {
  447. return convertResultStringToMap(result);
  448. }
  449. /**
  450. * 将形如key=value&key=value的字符串转换为相应的Map对象
  451. *
  452. * @param result
  453. * @return
  454. */
  455. public static Map<String, String> convertResultStringToMap(String result) {
  456. Map<String, String> map = null;
  457. if (result != null && !"".equals(result.trim())) {
  458. if (result.startsWith("{") && result.endsWith("}")) {
  459. result = result.substring(1, result.length() - 1);
  460. }
  461. map = parseQString(result);
  462. }
  463. return map;
  464. }
  465. /**
  466. * 解析应答字符串,生成应答要素
  467. *
  468. * @param str
  469. * 需要解析的字符串
  470. * @return 解析的结果map
  471. * @throws UnsupportedEncodingException
  472. */
  473. public static Map<String, String> parseQString(String str) {
  474. Map<String, String> map = new HashMap<String, String>();
  475. int len = str.length();
  476. StringBuilder temp = new StringBuilder();
  477. char curChar;
  478. String key = null;
  479. boolean isKey = true;
  480. boolean isOpen = false;//值里有嵌套
  481. char openName = 0;
  482. if(len>0){
  483. for (int i = 0; i < len; i++) {// 遍历整个带解析的字符串
  484. curChar = str.charAt(i);// 取当前字符
  485. if (isKey) {// 如果当前生成的是key
  486. if (curChar == '=') {// 如果读取到=分隔符
  487. key = temp.toString();
  488. temp.setLength(0);
  489. isKey = false;
  490. } else {
  491. temp.append(curChar);
  492. }
  493. } else {// 如果当前生成的是value
  494. if(isOpen){
  495. if(curChar == openName){
  496. isOpen = false;
  497. }
  498. }else{//如果没开启嵌套
  499. if(curChar == '{'){//如果碰到,就开启嵌套
  500. isOpen = true;
  501. openName ='}';
  502. }
  503. if(curChar == '['){
  504. isOpen = true;
  505. openName =']';
  506. }
  507. }
  508. if (curChar == '&' && !isOpen) {// 如果读取到&分割符,同时这个分割符不是值域,这时将map里添加
  509. putKeyValueToMap(temp, isKey, key, map);
  510. temp.setLength(0);
  511. isKey = true;
  512. } else {
  513. temp.append(curChar);
  514. }
  515. }
  516. }
  517. putKeyValueToMap(temp, isKey, key, map);
  518. }
  519. return map;
  520. }
  521. private static void putKeyValueToMap(StringBuilder temp, boolean isKey,
  522. String key, Map<String, String> map) {
  523. if (isKey) {
  524. key = temp.toString();
  525. if (key.length() == 0) {
  526. throw new RuntimeException("QString format illegal");
  527. }
  528. map.put(key, "");
  529. } else {
  530. if (key.length() == 0) {
  531. throw new RuntimeException("QString format illegal");
  532. }
  533. map.put(key, temp.toString());
  534. }
  535. }
  536. /**
  537. *
  538. * 获取应答报文中的加密公钥证书,并存储到本地,并备份原始证书<br>
  539. * 更新成功则返回1,无更新返回0,失败异常返回-1。
  540. *
  541. * @param resData
  542. * @param encoding
  543. * @return
  544. */
  545. public static int getEncryptCert(Map<String, String> resData,
  546. String encoding) {
  547. String strCert = resData.get(SDKConstants.param_encryptPubKeyCert);
  548. String certType = resData.get(SDKConstants.param_certType);
  549. if (isEmpty(strCert) || isEmpty(certType))
  550. return -1;
  551. X509Certificate x509Cert = CertUtil.genCertificateByStr(strCert);
  552. if (CERTTYPE_01.equals(certType)) {
  553. // 更新敏感信息加密公钥
  554. if (!CertUtil.getEncryptCertId().equals(
  555. x509Cert.getSerialNumber().toString())) {
  556. // ID不同时进行本地证书更新操作
  557. String localCertPath = SDKConfig.getConfig().getEncryptCertPath();
  558. String newLocalCertPath = genBackupName(localCertPath);
  559. // 1.将本地证书进行备份存储
  560. if (!copyFile(localCertPath, newLocalCertPath))
  561. return -1;
  562. // 2.备份成功,进行新证书的存储
  563. if (!writeFile(localCertPath, strCert, encoding))
  564. return -1;
  565. LogUtil.writeLog("save new encryptPubKeyCert success");
  566. CertUtil.resetEncryptCertPublicKey();
  567. return 1;
  568. }else {
  569. return 0;
  570. }
  571. } else if (CERTTYPE_02.equals(certType)) {
  572. // // 更新磁道加密公钥
  573. // if (!CertUtil.getEncryptTrackCertId().equals(
  574. // x509Cert.getSerialNumber().toString())) {
  575. // // ID不同时进行本地证书更新操作
  576. // String localCertPath = SDKConfig.getConfig().getEncryptTrackCertPath();
  577. // String newLocalCertPath = genBackupName(localCertPath);
  578. // // 1.将本地证书进行备份存储
  579. // if (!copyFile(localCertPath, newLocalCertPath))
  580. // return -1;
  581. // // 2.备份成功,进行新证书的存储
  582. // if (!writeFile(localCertPath, strCert, encoding))
  583. // return -1;
  584. // LogUtil.writeLog("save new encryptPubKeyCert success");
  585. // CertUtil.resetEncryptTrackCertPublicKey();
  586. // return 1;
  587. // }else {
  588. return 0;
  589. // }
  590. }else {
  591. LogUtil.writeLog("unknown cerType:"+certType);
  592. return -1;
  593. }
  594. }
  595. /**
  596. * 文件拷贝方法
  597. *
  598. * @param srcFile
  599. * 源文件
  600. * @param destFile
  601. * 目标文件
  602. * @return
  603. * @throws IOException
  604. */
  605. public static boolean copyFile(String srcFile, String destFile) {
  606. boolean flag = false;
  607. FileInputStream fin = null;
  608. FileOutputStream fout = null;
  609. FileChannel fcin = null;
  610. FileChannel fcout = null;
  611. try {
  612. // 获取源文件和目标文件的输入输出流
  613. fin = new FileInputStream(srcFile);
  614. fout = new FileOutputStream(destFile);
  615. // 获取输入输出通道
  616. fcin = fin.getChannel();
  617. fcout = fout.getChannel();
  618. // 创建缓冲区
  619. ByteBuffer buffer = ByteBuffer.allocate(1024);
  620. while (true) {
  621. // clear方法重设缓冲区,使它可以接受读入的数据
  622. buffer.clear();
  623. // 从输入通道中将数据读到缓冲区
  624. int r = fcin.read(buffer);
  625. // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
  626. if (r == -1) {
  627. flag = true;
  628. break;
  629. }
  630. // flip方法让缓冲区可以将新读入的数据写入另一个通道
  631. buffer.flip();
  632. // 从输出通道中将数据写入缓冲区
  633. fcout.write(buffer);
  634. }
  635. fout.flush();
  636. } catch (IOException e) {
  637. LogUtil.writeErrorLog("CopyFile fail", e);
  638. } finally {
  639. try {
  640. if (null != fin)
  641. fin.close();
  642. if (null != fout)
  643. fout.close();
  644. if (null != fcin)
  645. fcin.close();
  646. if (null != fcout)
  647. fcout.close();
  648. } catch (IOException ex) {
  649. LogUtil.writeErrorLog("Releases any system resources fail", ex);
  650. }
  651. }
  652. return flag;
  653. }
  654. /**
  655. * 写文件方法
  656. *
  657. * @param filePath
  658. * 文件路径
  659. * @param fileContent
  660. * 文件内容
  661. * @param encoding
  662. * 编码
  663. * @return
  664. */
  665. public static boolean writeFile(String filePath, String fileContent,
  666. String encoding) {
  667. FileOutputStream fout = null;
  668. FileChannel fcout = null;
  669. File file = new File(filePath);
  670. if (file.exists()) {
  671. file.delete();
  672. }
  673. try {
  674. fout = new FileOutputStream(filePath);
  675. // 获取输出通道
  676. fcout = fout.getChannel();
  677. // 创建缓冲区
  678. // ByteBuffer buffer = ByteBuffer.allocate(1024);
  679. ByteBuffer buffer = ByteBuffer.wrap(fileContent.getBytes(encoding));
  680. fcout.write(buffer);
  681. fout.flush();
  682. } catch (FileNotFoundException e) {
  683. LogUtil.writeErrorLog("WriteFile fail", e);
  684. return false;
  685. } catch (IOException ex) {
  686. LogUtil.writeErrorLog("WriteFile fail", ex);
  687. return false;
  688. } finally {
  689. try {
  690. if (null != fout)
  691. fout.close();
  692. if (null != fcout)
  693. fcout.close();
  694. } catch (IOException ex) {
  695. LogUtil.writeErrorLog("Releases any system resources fail", ex);
  696. return false;
  697. }
  698. }
  699. return true;
  700. }
  701. /**
  702. * 将传入的文件名(xxx)改名 <br>
  703. * 结果为: xxx_backup.cer
  704. *
  705. * @param fileName
  706. * @return
  707. */
  708. public static String genBackupName(String fileName) {
  709. if (isEmpty(fileName))
  710. return "";
  711. int i = fileName.lastIndexOf(POINT);
  712. String leftFileName = fileName.substring(0, i);
  713. String rightFileName = fileName.substring(i + 1);
  714. String newFileName = leftFileName + "_backup" + POINT + rightFileName;
  715. return newFileName;
  716. }
  717. public static byte[] readFileByNIO(String filePath) {
  718. FileInputStream in = null;
  719. FileChannel fc = null;
  720. ByteBuffer bf = null;
  721. try {
  722. in = new FileInputStream(filePath);
  723. fc = in.getChannel();
  724. bf = ByteBuffer.allocate((int) fc.size());
  725. fc.read(bf);
  726. return bf.array();
  727. } catch (Exception e) {
  728. LogUtil.writeErrorLog(e.getMessage());
  729. return null;
  730. } finally {
  731. try {
  732. if (null != fc) {
  733. fc.close();
  734. }
  735. if (null != in) {
  736. in.close();
  737. }
  738. } catch (Exception e) {
  739. LogUtil.writeErrorLog(e.getMessage());
  740. return null;
  741. }
  742. }
  743. }
  744. /**
  745. * 过滤请求报文中的空字符串或者空字符串
  746. * @param contentData
  747. * @return
  748. */
  749. public static Map<String, String> filterBlank(Map<String, String> contentData){
  750. LogUtil.writeLog("打印请求报文域 :");
  751. Map<String, String> submitFromData = new HashMap<String, String>();
  752. Set<String> keyset = contentData.keySet();
  753. for(String key:keyset){
  754. String value = contentData.get(key);
  755. if (value != null && !"".equals(value.trim())) {
  756. // 对value值进行去除前后空处理
  757. submitFromData.put(key, value.trim());
  758. LogUtil.writeLog(key + "-->" + String.valueOf(value));
  759. }
  760. }
  761. return submitFromData;
  762. }
  763. /**
  764. * 解压缩.
  765. *
  766. * @param inputByte
  767. * byte[]数组类型的数据
  768. * @return 解压缩后的数据
  769. * @throws IOException
  770. */
  771. public static byte[] inflater(final byte[] inputByte) throws IOException {
  772. int compressedDataLength = 0;
  773. Inflater compresser = new Inflater(false);
  774. compresser.setInput(inputByte, 0, inputByte.length);
  775. ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
  776. byte[] result = new byte[1024];
  777. try {
  778. while (!compresser.finished()) {
  779. compressedDataLength = compresser.inflate(result);
  780. if (compressedDataLength == 0) {
  781. break;
  782. }
  783. o.write(result, 0, compressedDataLength);
  784. }
  785. } catch (Exception ex) {
  786. System.err.println("Data format error!\n");
  787. ex.printStackTrace();
  788. } finally {
  789. o.close();
  790. }
  791. compresser.end();
  792. return o.toByteArray();
  793. }
  794. /**
  795. * 压缩.
  796. *
  797. * @param inputByte
  798. * 需要解压缩的byte[]数组
  799. * @return 压缩后的数据
  800. * @throws IOException
  801. */
  802. public static byte[] deflater(final byte[] inputByte) throws IOException {
  803. int compressedDataLength = 0;
  804. Deflater compresser = new Deflater();
  805. compresser.setInput(inputByte);
  806. compresser.finish();
  807. ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
  808. byte[] result = new byte[1024];
  809. try {
  810. while (!compresser.finished()) {
  811. compressedDataLength = compresser.deflate(result);
  812. o.write(result, 0, compressedDataLength);
  813. }
  814. } finally {
  815. o.close();
  816. }
  817. compresser.end();
  818. return o.toByteArray();
  819. }
  820. /**
  821. * 判断字符串是否为NULL或空
  822. *
  823. * @param s
  824. * 待判断的字符串数据
  825. * @return 判断结果 true-是 false-否
  826. */
  827. public static boolean isEmpty(String s) {
  828. return null == s || "".equals(s.trim());
  829. }
  830. }