Robert Daniels
Robert Daniels

Reputation: 161

How to overwrite CN in Bouncy Castle X500Name?

I'm signing CSRs in Java using Bouncy Castle. When signing, I want to copy the X500Name for subject from the CSR into the certificate, however I want to replace the CN that comes from CSR with a custom CN. Basically, clone the subject rdn list but overwrite, or create a custom CN for the certificate.

Basically, I'm looking for something like:

X500Name xname = CSR.getSubject();
xname.update("CN", "mycustomcn");

Upvotes: 2

Views: 2000

Answers (1)

dave_thompson_085
dave_thompson_085

Reputation: 39000

import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.x500.*;
import org.bouncycastle.asn1.x500.style.BCStyle;
...
// test value, actually use CSR subject
X500Name name = new X500Name ("O=Evil Inc,CN=original,L=Toronto,C=CA");
// get the RDNs as an array 
RDN[] rdns = name.getRDNs();
// find the attribute and mutate the containing RDN 
for(int i = 0; i < rdns.length; i++){
    AttributeTypeAndValue[] atts = rdns[i].getTypesAndValues();
    for(int j = 0; j < atts.length; j++){
        if( atts[j].getType().equals(BCStyle.CN) ){
            atts[j] = new AttributeTypeAndValue (BCStyle.CN, new DERUTF8String("substitute"));
            // or DERPrintableString if value suitable and you prefer
            // or maybe other DirectoryString choice if you don't believe in 5280 
            rdns[i] = new RDN (atts);
        }
    }
}
// put into a new X500Name
name = new X500Name (rdns);
System.out.println (name.toString()); // etc.

Upvotes: 2

Related Questions