Example usage for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo getPublicKeyData

List of usage examples for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo getPublicKeyData

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo getPublicKeyData.

Prototype

public DERBitString getPublicKeyData() 

Source Link

Document

for when the public key is raw bits.

Usage

From source file:be.neutrinet.ispng.vpn.api.VPNClientCertificate.java

@Put
public Representation storeCSR(Representation csrstream) {
    if (!getRequestAttributes().containsKey("client")) {
        return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
    }//w w  w.ja  v a 2s  . c o  m

    StreamRepresentation sr = (StreamRepresentation) csrstream;

    // Do all kinds of security checks
    try {
        Client client = Clients.dao.queryForId(getAttribute("client").toString());
        PEMParser parser = new PEMParser(sr.getReader());
        PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parser.readObject();

        SubjectPublicKeyInfo pkInfo = csr.getSubjectPublicKeyInfo();
        RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);

        // This makes the NSA work harder on their quantum computer
        // Require 4096 bit key
        // http://stackoverflow.com/a/20622933
        if (!(rsa.getModulus().bitLength() > 2048)) {
            ClientError err = new ClientError("ILLEGAL_KEY_SIZE");
            return new JacksonRepresentation(err);
        }

        X500Name subject = X500Name.getInstance(csr.getSubject());
        RDN[] rdns = subject.getRDNs(BCStyle.CN);
        if (rdns == null || rdns.length == 0) {
            return clientError("NO_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        String CN = IETFUtils.valueToString(rdns[0].getFirst().getValue());
        if (CN == null || CN.isEmpty()) {
            return clientError("INVALID_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        if (getQueryValue("rekey") != null && Boolean.parseBoolean(getQueryValue("rekey"))) {
            if (!getRequestAttributes().containsKey("cert")) {
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
            }

            Certificate old = Certificates.dao.queryForId(getAttribute("cert"));

            if (old == null)
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

            old.revocationDate = new Date();

            if (old.get() == null) {
                // this can happen when the old certificate is no longer present on the system
                // in which case the rekey has to go through
            } else if (pkInfo.getPublicKeyData().getString()
                    .equals(old.get().getSubjectPublicKeyInfo().getPublicKeyData().getString())) {
                return clientError("REKEY_USING_SAME_KEY", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }

            Certificates.dao.update(old);
        }

        for (Certificate existingCert : Certificates.dao.queryForEq("client_id", client)) {
            if (existingCert.revocationDate.getTime() > System.currentTimeMillis()) {
                return clientError("ANOTHER_CLIENT_CERT_ACTIVE", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }
        }

        // couple CN to client
        client.commonName = CN;
        Clients.dao.update(client);

        String caStorePath = VPN.cfg.getProperty("ca.storeDir", "ca");
        File dir = new File(caStorePath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        Certificate cert = new Certificate();
        cert.client = client;
        Certificates.dao.create(cert);

        FileWriter fw = new FileWriter(caStorePath + "/" + cert.id + ".csr");
        PEMWriter pw = new PEMWriter(fw);
        pw.writeObject(csr);
        pw.flush();

        return new JacksonRepresentation<>(cert);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to validate CSR and/or sign CSR", ex);
    }

    return DEFAULT_ERROR;
}

From source file:com.vvote.thirdparty.ximix.util.BLSPublicKeyFactory.java

License:Apache License

/**
 * Create BLS01PublicKeyParameters from an ASN.1 encoding of a SubjectPublicKeyInfo object.
 *
 * @param publicKeyInfo the info structure containing the BLS public key.
 * @return a BLS public key.//from  www .  ja  va2  s . co  m
 */
public static BLS01PublicKeyParameters createKey(SubjectPublicKeyInfo publicKeyInfo) {
    AlgorithmIdentifier algId = publicKeyInfo.getAlgorithm();
    CurveParameters curveParameters;
    Element G;
    Pairing pairing;
    try {
        ASN1Sequence parameters = ASN1Sequence.getInstance(algId.getParameters());

        curveParameters = new DefaultCurveParameters().load(new ByteArrayInputStream(
                DERUTF8String.getInstance(parameters.getObjectAt(0)).getString().getBytes("UTF8")));
        pairing = PairingFactory.getPairing(curveParameters);
        G = pairing.getG2().newElement();
        G.setFromBytes(DEROctetString.getInstance(parameters.getObjectAt(1)).getOctets());
    } catch (IOException e) {
        throw new IllegalStateException("Unable to support encoding: " + e.getMessage(), e);
    }

    BLS01Parameters blsParameters = new BLS01Parameters(curveParameters, G.getImmutable());
    Element pK = pairing.getG2().newElement();

    pK.setFromBytes(publicKeyInfo.getPublicKeyData().getBytes());

    return new BLS01PublicKeyParameters(blsParameters, pK.getImmutable());
}

From source file:eu.betaas.taas.securitymanager.common.ec.ECKeyPairGen.java

License:Apache License

/**
 * A method to reconstruct an ECPublicKey from a SubjectPublicKeyInfo of a 
 * certificate /*from   w  w w.  ja v  a  2s  .  c  o  m*/
 * @param info: SubjectPublicKeyInfo in a X509Certificate
 * @return: ECPublicKeyParameters
 */
public static ECPublicKeyParameters generateECPublicKey(SubjectPublicKeyInfo info) {
    X962Parameters as = (X962Parameters) info.getAlgorithm().getParameters();
    DERSequence aa = (DERSequence) as.getParameters();
    Enumeration en = aa.getObjects();
    ECCurve curve = null;
    org.bouncycastle.math.ec.ECPoint g = null;
    byte[] seed = null;
    BigInteger h = null;
    BigInteger n = null;
    while (en.hasMoreElements()) {
        Object oen = en.nextElement();
        if (oen instanceof X9Curve) {
            curve = ((X9Curve) oen).getCurve();
            seed = ((X9Curve) oen).getSeed();
        } else if (oen instanceof X9ECPoint) {
            g = ((X9ECPoint) oen).getPoint();
        } else if (oen instanceof ASN1Integer) {
            BigInteger xoen = ((ASN1Integer) oen).getValue();
            if (xoen.equals(BigInteger.ONE))
                h = xoen;
            else
                n = xoen;
        }
    }

    ASN1OctetString key = new DEROctetString(info.getPublicKeyData().getBytes());
    X9ECPoint derQ = new X9ECPoint(curve, key);

    ECDomainParameters dParams = new ECDomainParameters(curve, g, n, h, seed);

    return new ECPublicKeyParameters(derQ.getPoint(), dParams);
}

From source file:net.sf.keystore_explorer.crypto.publickey.KeyIdentifierGenerator.java

License:Open Source License

private byte[] encodeEcPublicKeyAsBitString(ECPublicKey ecPublicKey) {
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(ecPublicKey.getEncoded());
    byte[] bytes = publicKeyInfo.getPublicKeyData().getBytes();
    return bytes;
}

From source file:org.apache.kerby.pkix.EndEntityGenerator.java

License:Apache License

private static byte[] getDigest(SubjectPublicKeyInfo spki) {
    Digest digest = new SHA1Digest();
    byte[] resBuf = new byte[digest.getDigestSize()];

    byte[] bytes = spki.getPublicKeyData().getBytes();
    digest.update(bytes, 0, bytes.length);
    digest.doFinal(resBuf, 0);//from   w  w  w  .  ja v a2 s  .co  m
    return resBuf;
}

From source file:org.conscrypt.java.security.cert.CertificateFactoryTest.java

License:Apache License

/**
 * Generates a type 1 key identifier according to RFC 3280 4.2.1.2.
 *//*from  ww w.j  av  a2  s  .c om*/
private static byte[] generatePublicKeyDigest(PublicKey pubKey) {
    SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded());
    MessageDigest sha1digest;
    try {
        sha1digest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("SHA-1 not available");
    }
    return sha1digest.digest(spki.getPublicKeyData().getBytes());
}

From source file:org.xipki.ca.api.profile.x509.BaseX509Certprofile.java

License:Open Source License

@Override
public SubjectPublicKeyInfo checkPublicKey(final SubjectPublicKeyInfo publicKey)
        throws BadCertTemplateException {
    Map<ASN1ObjectIdentifier, KeyParametersOption> keyAlgorithms = getKeyAlgorithms();
    if (CollectionUtil.isEmpty(keyAlgorithms)) {
        return publicKey;
    }//from  w  ww .  j  a v  a  2 s.  c om

    ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm();
    if (keyAlgorithms.containsKey(keyType) == false) {
        throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted");
    }

    KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType);
    if (keyParamsOption instanceof AllowAllParametersOption) {
        return publicKey;
    } else if (keyParamsOption instanceof ECParamatersOption) {
        ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption;
        // parameters
        ASN1Encodable algParam = publicKey.getAlgorithm().getParameters();
        ASN1ObjectIdentifier curveOid;

        if (algParam instanceof ASN1ObjectIdentifier) {
            curveOid = (ASN1ObjectIdentifier) algParam;
            if (ecOption.allowsCurve(curveOid) == false) {
                throw new BadCertTemplateException("EC curve " + SecurityUtil.getCurveName(curveOid) + " (OID: "
                        + curveOid.getId() + ") is not allowed");
            }
        } else {
            throw new BadCertTemplateException("only namedCurve or implictCA EC public key is supported");
        }

        // point encoding
        if (ecOption.getPointEncodings() != null) {
            byte[] keyData = publicKey.getPublicKeyData().getBytes();
            if (keyData.length < 1) {
                throw new BadCertTemplateException("invalid publicKeyData");
            }
            byte pointEncoding = keyData[0];
            if (ecOption.getPointEncodings().contains(pointEncoding) == false) {
                throw new BadCertTemplateException("unaccepted EC point encoding " + pointEncoding);
            }
        }

        byte[] keyData = publicKey.getPublicKeyData().getBytes();
        try {
            checkECSubjectPublicKeyInfo(curveOid, keyData);
        } catch (BadCertTemplateException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("populateFromPubKeyInfo", e);
            throw new BadCertTemplateException("invalid public key: " + e.getMessage());
        }
        return publicKey;
    } else if (keyParamsOption instanceof RSAParametersOption) {
        RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption;

        ASN1Integer modulus;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes());
            modulus = ASN1Integer.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException e) {
            throw new BadCertTemplateException("invalid publicKeyData");
        }

        int modulusLength = modulus.getPositiveValue().bitLength();
        if ((rsaOption.allowsModulusLength(modulusLength))) {
            return publicKey;
        }
    } else if (keyParamsOption instanceof DSAParametersOption) {
        DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption;
        ASN1Encodable params = publicKey.getAlgorithm().getParameters();
        if (params == null) {
            throw new BadCertTemplateException("null Dss-Parms is not permitted");
        }

        int pLength;
        int qLength;

        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(params);
            ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0));
            ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(1));
            pLength = p.getPositiveValue().bitLength();
            qLength = q.getPositiveValue().bitLength();
        } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
            throw new BadCertTemplateException("illegal Dss-Parms");
        }

        boolean match = dsaOption.allowsPLength(pLength);
        if (match) {
            match = dsaOption.allowsQLength(qLength);
        }

        if (match) {
            return publicKey;
        }
    } else {
        throw new RuntimeException("should not reach here, unknown KeyParametersOption " + keyParamsOption);
    }

    throw new BadCertTemplateException("the given publicKey is not permitted");
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

