You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中生成DER格式CSR及实现PEM转DER(无BouncyCastle)

Got it, let's tackle these two CSR-related tasks using plain Java (no BouncyCastle required) step by step.

1. Generating a DER-formatted CSR in Java

To create a DER-encoded CSR directly with Java's standard libraries, we'll use core security APIs plus JDK-internal classes that are widely available (and standard for this use case without external dependencies).

Here's a complete, working example:

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import sun.security.pkcs.PKCS10;
import sun.security.x509.X500Name;

public class DerCsrGenerator {
    public static void main(String[] args) throws Exception {
        // 1. Generate a 2048-bit RSA key pair (industry standard for CSRs)
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(2048, new SecureRandom());
        KeyPair keyPair = keyPairGen.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 2. Define your CSR's subject distinguished name (DN)
        // Adjust these values to match your organization/domain
        String subjectDN = "CN=YourDomain.com, OU=Engineering, O=YourCompany, L=Austin, ST=TX, C=US";
        X500Name x500Name = new X500Name(subjectDN);

        // 3. Build the PKCS#10 CSR request and sign it
        PKCS10 pkcs10 = new PKCS10(publicKey);
        pkcs10.encodeAndSign(x500Name, privateKey, "SHA256withRSA", null);

        // 4. Get the raw DER-encoded bytes (PKCS10.getEncoded() outputs DER by default)
        byte[] derCsrBytes = pkcs10.getEncoded();

        // 5. Write the DER bytes to a file
        try (FileOutputStream fos = new FileOutputStream("my_csr.der")) {
            fos.write(derCsrBytes);
        }
        System.out.println("DER-formatted CSR generated successfully!");
    }
}

Quick notes:

  • The sun.security.pkcs.PKCS10 class handles all the CSR structure work, and its getEncoded() method natively returns DER-encoded data—no extra conversion steps needed.
  • We use SHA256withRSA for signing, which is secure and universally supported by certificate authorities.
2. Converting PEM CSR to DER (Equivalent to the OpenSSL Command)

The OpenSSL command you provided strips PEM headers/footers, Base64-decodes the content, and saves the raw bytes as DER. We can replicate this exactly with Java's standard libraries (no external dependencies needed).

Here's the Java code that matches the OpenSSL behavior:

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PemToDerConverter {
    public static void main(String[] args) throws Exception {
        // 1. Read the entire PEM CSR file into a string
        String pemContent = Files.readString(Paths.get("file_one.csr"), StandardCharsets.UTF_8);

        // 2. Clean up the PEM content: remove headers, footers, and all whitespace/newlines
        String base64Csr = pemContent
                .replace("-----BEGIN CERTIFICATE REQUEST-----", "")
                .replace("-----END CERTIFICATE REQUEST-----", "")
                .replaceAll("\\s+", "");

        // 3. Base64-decode the cleaned string to get raw DER bytes
        byte[] derCsrBytes = Base64.getDecoder().decode(base64Csr);

        // 4. Write the DER bytes to the output file
        try (FileOutputStream fos = new FileOutputStream("file_two.der")) {
            fos.write(derCsrBytes);
        }
        System.out.println("PEM CSR converted to DER successfully!");
    }
}

How this matches the OpenSSL command:

  • OpenSSL reads the PEM file, parses out the Base64 content between the headers, decodes it, and writes the raw bytes. This code does exactly the same thing using Java's built-in Base64 decoder and file APIs.
  • The replaceAll("\\s+", "") ensures we handle any line breaks or extra spaces that might be present in the PEM file.

内容的提问来源于stack exchange,提问作者Hulk Man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:45:13