java_sdk.txt 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Java SDK 获取Root证书SN AntCertificationUtil.getRootCertSN();
  2. /**
  3. * 从公钥证书中提取公钥序列号
  4. *
  5. * @param certPath 公钥证书存放路径,例如:/home/admin/cert.crt
  6. * @return 公钥证书序列号
  7. * @throws AlipayApiException
  8. */
  9. public static String getCertSN(String certPath) throws AlipayApiException {
  10. InputStream inputStream = null;
  11. try {
  12. inputStream = new FileInputStream(certPath);
  13. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  14. X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
  15. MessageDigest md = MessageDigest.getInstance("MD5");
  16. md.update((cert.getIssuerX500Principal().getName() + cert.getSerialNumber()).getBytes());
  17. String certSN = new BigInteger(1, md.digest()).toString(16);
  18. //BigInteger会把0省略掉,需补全至32位
  19. certSN = fillMD5(certSN);
  20. return certSN;
  21. } catch (NoSuchAlgorithmException e) {
  22. throw new AlipayApiException(e);
  23. } catch (IOException e) {
  24. throw new AlipayApiException(e);
  25. } catch (CertificateException e) {
  26. throw new AlipayApiException(e);
  27. } finally {
  28. try {
  29. if (inputStream != null) {
  30. inputStream.close();
  31. }
  32. } catch (IOException e) {
  33. throw new AlipayApiException(e);
  34. }
  35. }
  36. }
  37. // Java SDK 获取证书SN AlipaySignature.getCertSN();
  38. /**
  39. * 获取根证书序列号
  40. *
  41. * @param rootCertContent
  42. * @return
  43. */
  44. public static String getRootCertSN(String rootCertContent) {
  45. String rootCertSN = null;
  46. try {
  47. X509Certificate[] x509Certificates = readPemCertChain(rootCertContent);
  48. MessageDigest md = MessageDigest.getInstance("MD5");
  49. for (X509Certificate c : x509Certificates) {
  50. if (c.getSigAlgOID().startsWith("1.2.840.113549.1.1")) {
  51. md.update((c.getIssuerX500Principal().getName() + c.getSerialNumber()).getBytes());
  52. String certSN = new BigInteger(1, md.digest()).toString(16);
  53. //BigInteger会把0省略掉,需补全至32位
  54. certSN = fillMD5(certSN);
  55. if (StringUtils.isEmpty(rootCertSN)) {
  56. rootCertSN = certSN;
  57. } else {
  58. rootCertSN = rootCertSN + "_" + certSN;
  59. }
  60. }
  61. }
  62. } catch (Exception e) {
  63. AlipayLogger.logBizError(("提取根证书失败"));
  64. }
  65. return rootCertSN;
  66. }
  67. private static String fillMD5(String md5) {
  68. return md5.length() == 32 ? md5 : fillMD5("0" + md5);
  69. }