PAYATHON 2026

如何仅用 Java 标准 API 在内存中生成 X.509 v3 RSA 证书?

数据阿明

结论

可以实现。需要自行按证书结构进行 ASN.1 DER 编码,使用 Java 标准 API 完成 RSA 签名,再将编码结果解析为 X509Certificate。整个过程可以在内存中完成。

CertificateFactory.generateCertificate() 接收已经编码的证书数据,不能直接根据主题、有效期和公钥等字段签发证书。可以在最后用它解析证书,通过 ByteArrayInputStream 输入数据,无需创建文件。CertificateFactory 文档

实现步骤

  1. 使用 KeyPairGenerator 生成 RSA 密钥对,也可以传入已有密钥对。
  2. 按 X.509 结构编码 TBSCertificate,其中包含版本、序列号、签名算法、颁发者、有效期、主体、公钥和扩展。
  3. 使用私钥对 TBSCertificate 的完整 DER 字节签名。
  4. 将待签名内容、签名算法和签名值组装为完整证书,再解析成对象。

X.509 v3 的版本字段编码值是 2,版本和扩展分别使用 [0] EXPLICIT、[3] EXPLICIT 标签。扩展值还需要包在 OCTET STRING 中。这些结构要求见 RFC 5280 第 4.1 节。

仅使用标准库的示例

原问题没有说明由谁签发证书。下面以自签名证书为例:主体和颁发者相同,使用同一密钥对签名和验签。2048 位 RSA、365 天有效期和示例名称都是演示参数。

示例包含两个扩展:Basic Constraints 表示非 CA 证书,Key Usage 允许数字签名。签名使用 SHA256withRSA,其标准调用方式见 Signature 文档。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import javax.security.auth.x500.X500Principal;

public final class InMemoryX509 {
    // sha256WithRSAEncryption: 1.2.840.113549.1.1.11
    private static final byte[] SIGNATURE_ALGORITHM = seq(
        oid(0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b),
        der(0x05) // NULL
    );

    public static X509Certificate selfSigned(KeyPair pair) throws Exception {
        SecureRandom random = new SecureRandom();
        Instant now = Instant.now();
        byte[] name = new X500Principal("CN=Memory Example").getEncoded();

        // Positive serial number, encoded in at most 20 octets.
        BigInteger serial = new BigInteger(159, random).setBit(158);

        byte[] extensions = der(0xa3, seq(
            // Basic Constraints: cA defaults to false.
            extension(oid(0x55, 0x1d, 0x13), true, seq()),
            // Key Usage: digitalSignature; seven unused bits.
            extension(oid(0x55, 0x1d, 0x0f), true,
                der(0x03, new byte[] {7, (byte) 0x80}))
        ));

        byte[] tbs = seq(
            der(0xa0, integer(BigInteger.valueOf(2))),
            integer(serial),
            SIGNATURE_ALGORITHM,
            name,
            seq(time(now.minusSeconds(60)),
                time(now.plusSeconds(365L * 24 * 60 * 60))),
            name,
            pair.getPublic().getEncoded(),
            extensions
        );

        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initSign(pair.getPrivate(), random);
        signer.update(tbs);
        byte[] signature = signer.sign();

        byte[] encoded = seq(
            tbs,
            SIGNATURE_ALGORITHM,
            der(0x03, new byte[] {0}, signature)
        );

        return (X509Certificate) CertificateFactory.getInstance("X.509")
            .generateCertificate(new ByteArrayInputStream(encoded));
    }

    private static byte[] extension(byte[] oid, boolean critical,
                                    byte[] encodedValue) {
        byte[] value = der(0x04, encodedValue);
        return critical
            ? seq(oid, der(0x01, new byte[] {(byte) 0xff}), value)
            : seq(oid, value);
    }

    private static byte[] integer(BigInteger value) {
        return der(0x02, value.toByteArray());
    }

    private static byte[] time(Instant instant) {
        ZonedDateTime utc = instant.atZone(ZoneOffset.UTC);
        boolean useUtcTime = utc.getYear() >= 1950 && utc.getYear() <= 2049;
        String pattern = useUtcTime
            ? "yyMMddHHmmss'Z'"
            : "uuuuMMddHHmmss'Z'";
        byte[] value = DateTimeFormatter.ofPattern(pattern, Locale.ROOT)
            .format(utc).getBytes(StandardCharsets.US_ASCII);
        return der(useUtcTime ? 0x17 : 0x18, value);
    }

    // Arguments are encoded OID content octets, not decimal OID arcs.
    private static byte[] oid(int... octets) {
        byte[] value = new byte[octets.length];
        for (int i = 0; i < octets.length; i++) {
            value[i] = (byte) octets[i];
        }
        return der(0x06, value);
    }

    private static byte[] seq(byte[]... values) {
        return der(0x30, values);
    }

    // Encodes the single-octet tags needed by this example.
    private static byte[] der(int tag, byte[]... values) {
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        for (byte[] value : values) {
            body.write(value, 0, value.length);
        }

        byte[] content = body.toByteArray();
        int length = content.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(tag);

        if (length < 128) {
            out.write(length);
        } else {
            int count = 0;
            for (int n = length; n != 0; n >>>= 8) {
                count++;
            }
            out.write(0x80 | count);
            for (int i = count - 1; i >= 0; i--) {
                out.write(length >>> (8 * i));
            }
        }

        out.write(content, 0, content.length);
        return out.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();

        X509Certificate certificate = selfSigned(pair);
        certificate.checkValidity();
        certificate.verify(pair.getPublic());

        System.out.println(certificate.getVersion());
        // Keep pair.getPrivate() separately if the application needs it.
    }
}

代码没有文件读写,也没有直接调用 sun.security.x509 或第三方库。der() 只处理示例所需的单字节标签,并非完整的 ASN.1 编码库。

如何添加其他扩展

extension() 接收扩展 OID、是否为 critical,以及扩展值自身的 DER 编码。例如,为演示域名增加 Subject Alternative Name:

byte[] san = extension(
    oid(0x55, 0x1d, 0x11), // 2.5.29.17
    false,
    seq(der(0x82, "example.test".getBytes(StandardCharsets.US_ASCII)))
);

将 san 加入构造 extensions 的 seq(...) 中,然后重新生成 tbs 并签名。这里的 0x82 是 dNSName 的上下文标签;IP 地址等其他名称类型需要使用各自的标签和编码,不能直接复用这一段。RFC 5280 第 4.2.1.6 节

使用时需要注意什么

  • 扩展值的 DER 编码由调用方负责,extension() 仅负责外层封装。同一证书中不要重复添加相同 OID。
  • TBSCertificate 内部和证书外层的签名算法标识必须一致。示例固定使用 SHA256withRSA,更换签名算法时需要同步调整算法标识及参数编码。
  • checkValidity() 检查有效期,verify() 检查签名;两者都不代表证书已经获得客户端信任。自签名证书仍需要按使用场景配置可信证书。
  • X509Certificate 不包含私钥。需要签名或配置服务端身份时,应另外保留对应的 PrivateKey。
  • 若需要由 CA 签发,应分别传入主体公钥、颁发者名称和 CA 私钥,并按用途调整扩展。不能只把示例的颁发者名称改成某个 CA 名称。

备注:内容仅供参考。