如何在Java程序中设置SubjectAltName

如何在Java程序中设置SubjectAltName,java,bouncycastle,csr,Java,Bouncycastle,Csr,我有下面的java代码来生成CSR,但我不知道如何在下面的代码中添加SubjectAltName。假设我想在这里添加两个SAN,如a1.example.ca和a2.example.ca。请帮助在以下程序中添加SubjectAltName的位置和方式 public static void createCSR()抛出NoSuchAlgorithmException、OperatorCreationException和IOException{ 提供者bc=新 org.bouncycastle.jce.

我有下面的java代码来生成CSR,但我不知道如何在下面的代码中添加SubjectAltName。假设我想在这里添加两个SAN,如
a1.example.ca
a2.example.ca
。请帮助在以下程序中添加SubjectAltName的位置和方式

public static void createCSR()抛出NoSuchAlgorithmException、OperatorCreationException和IOException{
提供者bc=新
org.bouncycastle.jce.provider.BouncyCastleProvider();
安全性.insertProviderAt(bc,1);
KeyPairGenerator gen=KeyPairGenerator.getInstance(“RSA”);
第二代(2048年);
密钥对=gen.generateKeyPair();
PrivateKey PrivateKey=pair.getPrivate();
PublicKey PublicKey=pair.getPublic();
X500主体=新X500主体(“C=CN,ST=ON,L=Brmpt,O=loblaw,OU=network,CN=abc.example.ca,EMAILADDRESS=john。adam@test.ca");
ContentSigner-signGen=新的JcaContentSignerBuilder(“SHA1withRSA”).build(私钥);
PKCS10CertificationRequestBuilder=新JcaPKCS10CertificationRequestBuilder(主题,公钥);
PKCS10CertificationRequestCSR=builder.build(signGen);
OutputStreamWriter输出=新的OutputStreamWriter(System.out);
PEMWriter pem=新的PEMWriter(输出);
pem.writeObject(csr);
pem.writeObject(私钥);
pem.close();
}

您需要向PKCS10CertificationRequestBuilder添加一个属性,请求在证书上请求所需的扩展集:

//import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
//import org.bouncycastle.asn1.x509.Extension;
//import org.bouncycastle.asn1.x509.Extensions;
//import org.bouncycastle.asn1.x509.GeneralName;
//import org.bouncycastle.asn1.x509.GeneralNames;

GeneralName[] subjectAltNames = new GeneralName[]{
    new GeneralName(GeneralName.dNSName, "a1.example.ca"),
    new GeneralName(GeneralName.dNSName, "a2.example.ca")
};

Extension[] extensions = new Extension[] {
    Extension.create(Extension.subjectAlternativeName, true, new GeneralNames(subjectAltNames))
};

builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions));

您需要向PKCS10CertificationRequestBuilder添加一个属性,请求在证书上请求所需的扩展集:

//import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
//import org.bouncycastle.asn1.x509.Extension;
//import org.bouncycastle.asn1.x509.Extensions;
//import org.bouncycastle.asn1.x509.GeneralName;
//import org.bouncycastle.asn1.x509.GeneralNames;

GeneralName[] subjectAltNames = new GeneralName[]{
    new GeneralName(GeneralName.dNSName, "a1.example.ca"),
    new GeneralName(GeneralName.dNSName, "a2.example.ca")
};

Extension[] extensions = new Extension[] {
    Extension.create(Extension.subjectAlternativeName, true, new GeneralNames(subjectAltNames))
};

builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions));