Example usage for org.bouncycastle.asn1.x509 Extension subjectAlternativeName

List of usage examples for org.bouncycastle.asn1.x509 Extension subjectAlternativeName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension subjectAlternativeName.

Prototype

ASN1ObjectIdentifier subjectAlternativeName

To view the source code for org.bouncycastle.asn1.x509 Extension subjectAlternativeName.

Click Source Link

Document

Subject Alternative Name

Usage

From source file:org.cesecore.certificates.certificate.request.RequestMessageTest.java

License:Open Source License

private PKCS10CertificationRequest createP10(final String subjectDN)
        throws IOException, OperatorCreationException {
    // Create a P10 with extensions, in this case altNames with a DNS name
    ASN1EncodableVector altnameattr = new ASN1EncodableVector();
    altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    // AltNames//  ww  w.  j a  v a 2 s.c o m
    // String[] namearray = altnames.split(",");
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com");
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    Extensions exts = extgen.generate();
    altnameattr.add(new DERSet(exts));

    // Add a challenge password as well
    ASN1EncodableVector pwdattr = new ASN1EncodableVector();
    pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String("foo123"));
    pwdattr.add(new DERSet(pwdvalues));

    // Complete the Attribute section of the request, the set (Attributes)
    // contains one sequence (Attribute)
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(altnameattr));
    v.add(new DERSequence(pwdattr));
    DERSet attributes = new DERSet(v);

    // Create the PKCS10
    X500Name dn = new X500Name(subjectDN);
    PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", dn,
            keyPair.getPublic(), attributes, keyPair.getPrivate(), null);
    return basicpkcs10;
}

From source file:org.cesecore.certificates.certificateprofile.CertificateProfileTest.java

License:Open Source License

@Test
public void test06CertificateExtensions() throws Exception {
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);

    // Check standard values for the certificate profile
    List<String> l = profile.getUsedStandardCertificateExtensions();
    assertEquals(6, l.size());// w ww .  ja  v  a  2 s .  co m
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));

    CertificateProfile eprofile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);

    // Check standard values for the certificate profile
    l = eprofile.getUsedStandardCertificateExtensions();
    assertEquals(7, l.size());
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));
    assertTrue(l.contains(Extension.extendedKeyUsage.getId()));

    profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
    profile.setUseAuthorityInformationAccess(true);
    profile.setUseCertificatePolicies(true);
    profile.setUseCRLDistributionPoint(true);
    profile.setUseFreshestCRL(true);
    profile.setUseMicrosoftTemplate(true);
    profile.setUseOcspNoCheck(true);
    profile.setUseQCStatement(true);
    profile.setUseExtendedKeyUsage(true);
    profile.setUseSubjectDirAttributes(true);
    l = profile.getUsedStandardCertificateExtensions();
    assertEquals(15, l.size());
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));
    assertTrue(l.contains(Extension.extendedKeyUsage.getId()));
    assertTrue(l.contains(Extension.authorityInfoAccess.getId()));
    assertTrue(l.contains(Extension.certificatePolicies.getId()));
    assertTrue(l.contains(Extension.cRLDistributionPoints.getId()));
    assertTrue(l.contains(Extension.freshestCRL.getId()));
    assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    assertTrue(l.contains(Extension.qCStatements.getId()));
    assertTrue(l.contains(Extension.subjectDirectoryAttributes.getId()));
    assertTrue(l.contains(CertTools.OID_MSTEMPLATE));
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

@Test
public void test19getAltNameStringFromExtension() throws Exception {
    {/*from   ww  w  . j  a v a  2s . c o m*/
        PKCS10CertificationRequest p10 = new JcaPKCS10CertificationRequest(p10ReqWithAltNames);
        Attribute attribute = p10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)[0];
        // The set of attributes contains a sequence of with type oid
        // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest
        boolean found = false;
        DERSet s = (DERSet) attribute.getAttrValues();
        Extensions exts = Extensions.getInstance(s.getObjectAt(0));
        Extension ext = exts.getExtension(Extension.subjectAlternativeName);
        if (ext != null) {
            found = true;
            String altNames = CertTools.getAltNameStringFromExtension(ext);
            assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames);

        }
        assertTrue(found);
    }
    {
        PKCS10CertificationRequest p10 = new JcaPKCS10CertificationRequest(p10ReqWithAltNames2);
        // The set of attributes contains a sequence of with type oid
        // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest
        Attribute attribute = p10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)[0];
        boolean found = false;
        DERSet s = (DERSet) attribute.getAttrValues();
        Extensions exts = Extensions.getInstance(s.getObjectAt(0));
        Extension ext = exts.getExtension(Extension.subjectAlternativeName);
        if (ext != null) {
            found = true;
            String altNames = CertTools.getAltNameStringFromExtension(ext);
            assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames);
        }
        assertTrue(found);
    }

}

From source file:org.codice.ddf.security.certificate.generator.CertificateCommandTest.java

License:Open Source License

