在使用微信支付中:
附件中的三份文件(证书pkcs12格式、证书pem格式、证书密钥pem格式),为接口中强制要求时需携带的证书文件。
证书属于敏感信息,请妥善保管不要泄露和被他人复制。
不同开发语言下的证书格式不同,以下为说明指引:
证书pkcs12格式(apiclient_cert.p12):
包含了私钥信息的证书文件,为p12(pfx)格式,由微信支付签发给您用来标识和界定您的身份
部分安全性要求较高的API需要使用该证书来确认您的调用身份
windows上可以直接双击导入系统,导入过程中会提示输入证书密码,证书密码默认为您的商 户号(如:1900006031)
证书pem格式(apiclient_cert.pem)
从apiclient_cert.p12中导出证书部分的文件,为pem格式,请妥善保管不要泄漏和被他人复制
部分开发语言和环境,不能直接使用p12文件,而需要使用pem,所以为了方便您使用,已为您直接提供
您也可以使用openssl命令来自己导出:openssl pkcs12 -clcerts -nokeys -in apiclient_cert.p12 -out apiclient_cert.pem
证书密钥pem格式(apiclient_key.pem)
从apiclient_cert.p12中导出密钥部分的文件,为pem格式
部分开发语言和环境,不能直接使用p12文件,而需要使用pem,所以为了方便您使用,已为您直接提供
您也可以使用openssl命令来自己导出:openssl pkcs12 -nocerts -in apiclient_cert.p12 -out apiclient_key.pem
备注说明:
由于绝大部分操作系统已内置了微信支付服务器证书的根CA证书, 2018年3月6日后, 不再提供CA证书文件(rootca.pem)下载
import cn.hutool.core.codec.Base64; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.util.Enumeration;
/** * @param pkcs12Url 文件远程路径 http://ip/build/2023-11-16/apiclient_cert.p12 * @return */
public static String getCertPem(String pkcs12Url) throws Exception { String p12=pkcs12Url; URL url=new URL(p12); URLConnection connection=url.openConnection(); InputStream inputStream=connection.getInputStream(); //API证书apiclient_cert.p12的classpath路径,一般我们会放在resources路径下,当然你可以修 改获取证书输入流的方式。 //InputStream inputStream = new FileInputStream("本地文件路径"); //证书密码,这个默认就是商户号,在其它配置中也需要使用就是mchid final String KEYSTORE_PASSWORD="156045337111"; try { KeyStore ks=KeyStore.getInstance("PKCS12"); char[] nPassword=null; if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals("")) { nPassword=null; } else { nPassword=KEYSTORE_PASSWORD.toCharArray(); } ks.load(inputStream, nPassword); //循环获取别名 Enumeration enumm=ks.aliases(); String keyAlias=null; if (enumm.hasMoreElements()) // we are readin just one certificate. { keyAlias=(String) enumm.nextElement(); System.out.println("alias=[" + keyAlias + "]"); } // Now once we know the alias, we could get the keys. System.out.println("is key entry=" + ks.isKeyEntry(keyAlias)); //第一种获取私钥的方式 PrivateKey prikey=(PrivateKey) ks.getKey(keyAlias, nPassword); Certificate cert=ks.getCertificate(keyAlias); PublicKey pubkey=cert.getPublicKey(); System.out.println("cert class = " + cert.getClass().getName()); System.out.println("cert = " + cert); System.out.println("public key = " + pubkey); //第二种获取私钥的方式,这个是写在KeyStore文档里的,似乎是比较推荐的那种 KeyStore.ProtectionParameter protParam=new KeyStore.PasswordProtection(nPassword); //别名固定 为 Tenpay Certificate KeyStore.PrivateKeyEntry pkEntry=(KeyStore.PrivateKeyEntry) ks.getEntry("Tenpay Certificate", protParam); PrivateKey myPrivateKey=pkEntry.getPrivateKey(); //base64解码,获取真正信息 byte[] a=myPrivateKey.getEncoded(); String pri=Base64.encode(a); return pri; } catch (Exception e) { e.printStackTrace(); } return ""; }