private void checkPublicKey(final SubjectPublicKeyInfo publicKey) throws BadCertTemplateException {
    if (CollectionUtil.isEmpty(keyAlgorithms)) {
        return;/*ww  w . j  a  va 2  s .c  o m*/
    }

    ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm();
    if (keyAlgorithms.containsKey(keyType) == false) {
        throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted");
    }

    KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType);
    if (keyParamsOption instanceof AllowAllParametersOption) {
        return;
    } else if (keyParamsOption instanceof ECParamatersOption) {
        ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption;
        // parameters
        ASN1Encodable algParam = publicKey.getAlgorithm().getParameters();
        ASN1ObjectIdentifier curveOid;

        if (algParam instanceof ASN1ObjectIdentifier) {
            curveOid = (ASN1ObjectIdentifier) algParam;
            if (ecOption.allowsCurve(curveOid) == false) {
                throw new BadCertTemplateException("EC curve " + SecurityUtil.getCurveName(curveOid) + " (OID: "
                        + curveOid.getId() + ") is not allowed");
            }
        } else {
            throw new BadCertTemplateException("only namedCurve or implictCA EC public key is supported");
        }

        // point encoding
        if (ecOption.getPointEncodings() != null) {
            byte[] keyData = publicKey.getPublicKeyData().getBytes();
            if (keyData.length < 1) {
                throw new BadCertTemplateException("invalid publicKeyData");
            }
            byte pointEncoding = keyData[0];
            if (ecOption.getPointEncodings().contains(pointEncoding) == false) {
                throw new BadCertTemplateException("unaccepted EC point encoding " + pointEncoding);
            }
        }

        try {
            checkECSubjectPublicKeyInfo(curveOid, publicKey.getPublicKeyData().getBytes());
        } catch (BadCertTemplateException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("populateFromPubKeyInfo", e);
            throw new BadCertTemplateException("invalid public key: " + e.getMessage());
        }

        return;
    } else if (keyParamsOption instanceof RSAParametersOption) {
        RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption;

        ASN1Integer modulus;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes());
            modulus = ASN1Integer.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException e) {
            throw new BadCertTemplateException("invalid publicKeyData");
        }

        int modulusLength = modulus.getPositiveValue().bitLength();
        if ((rsaOption.allowsModulusLength(modulusLength))) {
            return;
        }
    } else if (keyParamsOption instanceof DSAParametersOption) {
        DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption;
        ASN1Encodable params = publicKey.getAlgorithm().getParameters();
        if (params == null) {
            throw new BadCertTemplateException("null Dss-Parms is not permitted");
        }

        int pLength;
        int qLength;

        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(params);
            ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0));
            ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(1));
            pLength = p.getPositiveValue().bitLength();
            qLength = q.getPositiveValue().bitLength();
        } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
            throw new BadCertTemplateException("illegal Dss-Parms");
        }

        boolean match = dsaOption.allowsPLength(pLength);
        if (match) {
            match = dsaOption.allowsQLength(qLength);
        }

        if (match) {
            return;
        }
    } else {
        throw new RuntimeException("should not reach here, unknown keyParamsOption "
                + (keyParamsOption == null ? "null" : keyParamsOption.getClass().getName()));
    }

    throw new BadCertTemplateException("the given publicKey is not permitted");
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

