Create a CSR with extended information in Java

Even if you google it, it will not be a hit in Japanese, so there may not be much demand, but ...

Operating environment

The version of Bouncy Castle used is as follows. It's too old!

Creating a CSR with private key, public key, and extended information

public class CreateExtensionCsr {
    public static void main(String[] args) throws Exception {
        //Generate an RSA encryption key to securely exchange the encryption key between two points.
        KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
        keygen.initialize(2048);
        KeyPair keyPair = keygen.generateKeyPair();

        //Private key
        PrivateKey privateKey = keyPair.getPrivate();

        //Public key
        PublicKey publicKey = keyPair.getPublic();

        //Create a CSR
        Security.addProvider(new BouncyCastleProvider());
        PKCS10CertificationRequest certReq = generateRequest(privateKey, publicKey);
        
        //Convert to PEM format
        String csr = toPem(certReq);

        System.out.println(csr);
    }

    /**
     *Create a CSR with extended information
     */
    public static PKCS10CertificationRequest generateRequest(PrivateKey privateKey,
            PublicKey publicKey) throws Exception {
        Vector oids = new Vector();
        Vector values = new Vector();

        //Creating extended information
        oids.add(X509Extensions.SubjectKeyIdentifier);
        values.add(new X509Extension(false, new DEROctetString(new SubjectKeyIdentifierStructure(
                publicKey))));
        oids.add(X509Extensions.KeyUsage);
        values.add(new X509Extension(true, new DEROctetString(new KeyUsage(
                KeyUsage.digitalSignature))));

        //Granting extended information
        X509Extensions extensions = new X509Extensions(oids, values);
        Attribute attribute =
                new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(
                        extensions));

        //Creating a CSR
        return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(
                "C=JP"), publicKey, new DERSet(
                attribute), privateKey);
    }

    /**
     *Convert to PEM format
     */
    private static String toPem(Object obj) throws IOException {
        StringWriter sw = new StringWriter();
        PEMWriter writer = null;
        try {
            writer = new PEMWriter(sw);
            writer.writeObject(obj);
            writer.flush();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        return sw.toString();
    }
}

Confirmation of CSR contents

$ openssl req -text -noout -in testcreate.csr
Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: C=JP
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:b4:ed:73:b2:3a:02:d6:e5:6c:33:29:98:0a:cc:
                    f8:74:43:e0:04:8b:98:1f:f0:4d:1c:28:6e:b4:ec:
                    <<abridgement>>
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Key Identifier:
                00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:0
            X509v3 Key Usage: critical
                Digital Signature
    Signature Algorithm: sha256WithRSAEncryption
         8d:b7:fd:e2:14:04:7a:85:02:f1:d5:49:c0:02:c8:f2:46:72:
         b9:b5:f5:b3:e3:cf:06:ae:44:7a:37:12:b2:3d:7b:86:d0:db:
         <<abridgement>>

Recommended Posts

Create a CSR with extended information in Java
Create a SlackBot with AWS lambda & API Gateway in Java
Create a TODO app in Java 7 Create Header
Split a string with ". (Dot)" in Java
I can't create a Java class with a specific name in IntelliJ
Read a string in a PDF file with Java
Create a simple bulletin board with Java + MySQL
[Windows] [IntelliJ] [Java] [Tomcat] Create a Tomcat9 environment with IntelliJ
Let's create a timed process with Java Timer! !!
[Java] Create a filter
Try to create a bulletin board in Java
[Java] Create a collection with only one element
Let's create a super-simple web framework in Java
Create JSON in Java
Let's make a calculator application with Java ~ Create a display area in the window
How to create a Java environment in just 3 seconds
[Beginner] Create a competitive game with basic Java knowledge
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
Quickly implement a singleton with an enum in Java
[Note] Create a java environment from scratch with docker
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Get EXIF information in Java
Create hyperlinks in Java PowerPoint
Create a java method [Memo] [java11]
[Java] Create a temporary file
Find a subset in Java
Create a playground with Xcode 12
Create Azure Functions in Java
Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID
I tried to create a java8 development environment with Chocolatey
Implementing a large-scale GraphQL server in Java with Netflix DGS
Create a method to return the tax rate in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
Create an immutable class with JAVA
Create a Vue3 environment with Docker!
Build a Java project with Gradle
Morphological analysis in Java with Kuromoji
3 Implement a simple interpreter in Java
I created a PDF in Java.
Create a database in a production environment
Create a new app in Rails
Create a Java project using Eclipse
[Java] How to create a folder
A simple sample callback in Java
Create a Servlet program in Eclipse
Get stuck in a Java primer
Create exceptions with a fluid interface
Play with Markdown in Java flexmark-java
Create a Maven project with a command
Create a simple web server with the Java standard library com.sun.net.httpserver
Let's create a TODO application in Java 4 Implementation of posting function
Create a named Skip List like redis sorted set in Java
Let's create a TODO application in Java 6 Implementation of search function
Create a high-performance enum with fields and methods like Java with JavaScript
How to create a new Gradle + Java + Jar project in Intellij 2016.03
Let's create a TODO application in Java 8 Implementation of editing function
Let's create a TODO application in Java 1 Brief explanation of MVC
Let's create a TODO application in Java 5 Switch the display of TODO
Graph the sensor information of Raspberry Pi in Java and check it with a web browser