如何在Bouncy Castle X500Name中覆盖CN?

时间:2018-04-11 23:56:59

标签: java bouncycastle

我正在使用Bouncy Castle在Java中签署CSR。签名时,我想将CSR的主题X500Name复制到证书中,但是我想用自定义CN替换来自CSR的CN。基本上,克隆主题rdn列表但覆盖,或为证书创建自定义CN。

基本上,我正在寻找类似的东西:

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

1 个答案:

答案 0 :(得分:1)

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.