private void checkExtensionSubjectKeyIdentifier(final StringBuilder failureMsg, final byte[] extensionValue,
        final SubjectPublicKeyInfo subjectPublicKeyInfo) {
    // subjectKeyIdentifier
    SubjectKeyIdentifier asn1 = SubjectKeyIdentifier.getInstance(extensionValue);
    byte[] ski = asn1.getKeyIdentifier();
    byte[] pkData = subjectPublicKeyInfo.getPublicKeyData().getBytes();
    byte[] expectedSki = HashCalculator.hash(HashAlgoType.SHA1, pkData);
    if (Arrays.equals(expectedSki, ski) == false) {
        failureMsg.append("SKI is '" + hex(ski) + "' but expected is '" + hex(expectedSki) + "'");
        failureMsg.append("; ");
    }/* ww w.  ja  v  a  2s. c  om*/
}

From source file:org.xipki.ca.server.impl.IdentifiedX509Certprofile.java

License:Open Source License

public ExtensionValues getExtensions(final X500Name requestedSubject, final Extensions requestExtensions,
        final SubjectPublicKeyInfo publicKeyInfo, final PublicCAInfo publicCaInfo,
        final X509Certificate crlSignerCert) throws CertprofileException, BadCertTemplateException {
    ExtensionValues values = new ExtensionValues();

    Map<ASN1ObjectIdentifier, ExtensionControl> controls = new HashMap<>(certprofile.getExtensionControls());

    Set<ASN1ObjectIdentifier> neededExtensionTypes = new HashSet<>();
    Set<ASN1ObjectIdentifier> wantedExtensionTypes = new HashSet<>();
    if (requestExtensions != null) {
        Extension reqExtension = requestExtensions
                .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions);
        if (reqExtension != null) {
            ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue());
            neededExtensionTypes.addAll(ee.getNeedExtensions());
            wantedExtensionTypes.addAll(ee.getWantExtensions());
        }//ww w. j a v a  2s .com

        for (ASN1ObjectIdentifier oid : neededExtensionTypes) {
            if (wantedExtensionTypes.contains(oid)) {
                wantedExtensionTypes.remove(oid);
            }

            if (controls.containsKey(oid) == false) {
                throw new BadCertTemplateException("could not add needed extension " + oid.getId());
            }
        }
    }

    // SubjectKeyIdentifier
    ASN1ObjectIdentifier extType = Extension.subjectKeyIdentifier;
    ExtensionControl extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new CertprofileException(e.getMessage(), e);
        }
        byte[] skiValue = sha1.digest(publicKeyInfo.getPublicKeyData().getBytes());

        SubjectKeyIdentifier value = new SubjectKeyIdentifier(skiValue);
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // Authority key identifier
    extType = Extension.authorityKeyIdentifier;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        byte[] ikiValue = publicCaInfo.getSubjectKeyIdentifer();
        AuthorityKeyIdentifier value = null;
        if (ikiValue != null) {
            if (certprofile.includeIssuerAndSerialInAKI()) {
                GeneralNames x509CaSubject = new GeneralNames(new GeneralName(publicCaInfo.getX500Subject()));
                value = new AuthorityKeyIdentifier(ikiValue, x509CaSubject, publicCaInfo.getSerialNumber());
            } else {
                value = new AuthorityKeyIdentifier(ikiValue);
            }
        }

        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // IssuerAltName
    extType = Extension.issuerAlternativeName;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        GeneralNames value = publicCaInfo.getSubjectAltName();
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // AuthorityInfoAccess
    extType = Extension.authorityInfoAccess;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        AuthorityInfoAccessControl aiaControl = certprofile.getAIAControl();

        List<String> caIssuers = null;
        if (aiaControl == null || aiaControl.includesCaIssuers()) {
            caIssuers = publicCaInfo.getCaCertUris();
        }

        List<String> ocspUris = null;
        if (aiaControl == null || aiaControl.includesOcsp()) {
            ocspUris = publicCaInfo.getOcspUris();
        }
        AuthorityInformationAccess value = X509CertUtil.createAuthorityInformationAccess(caIssuers, ocspUris);
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    if (controls.containsKey(Extension.cRLDistributionPoints) || controls.containsKey(Extension.freshestCRL)) {
        X500Name crlSignerSubject = null;
        if (crlSignerCert != null) {
            crlSignerSubject = X500Name.getInstance(crlSignerCert.getSubjectX500Principal().getEncoded());
        }

        X500Name x500CaPrincipal = publicCaInfo.getX500Subject();

        // CRLDistributionPoints
        extType = Extension.cRLDistributionPoints;
        extControl = controls.remove(extType);
        if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
            CRLDistPoint value;
            try {
                value = X509CertUtil.createCRLDistributionPoints(publicCaInfo.getCrlUris(), x500CaPrincipal,
                        crlSignerSubject);
            } catch (IOException e) {
                throw new CertprofileException(e.getMessage(), e);
            }
            addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
        }

        // FreshestCRL
        extType = Extension.freshestCRL;
        extControl = controls.remove(extType);
        if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
            CRLDistPoint value;
            try {
                value = X509CertUtil.createCRLDistributionPoints(publicCaInfo.getDeltaCrlUris(),
                        x500CaPrincipal, crlSignerSubject);
            } catch (IOException e) {
                throw new CertprofileException(e.getMessage(), e);
            }
            addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
        }
    }

    // BasicConstraints
    extType = Extension.basicConstraints;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        BasicConstraints value = X509CertUtil.createBasicConstraints(certprofile.isCA(),
                certprofile.getPathLenBasicConstraint());
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // KeyUsage
    extType = Extension.keyUsage;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        Set<KeyUsage> usages = new HashSet<>();
        Set<KeyUsageControl> usageOccs = certprofile.getKeyUsage();
        for (KeyUsageControl k : usageOccs) {
            if (k.isRequired()) {
                usages.add(k.getKeyUsage());
            }
        }

        // the optional KeyUsage will only be set if requested explicitly
        if (requestExtensions != null && extControl.isRequest()) {
            addRequestedKeyusage(usages, requestExtensions, usageOccs);
        }

        org.bouncycastle.asn1.x509.KeyUsage value = X509Util.createKeyUsage(usages);
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // ExtendedKeyUsage
    extType = Extension.extendedKeyUsage;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        Set<ASN1ObjectIdentifier> usages = new HashSet<>();
        Set<ExtKeyUsageControl> usageOccs = certprofile.getExtendedKeyUsages();
        for (ExtKeyUsageControl k : usageOccs) {
            if (k.isRequired()) {
                usages.add(k.getExtKeyUsage());
            }
        }

        // the optional ExtKeyUsage will only be set if requested explicitly
        if (requestExtensions != null && extControl.isRequest()) {
            addRequestedExtKeyusage(usages, requestExtensions, usageOccs);
        }

        if (extControl.isCritical() && usages.contains(ObjectIdentifiers.anyExtendedKeyUsage)) {
            extControl = new ExtensionControl(false, extControl.isRequired(), extControl.isRequest());
        }

        ExtendedKeyUsage value = X509Util.createExtendedUsage(usages);
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // ocsp-nocheck
    extType = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        // the extension ocsp-nocheck will only be set if requested explicitly
        DERNull value = DERNull.INSTANCE;
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // SubjectAltName
    extType = Extension.subjectAlternativeName;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        GeneralNames value = null;
        if (requestExtensions != null && extControl.isRequest()) {
            value = createRequestedSubjectAltNames(requestExtensions, certprofile.getSubjectAltNameModes());
        }
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    // SubjectInfoAccess
    extType = Extension.subjectInfoAccess;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtensionTypes, wantedExtensionTypes)) {
        ASN1Sequence value = null;
        if (requestExtensions != null && extControl.isRequest()) {
            value = createSubjectInfoAccess(requestExtensions, certprofile.getSubjectInfoAccessModes());
        }
        addExtension(values, extType, value, extControl, neededExtensionTypes, wantedExtensionTypes);
    }

    ExtensionValues subvalues = certprofile.getExtensions(Collections.unmodifiableMap(controls),
            requestedSubject, requestExtensions);

    Set<ASN1ObjectIdentifier> extTypes = new HashSet<>(controls.keySet());
    for (ASN1ObjectIdentifier type : extTypes) {
        extControl = controls.remove(type);
        boolean addMe = addMe(type, extControl, neededExtensionTypes, wantedExtensionTypes);
        if (addMe) {
            ExtensionValue value = null;
            if (extControl.isRequest()) {
                Extension reqExt = requestExtensions.getExtension(type);
                if (reqExt != null) {
                    value = new ExtensionValue(reqExt.isCritical(), reqExt.getParsedValue());
                }
            }

            if (value == null) {
                value = subvalues.getExtensionValue(type);
            }

            addExtension(values, type, value, extControl, neededExtensionTypes, wantedExtensionTypes);
        }
    }

    Set<ASN1ObjectIdentifier> unprocessedExtTypes = new HashSet<>();
    for (ASN1ObjectIdentifier type : controls.keySet()) {
        if (controls.get(type).isRequired()) {
            unprocessedExtTypes.add(type);
        }
    }

    if (CollectionUtil.isNotEmpty(unprocessedExtTypes)) {
        throw new CertprofileException("could not add required extensions " + toString(unprocessedExtTypes));
    }

    if (CollectionUtil.isNotEmpty(neededExtensionTypes)) {
        throw new BadCertTemplateException(
                "could not add requested extensions " + toString(neededExtensionTypes));
    }

    return values;
}