private static void validateSans(KeyStoreFile ksf, String alias, boolean withAdditionalSans) throws Exception {
    final KeyStore.Entry ke = ksf.getEntry(alias);
    assertThat(ke, instanceOf(KeyStore.PrivateKeyEntry.class));

    final KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry) ke;
    final Certificate c = pke.getCertificate();
    final X509CertificateHolder holder = new X509CertificateHolder(c.getEncoded());
    final Extension csn = holder.getExtension(Extension.subjectAlternativeName);

    assertThat(csn.getParsedValue().toASN1Primitive().getEncoded(ASN1Encoding.DER),
            equalTo(expectedSanGeneralName(alias, withAdditionalSans)));
}

From source file:org.conscrypt.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages,
        List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints,
        List<GeneralSubtree> excludedNameConstraints, BigInteger serialNumber) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;/* w  w w. j a v a 2  s.c  om*/
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha256WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha256WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    if (serialNumber == null) {
        byte[] serialBytes = new byte[16];
        new SecureRandom().nextBytes(serialBytes);
        serialNumber = new BigInteger(1, serialBytes);
    }

    X509v3CertificateBuilder x509cg = new X509v3CertificateBuilder(X500Name.getInstance(issuer.getEncoded()),
            serialNumber, start, end, X500Name.getInstance(subject.getEncoded()),
            SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
    if (keyUsage != 0) {
        x509cg.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    if (!subjectAltNames.isEmpty()) {
        x509cg.addExtension(Extension.subjectAlternativeName, false,
                new GeneralNames(subjectAltNames.toArray(new GeneralName[0])).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(Extension.nameConstraints, true,
                new NameConstraints(
                        permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]),
                        excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }

    X509CertificateHolder x509holder = x509cg
            .build(new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey));
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    X509Certificate x509c = (X509Certificate) certFactory
            .generateCertificate(new ByteArrayInputStream(x509holder.getEncoded()));
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Check the extensions in the certification request
 *
 * @throws OperatorCreationException//  w  ww.ja v  a 2  s .  com
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithExtensions()
        throws OperatorCreationException, PKICMPMessageException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    List<Extension> extensionList = new ArrayList<Extension>();
    // KeyUsage
    extensionList.add(new Extension(X509Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation).getEncoded()));
    // Extended keyUsage
    List<KeyPurposeId> keyPurposeIds = new ArrayList<KeyPurposeId>();
    keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_clientAuth));
    keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_emailProtection));
    extensionList.add(new Extension(X509Extension.extendedKeyUsage, false,
            new ExtendedKeyUsage(keyPurposeIds.toArray(new KeyPurposeId[keyPurposeIds.size()])).getEncoded()));
    // Subject alternative names
    List<GeneralName> generalNames = new ArrayList<GeneralName>();
    generalNames.add(new GeneralName(GeneralName.dNSName, "www1.cryptable.org"));
    generalNames.add(new GeneralName(GeneralName.dNSName, "www2.cryptable.org"));
    GeneralNames subjectAlternativeName = new GeneralNames(
            generalNames.toArray(new GeneralName[generalNames.size()]));
    extensionList.add(
            new Extension(X509Extension.subjectAlternativeName, false, subjectAlternativeName.getEncoded()));

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    pkiMessages.setExtensions(extensionList.toArray(new Extension[extensionList.size()]));
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    // KeyUsage
    KeyUsage verifyKeyUsage = KeyUsage.getInstance(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions()
            .getExtensionParsedValue(Extension.keyUsage));
    Assert.assertEquals(KeyUsage.digitalSignature | KeyUsage.nonRepudiation,
            verifyKeyUsage.getBytes()[0] & 0xFF);
    // Extended KeyUsage
    ExtendedKeyUsage verifyExtendedKeyUsage = ExtendedKeyUsage
            .fromExtensions(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions());
    Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection));
    // Subject Alternative Name
    GeneralNames verifyGeneralNames = GeneralNames.fromExtensions(
            certReqMsgs[0].getCertReq().getCertTemplate().getExtensions(), Extension.subjectAlternativeName);
    Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[0]));
    Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[1]));
}

From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java

License:Open Source License

/**
 * Generate a {@link PKCS10CertificationRequest} for the provided {@code certificate} and {@code keyPair}.
 *
 * @param keyPair     the {@link KeyPair} for {@code certificate}.
 * @param certificate the {@link X509Certificate} to request signing for.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 *//*from   w w  w .j a va 2  s .  c  om*/
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X509Certificate certificate)
        throws Exception {

    PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
            certificate.getSubjectX500Principal(), certificate.getPublicKey());

    GeneralNames subjectAltNames = new GeneralNames(
            getSubjectAltNames(certificate).toArray(new GeneralName[0]));

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(certificate.getSigAlgName());

    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java

License:Open Source License

