Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of parsing Alipay Public key Certificate by Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "the method of Python parsing Alipay public key certificate". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Python parsing Alipay public key certificate method" it!

Due to the need of work, the App we developed needs to be connected to the payment function of Alipay. So we started to learn about Alipay-related api documents.

After consideration, we chose to use a third-party SDK (https://github.com/fzlee/alipay). Here we have to complain about the official python SDK, from package path to use, with a strong java style, without the minimalist flavor of python.

Although SDK is used, we find that the latest Alipay uses public key certificates to sign. Java is the only official SDK that supports public key certificates, and the third-party SDK we use does not have it. So we have to implement the parsing of the public key certificate by ourselves, but there are few contents about the self-implementation signature on the network, and only some instructions are provided.

The official provides a self-implementation of the signature process https://docs.open.alipay.com/291/106118.

The key is to extract two key parameters, app_cert_sn and alipay_root_cert_sn, from the certificate. Here is the implementation in Java:

/ * extract the public key serial number from the public key certificate * * @ param certPath public key certificate storage path, for example: / home/admin/cert.crt * @ return public key certificate serial number * @ throws AlipayApiException * / public static String getCertSN (String certPath) throws AlipayApiException {InputStream inputStream = null; try {inputStream = new FileInputStream (certPath); CertificateFactory cf = CertificateFactory.getInstance ("X.509") X509Certificate cert = (X509Certificate) cf.generateCertificate (inputStream); MessageDigest md = MessageDigest.getInstance ("MD5"); md.update ((cert.getIssuerX500Principal (). GetName () + cert.getSerialNumber ()). GetBytes ()); String certSN = new BigInteger (1, md.digest ()) .toString (16); / / BigInteger omits 0 and needs to complete to 32-bit certSN = fillMD5 (certSN); return certSN } catch (NoSuchAlgorithmException e) {throw new AlipayApiException (e);} catch (IOException e) {throw new AlipayApiException (e);} catch (CertificateException e) {throw new AlipayApiException (e);} finally {try {if (inputStream! = null) {inputStream.close () }} catch (IOException e) {throw new AlipayApiException (e);}} / * obtain the root certificate serial number * * @ param rootCertContent * @ return * / public static String getRootCertSN (String rootCertContent) {String rootCertSN = null; try {X509Certificate [] x509Certificates = readPemCertChain (rootCertContent); MessageDigest md = MessageDigest.getInstance ("MD5") For (X509Certificate c: x509Certificates) {if (c.getSigAlgOID (). StartsWith ("1.2.840.113549.1.1")) {md.update ((c.getIssuerX500Principal (). GetName () + c.getSerialNumber ()) .getBytes ()); String certSN = new BigInteger (1, md.digest ()) .toString (16) / / BigInteger omits 0 and needs to complete it to 32-bit certSN = fillMD5 (certSN); if (StringUtils.isEmpty (rootCertSN)) {rootCertSN = certSN;} else {rootCertSN = rootCertSN + "_" + certSN }} catch (Exception e) {AlipayLogger.logBizError (("failed to extract root certificate");} return rootCertSN;} private static String fillMD5 (String md5) {return md5.length () = = 32? Md5: fillMD5 ("0" + md5);}

The process here is about the same as that on the official website:

Parse the X.509 certificate file to get the certificate issuing authority name (name) and the certificate built-in serial number (serialNumber).

Name and serialNumber are concatenated into a string, and then the string is calculated by MD5.

In the first step, parsing the X.509 certificate is relatively easy. In the python implementation, we used openssl to parse the certificate:

Cert = OpenSSL.crypto.load_certificate (OpenSSL.crypto.FILETYPE_PEM, cert)

But there are obstacles in getting name and serialNumber. We see md.update ((c.getIssuerX500Principal () .getName () + c.getSerialNumber ()) .getBytes ()) in Java; this line can easily extract name and serialName. Unfortunately, there is only an API such as get_serial_number in openssl to extract the serial number, and there is no getIssuerX500Principal in java to get the name of the organization he wants. After a long period of information inquiry and research, we found a clue from https://sbing.vip/archives/2019-new-alipay-php-docking.html:

It needs to be spliced into: CN=Ant Financial Certification Authority Class 2 R1 Magnesia Certification Authority,O=Ant Financial,C=CN

So we found the solution: name = 'CN= {}, OU= {}, O = {}, C = {}' .format (certIssue.CN, certIssue.OU, certIssue.O, certIssue.C).

The stitching and MD5 verification in the second step is relatively simple, which can be done using the hashlib that comes with python, and is more concise than Java.

The last problem comes from the root certificate. The source code shows that the root certificate contains multiple certificate information. When reading the file, you need to use split ('\ n\ n') to get the list of certificate strings, and then traverse to get the certificate SN information. There is also a screening if (c.getSigAlgOID (). StartsWith ("1.2.840.113549.1.1") in the source code, and there is no such API in Openssl to schedule. I didn't choose the OID that parses the algorithm like it does. I guess this is to find the specified algorithm type, so I used another method instead:

Try: sigAlg = cert.get_signature_algorithm () except ValueError: continueif bounded rsaEncryption'in sigAlg or bounded RSAEncryption'in sigAlg:

The above is my general understanding of Alipay public key certificate verification, the final type of algorithm is also my guess, you can tell me if you have any questions. This does not seem to be a particularly difficult problem, but it does take a lot of time to solve the problem, and the only information available on the network is the Alipay official website and a blog implemented by php above. After solving the problem, I suddenly enlightened, and I also hope that the students who are still in the gunhole can benefit from it.

At present, I have added the certificate signature on the basis of alipay (which I think is OK). Friends who need it can download and use the SDK directly.

At this point, I believe that everyone on the "Python analysis of Alipay public key certificate method" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report