Adding attributes to certificate request, java + bouncycastle 1.48

3.8k Views Asked by At

I'm currently working on creating attribute certificate requests using bouncycastle 1.48. Since there were some changes in API (and I'm beginner in this matter) I am unnable to add attributes to created request My current code is

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);

    KeyPair rsaKey = keyGen.generateKeyPair();
    PrivateKey privateKey = rsaKey.getPrivate();
    PublicKey publicKey = rsaKey.getPublic();

    System.out.println(privateKey.getEncoded());
    System.out.println(publicKey.getEncoded());
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(privateKey);
    AlgorithmIdentifier rsaEncryption = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, null); 
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(rsaEncryption, publicKey.getEncoded());
    Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);
    X500NameBuilder nameBuilder = new X500NameBuilder();
    nameBuilder.addRDN(BCStyle.CN, "test request");
    nameBuilder.addRDN(BCStyle.C, "UK");
    nameBuilder.addRDN(BCStyle.E,"[email protected]");
    nameBuilder.addRDN(BCStyle.GENDER,"M");
    X500Name name = nameBuilder.build();

    PKCS10CertificationRequestBuilder genReq = new PKCS10CertificationRequestBuilder(name,publicKeyInfo);
    PKCS10CertificationRequest request = genReq.build(sigGen);
    PEMWriter pemWriter = new PEMWriter(new FileWriter(new File("C:\\certs\\request.txt")));
    pemWriter.writeObject(request);
    pemWriter.flush();      

My question is - how should proper syntax looks like for addAttribute method? Thanks in advance

1

There are 1 best solutions below

0
On

It depends what you want to add. The main thing is to remember that attributes on a certificate request and extensions in a certificate are not the same thing. Generally people are trying to add one or more extensions, but in that case you need to use the appropriate PKCS#9 attribute to signify this, not the OID associated with the extension.

Say, for example, you wanted to request a specific KeyUsage extension from the CA, you would have something like:

ExtensionsGenerator extGen = new ExtensionsGenerator();

extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));

genReq.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

The extensionRequest block should then be assumed by the CA to contain the extensions you want.