/**
 * Generate a {@link PKCS10CertificationRequest}.
 *
 * @param keyPair            the {@link KeyPair} containing Public and Private keys.
 * @param subject            the subject name {@link X500Name}.
 * @param sanUri             the URI to request in the SAN.
 * @param sanDnsNames        the DNS names to request in the SAN.
 * @param sanIpAddresses     the IP addresses to request in the SAN.
 * @param signatureAlgorithm the signature algorithm to use when generating the signature to validate the
 *                           certificate.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 *///w ww  . j  a v a 2 s.co m
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X500Name subject, String sanUri,
        List<String> sanDnsNames, List<String> sanIpAddresses, String signatureAlgorithm) throws Exception {

    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject,
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    List<GeneralName> generalNames = new ArrayList<>();

    generalNames.add(new GeneralName(SUBJECT_ALT_NAME_URI, sanUri));

    sanDnsNames.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_DNS_NAME, n)).forEach(generalNames::add);

    sanIpAddresses.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_IP_ADDRESS, n))
            .forEach(generalNames::add);

    ExtensionsGenerator extGen = new ExtensionsGenerator();

    extGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames.toArray(new GeneralName[0])));

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

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);

    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java

License:Open Source License

protected void addSubjectAlternativeNames(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair,
        @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses)
        throws CertIOException, NoSuchAlgorithmException {

    List<GeneralName> generalNames = new ArrayList<>();

    if (applicationUri != null) {
        generalNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    }//  w  w w  .ja v a  2  s. c o m

    dnsNames.stream().distinct().map(s -> new GeneralName(GeneralName.dNSName, s)).forEach(generalNames::add);

    ipAddresses.stream().distinct().map(s -> new GeneralName(GeneralName.iPAddress, s))
            .forEach(generalNames::add);

    certificateBuilder.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames.toArray(new GeneralName[] {})));

    // Subject Key Identifier
    certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testExtensionOverride() throws Exception {
    final String altnames = "dNSName=foo1.bar.com,dNSName=foo2.bar.com,dNSName=foo3.bar.com,dNSName=foo4.bar.com,dNSName=foo5.bar.com,dNSName=foo6.bar.com,dNSName=foo7.bar.com,"
            + "dNSName=foo8.bar.com,dNSName=foo9.bar.com,dNSName=foo10.bar.com,dNSName=foo11.bar.com,dNSName=foo12.bar.com,dNSName=foo13.bar.com,dNSName=foo14.bar.com,"
            + "dNSName=foo15.bar.com,dNSName=foo16.bar.com,dNSName=foo17.bar.com,dNSName=foo18.bar.com,dNSName=foo19.bar.com,dNSName=foo20.bar.com,dNSName=foo21.bar.com";
    // Create a good certificate profile (good enough), using QC statement
    final String profileName = "TESTEXTENSIONOVERRIDE";
    certificateProfileSession.removeCertificateProfile(internalAdmin, profileName);
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Default profile does not allow Extension override
    certprof.setValidity(298);/*from   w  ww . ja  v  a2 s. c  o  m*/
    certificateProfileSession.addCertificateProfile(internalAdmin, profileName, certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId(profileName);
    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName);
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(internalAdmin, profileName, profile);
    try {
        int eeprofile = endEntityProfileSession.getEndEntityProfileId(profileName);
        int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
        EndEntityInformation user = new EndEntityInformation(RSA_USERNAME, "C=SE,CN=extoverride", rsacaid, null,
                "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        user.setStatus(EndEntityConstants.STATUS_NEW);
        // Change a user that we know...
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        // Create a P10 with extensions, in this case altNames with a lot of DNS
        // names
        ASN1EncodableVector extensionattr = new ASN1EncodableVector();
        extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altnames);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        extgen.addExtension(Extension.subjectAlternativeName, false, san);
        Extensions exts = extgen.generate();
        extensionattr.add(new DERSet(exts));
        // Complete the Attribute section of the request, the set (Attributes)
        // contains one sequence (Attribute)
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERSequence(extensionattr));
        DERSet attributes = new DERSet(v);
        // Create PKCS#10 certificate request
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                new X500Name("C=SE,CN=extoverride"), rsakeys.getPublic(), attributes, rsakeys.getPrivate(),
                null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        byte[] p10bytes = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes);
        p10.setUsername(RSA_USERNAME);
        p10.setPassword("foo123");
        // See if the request message works...
        Extensions p10exts = p10.getRequestExtensions();
        assertNotNull(p10exts);
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class,
                null);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
        // check altNames, should be none
        Collection<List<?>> c = cert.getSubjectAlternativeNames();
        assertNull(c);
        // Change so that we allow override of validity time
        CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile);
        prof.setAllowExtensionOverride(true);
        certificateProfileSession.changeCertificateProfile(internalAdmin, profileName, prof);
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
        cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
        // check altNames, should be one altName
        c = cert.getSubjectAlternativeNames();
        assertNotNull(c);
        assertEquals(21, c.size());
        String retAltNames = CertTools.getSubjectAlternativeName(cert);
        List<String> originalNames = Arrays.asList(altnames.split(","));
        List<String> returnNames = Arrays.asList(retAltNames.split(", "));
        assertTrue(originalNames.containsAll(returnNames));
    } finally {
        certificateProfileSession.removeCertificateProfile(internalAdmin, profileName);
        endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName);
    }
}