需求
- 检索 macOS 锚点根证书
- 为其获取一个 Java X509Certificate 实例
可能的解决方案
据我所知,没有纯 Java 的解决方法。但是,您可以创建一个本地的 C 库,通过操作系统特定的调用检索证书,并通过 JNI 将它们返回给 Java。
自 macOS 10.3 以来,Security 框架中有一个名为 SecTrustCopyAnchorCertificates 的函数,
它检索由 macOS 存储的锚(根)证书。
详见https://developer.apple.com/documentation/security/1401507-sectrustcopyanchorcertificates?language=objc
要构造 Java X509Certificate 实例,您需要以 DER 编码格式获得证书数据,详见https://docs.oracle.com/javase/8/docs/api/java/security/cert/CertificateFactory.html#generateCertificate-java.io.InputStream-
在 macOS 上,您可以通过 SecCertificateCopyData 获取 DER 编码的证书数据。
注意:由于两个函数 SecTrustCopyAnchorCertificates 和 SecCertificateCopyData 都包含单词“Copy”,因此必须在使用后调用 CFRelease 以避免创建内存泄漏。
每个证书的数据可以存储在 Java 字节数组中,并返回给 Java 调用方。
在 Java 端,可以通过调用 CertificateFactory.getInstance("X.509")
来获取一个 CertificateFactory。然后,您可以通过调用 certFactory.generateCertificate(in)
将字节转换为 X509Certificate,其中 in 是 ByteArrayInputStream,其中实际来自本地 C 库的证书字节。
这是一个自包含的示例:
本地 C 库
#include <stdio.h>
#include <string.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
#include "com_software7_test_MacOSX509Certificates.h"
JNIEXPORT jobjectArray JNICALL Java_com_software7_test_MacOSX509Certificates_retrieveCertificates
(JNIEnv *env, jobject obj) {
CFArrayRef certs = NULL;
OSStatus status = SecTrustCopyAnchorCertificates(&certs);
if (status != noErr) {
jclass rte = (*env)->FindClass(env, "java/lang/RuntimeException");
if (rte != NULL)
(*env)->ThrowNew(env, rte, "error retrieving anchor certificates");
(*env)->DeleteLocalRef(env, rte);
}
CFIndex ncerts = CFArrayGetCount(certs);
jclass byteArrayClass = (*env)->FindClass(env, "[B");
jobjectArray array = (*env)->NewObjectArray(env, ncerts, byteArrayClass, (*env)->NewByteArray(env, 0));
for (int i = 0; i < ncerts; i++) {
SecCertificateRef certRef = (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
CFDataRef certData = SecCertificateCopyData(certRef);
int numBytes = CFDataGetLength(certData);
jbyteArray jCert = (*env)->NewByteArray(env, numBytes);
(*env)->SetByteArrayRegion(env, jCert, 0, numBytes, (const jbyte *)CFDataGetBytePtr(certData));
CFRelease(certData);
(*env)->SetObjectArrayElement(env, array, i, jCert);
(*env)->DeleteLocalRef(env, jCert);
}
CFRelease(certs);
return array;
}
Java
package com.software7.test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MacOSX509Certificates {
static {
System.loadLibrary("maccerts");
}
private native byte[][] retrieveCertificates();
public static void main(String[] args) {
MacOSX509Certificates mc = new MacOSX509Certificates();
mc.retrieveAndPrint();
}
private void retrieveAndPrint() {
List<X509Certificate> x509Certificates = retrieve();
for (X509Certificate x509c : x509Certificates) {
System.out.println(x509c.getSubjectX500Principal());
}
}
private List<X509Certificate> retrieve() {
byte[][] certs = retrieveCertificates();
return Arrays.stream(certs)
.<X509Certificate>map(MacOSX509Certificates::convertToX509Certificate)
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
private static <X509Certificate> X509Certificate convertToX509Certificate(byte[] bytes) {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
try (InputStream in = new ByteArrayInputStream(bytes)) {
return (X509Certificate) certFactory.generateCertificate(in);
}
} catch (CertificateException | IOException e) {
throw new RuntimeException(e);
}
}
}
构建
一个构建过程可能包括以下步骤:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home/
javac -h . com/software7/test/MacOSX509Certificates.java
clang -c -fPIC -I$JAVA_HOME/include -I$JAVA_HOME/include/darwin com_software7_test_MacOSX509Certificates.c -o com_software7_test_MacOSX509Certificates.o
clang -dynamiclib -o libmaccerts.dylib com_software7_test_MacOSX509Certificates.o -lc -framework CoreFoundation -framework Security
mv libmaccerts.dylib ../out/production/read_mac_system_certs
rm com_software7_test_MacOSX509Certificates.o
rm com/software7/test/MacOSX509Certificates.class
测试
如果您在 Mac 上运行此示例,则会返回:
CN=Go Daddy Root Certificate Authority - G2, O="GoDaddy.com, Inc.", L=Scottsdale, ST=Arizona, C=US
CN=SwissSign Platinum CA - G2, O=SwissSign AG, C=CH
CN=AddTrust Class 1 CA Root, OU=AddTrust TTP Network, O=AddTrust AB, C=SE
CN=Global Chambersign Root, OU=http://www.chambersign.org, O=AC Camerfirma SA CIF A82743287, C=EU
...
CertificateFactory
已经可以读取PEM格式。您也不需要拆分(解析)数据并循环--CertificateFactory.generateCertificates
(注意s
)可以自行读取PEM证书序列。 - dave_thompson_085