Example usage for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

List of usage examples for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

Introduction

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

Prototype

private GeneralNames(ASN1Sequence seq) 

Source Link

Usage

From source file:org.tramaci.onionmail.LibSTLS.java

License:Open Source License

public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info,
        String[] AltName) throws Exception { //OK

    byte[] bi = Stdio.md5(onion.getBytes());
    byte[] bx = new byte[bi.length + 9];
    System.arraycopy(bi, 0, bx, 1, bi.length);
    bx[0] = 0x7C;//from   w ww  .  j  a  va  2  s  . com
    byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4);
    int bp = 17;
    for (int ax = 0; ax < 8; ax++)
        bx[bp++] = tmp[ax];

    Date startDate = new Date(Dfrom); // time from which certificate is valid
    Date expiryDate = new Date(Dto); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(bx); // serial number for certificate
    KeyPair keyPair = KP; // EC public/private key pair

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    if (info != null && info.length() > 0)
        info = ", " + info;
    else
        info = "";
    X500Principal dnName = new X500Principal("CN=" + onion + info);
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(KP.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    if (AltName != null) {
        int cx = AltName.length;
        for (int ax = 0; ax < cx; ax++)
            try {
                GeneralName generalName = new GeneralName(GeneralName.dNSName,
                        new DERIA5String(AltName[ax].toLowerCase().trim()));
                GeneralNames subjectAltNames = new GeneralNames(generalName);
                certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new DEROctetString(subjectAltNames));
            } catch (Exception EI) {
                Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n");
            }
    }

    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");

    return cert;
}

From source file:org.usrz.libs.crypto.cert.X509CertificateBuilder.java

License:Apache License

/**
 * Build the final {@link X509Certificate} instance.
 *///from   w w w  .j a va 2 s . c o m
public X509Certificate build() {
    if (subject == null)
        throw new IllegalStateException("Subject not specified");
    if (issuer == null)
        throw new IllegalStateException("Issuer not specified");
    if (serial == null)
        throw new IllegalStateException("Serial not specified");
    if (!notAfter.after(notBefore))
        throw new IllegalStateException("Date \"not-after\" before or equal to \"not-before\"");
    if (issuerPrivateKey == null)
        throw new IllegalStateException("Issuer private key not specified");
    if (subjectPublicKey == null)
        throw new IllegalStateException("Sobject public key not specified");

    /* Standard subject public key and X500 names */
    final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(subjectPublicKey.getEncoded());
    final X500Name subjectName = X500Name.getInstance(subject.getEncoded());
    final X500Name issuerName = X500Name.getInstance(issuer.getEncoded());

    /* Derive the issuer public key from the private one if needed/possible */
    if ((issuerPublicKey == null) && (issuerPrivateKey instanceof RSAPrivateCrtKey))
        try {
            final RSAPrivateCrtKey key = (RSAPrivateCrtKey) issuerPrivateKey;
            final RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            issuerPublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
        } catch (InvalidKeySpecException | NoSuchAlgorithmException exception) {
            Logger.getLogger(this.getClass().getName()).log(Level.FINE,
                    "Unable to generate public key from private", exception);
        }

    final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore, notAfter, subjectName, subjectPublicKeyInfo);

    try {
        final JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();

        /* Are we a certificate authority? */
        certificateBuilder.addExtension(Extension.basicConstraints, true,
                new BasicConstraints(Mode.AUTHORITY.equals(mode)));

        /* Add our subject key identifier */
        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(subjectPublicKeyInfo));

        /* Do we have Standard key usages? */
        if (!standardKeyUsage.isEmpty())
            certificateBuilder.addExtension(Extension.keyUsage, false,
                    new KeyUsage(StandardKeyUsage.combine(standardKeyUsage)));

        /* Do we have extended key usages? */
        if (!extendedKeyUsage.isEmpty())
            certificateBuilder.addExtension(Extension.extendedKeyUsage, false,
                    ExtendedKeyUsage.combine(extendedKeyUsage));

        /* Add our authority key identifer */
        if (issuerPublicKey != null) {
            final SubjectPublicKeyInfo authorityPublicKeyInfo = SubjectPublicKeyInfo
                    .getInstance(issuerPublicKey.getEncoded());
            certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                    utils.createAuthorityKeyIdentifier(authorityPublicKeyInfo));
        }

        /* Add our alternative names */
        if (!alternativeNames.isEmpty()) {
            final GeneralName[] names = alternativeNames.toArray(new GeneralName[alternativeNames.size()]);
            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(names));
        }

        /* Add CRL distribution points */
        if (!crlDistributionPoints.isEmpty()) {
            final DistributionPoint[] distributionPoints = new DistributionPoint[crlDistributionPoints.size()];
            int position = 0;
            for (GeneralName generalName : crlDistributionPoints) {
                final DistributionPointName distributionPointName = new DistributionPointName(
                        new GeneralNames(generalName));
                distributionPoints[position++] = new DistributionPoint(distributionPointName, null, null);
            }
            final CRLDistPoint crlDistributionPoint = new CRLDistPoint(distributionPoints);
            certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistributionPoint);
        }

    } catch (CertIOException | NoSuchAlgorithmException exception) {
        throw new IllegalStateException("Exception adding extensions", exception);
    }

    try {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final String signatureAlgorithm = CryptoUtils.getSignatureAlgorithm(issuerPrivateKey, hash);
        final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey);
        final X509CertificateHolder certificateHolder = certificateBuilder.build(signer);
        return (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    } catch (OperatorCreationException exception) {
        throw new IllegalStateException("Unable to create certificate signature", exception);
    } catch (IOException exception) {
        throw new IllegalStateException("Unable to generate certificate data", exception);
    } catch (CertificateException exception) {
        throw new IllegalStateException("Unable to generate certificate", exception);
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.CAAdminService.java

License:Open Source License

protected X509Certificate signCSR(String serialNo, PKCS10CertificationRequest request, int validity,
        PrivateKey privateKey, X509Certificate caCert) throws CaException {
    try {/*w  ww . j a v  a 2 s  .  c  o  m*/

        Date issuedDate = new Date();
        Date expiryDate = new Date(System.currentTimeMillis() + validity * MILLIS_PER_DAY);
        JcaPKCS10CertificationRequest jcaRequest = new JcaPKCS10CertificationRequest(request);
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(caCert,
                new BigInteger(serialNo), issuedDate, expiryDate, jcaRequest.getSubject(),
                jcaRequest.getPublicKey());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certificateBuilder
                .addExtension(Extension.authorityKeyIdentifier, false,
                        extUtils.createAuthorityKeyIdentifier(caCert))
                .addExtension(Extension.subjectKeyIdentifier, false,
                        extUtils.createSubjectKeyIdentifier(jcaRequest.getPublicKey()))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
                .addExtension(Extension.keyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment))
                .addExtension(Extension.extendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
        ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey);
        //todo add ocsp extension
        int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        DistributionPointName crlEp = new DistributionPointName(new GeneralNames(new GeneralName(
                GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/crl/" + tenantID)));
        DistributionPoint disPoint = new DistributionPoint(crlEp, null, null);
        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
                new CRLDistPoint(new DistributionPoint[] { disPoint }));
        AccessDescription ocsp = new AccessDescription(AccessDescription.id_ad_ocsp, new GeneralName(
                GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/ocsp/" + tenantID));
        ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector();
        authInfoAccessASN.add(ocsp);
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false,
                new DERSequence(authInfoAccessASN));
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateBuilder.build(signer));

        //            AccessDescription ocsp = new AccessDescription(ID_AD_OCSP,
        //                    new GeneralName(GeneralName.uniformResourceIdentifier,
        //                            new DERIA5String(CAUtils.getServerURL()+"/ca/ocsp/" + tenantID))
        //            );
        //
        //            ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector();
        //            authInfoAccessASN.add(ocsp);
        //
        //            certGen.addExtension(X509Extensions.AuthorityInfoAccess, false, new DERSequence(authInfoAccessASN));
        //
        //            DistributionPointName crlEP = new DistributionPointName(DNP_TYPE, new GeneralNames(
        //                    new GeneralName(GeneralName.uniformResourceIdentifier, CAUtils.getServerURL()+"/ca/crl/" + tenantID)));
        //
        //            DistributionPoint[] distPoints = new DistributionPoint[1];
        //            distPoints[0] = new DistributionPoint(crlEP, null, null);
        //
        //            certGen.addExtension(X509Extensions.CRLDistributionPoints, false, new CRLDistPoint(distPoints));
        //
        //            ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();
        //            for (int i = 0; i != attributes.size(); i++) {
        //                Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
        //
        //                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
        //                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
        //
        //                    Enumeration e = extensions.oids();
        //                    while (e.hasMoreElements()) {
        //                        DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
        //                        X509Extension ext = extensions.getExtension(oid);
        //
        //                        certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
        //                    }
        //                }
        //            }
        //            X509Certificate issuedCert = certGen.generateX509Certificate(privateKey);
        //            return issuedCert;
    } catch (Exception e) {
        throw new CaException("Error in signing the certificate", e);
    }
}

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

License:Open Source License

public static CRLDistPoint createCRLDistributionPoints(final List<String> crlUris, final X500Name caSubject,
        final X500Name crlSignerSubject) throws IOException, CertprofileException {
    if (CollectionUtil.isEmpty(crlUris)) {
        return null;
    }// w  w w. j av  a2 s  . c  o m

    int n = crlUris.size();
    DistributionPoint[] points = new DistributionPoint[1];

    GeneralName[] names = new GeneralName[n];
    for (int i = 0; i < n; i++) {
        names[i] = new GeneralName(GeneralName.uniformResourceIdentifier, crlUris.get(i));
    }
    // Distribution Point
    GeneralNames gns = new GeneralNames(names);
    DistributionPointName pointName = new DistributionPointName(gns);

    GeneralNames crlIssuer = null;
    if (crlSignerSubject != null && crlSignerSubject.equals(caSubject) == false) {
        GeneralName crlIssuerName = new GeneralName(crlSignerSubject);
        crlIssuer = new GeneralNames(crlIssuerName);
    }

    points[0] = new DistributionPoint(pointName, null, crlIssuer);

    return new CRLDistPoint(points);
}

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());
        }//from   ww w .  j av a2 s.  c o m

        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;
}

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

License:Open Source License

private static GeneralNames createRequestedSubjectAltNames(final Extensions requestExtensions,
        final Set<GeneralNameMode> modes) throws BadCertTemplateException {
    ASN1Encodable extValue = requestExtensions.getExtensionParsedValue(Extension.subjectAlternativeName);
    if (extValue == null) {
        return null;
    }//from   ww  w  .  j a va2 s . c om

    GeneralNames reqNames = GeneralNames.getInstance(extValue);
    if (modes == null) {
        return reqNames;
    }

    GeneralName[] reqL = reqNames.getNames();
    GeneralName[] l = new GeneralName[reqL.length];
    for (int i = 0; i < reqL.length; i++) {
        l[i] = createGeneralName(reqL[i], modes);
    }
    return new GeneralNames(l);
}

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

License:Open Source License

/**
 * added by lijun liao add the support of
 * @param certificateIssuer/* w ww  .j a v  a2 s.  co  m*/
 * @return
 */
private static Extension createCertificateIssuerExtension(final X500Name certificateIssuer) {
    try {
        GeneralName generalName = new GeneralName(certificateIssuer);
        return new Extension(Extension.certificateIssuer, true, new GeneralNames(generalName).getEncoded());
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding reason: " + e.getMessage(), e);
    }
}

From source file:org.xipki.commons.security.shell.p12.P12ComplexCertRequestGenCmd.java

License:Open Source License

private static GeneralNames createComplexGeneralNames(String prefix) {
    List<GeneralName> list = new LinkedList<>();
    // otherName// w ww .  j av  a  2 s.  com
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1ObjectIdentifier("1.2.3.1"));
    vec.add(new DERTaggedObject(true, 0, new DERUTF8String(prefix + "I am otherName 1.2.3.1")));
    list.add(new GeneralName(GeneralName.otherName, new DERSequence(vec)));

    vec = new ASN1EncodableVector();
    vec.add(new ASN1ObjectIdentifier("1.2.3.2"));
    vec.add(new DERTaggedObject(true, 0, new DERUTF8String(prefix + "I am otherName 1.2.3.2")));
    list.add(new GeneralName(GeneralName.otherName, new DERSequence(vec)));

    // rfc822Name
    list.add(new GeneralName(GeneralName.rfc822Name, prefix + "info@example.org"));

    // dNSName
    list.add(new GeneralName(GeneralName.dNSName, prefix + "dns.example.org"));

    // directoryName
    list.add(new GeneralName(GeneralName.directoryName, new X500Name("CN=demo,C=DE")));

    // ediPartyName
    vec = new ASN1EncodableVector();
    vec.add(new DERTaggedObject(false, 0, new DirectoryString(prefix + "assigner1")));
    vec.add(new DERTaggedObject(false, 1, new DirectoryString(prefix + "party1")));
    list.add(new GeneralName(GeneralName.ediPartyName, new DERSequence(vec)));

    // uniformResourceIdentifier
    list.add(new GeneralName(GeneralName.uniformResourceIdentifier, prefix + "uri.example.org"));

    // iPAddress
    list.add(new GeneralName(GeneralName.iPAddress, "69.1.2.190"));

    // registeredID
    list.add(new GeneralName(GeneralName.registeredID, "2.3.4.5"));

    return new GeneralNames(list.toArray(new GeneralName[0]));
}

From source file:org.xipki.commons.security.util.X509Util.java

License:Open Source License

public static GeneralNames createGeneralNames(final List<String> taggedValues) throws BadInputException {
    if (CollectionUtil.isEmpty(taggedValues)) {
        return null;
    }//from  ww  w .  j a v a 2  s .  co  m

    int len = taggedValues.size();
    GeneralName[] names = new GeneralName[len];
    for (int i = 0; i < len; i++) {
        names[i] = createGeneralName(taggedValues.get(i));
    }
    return new GeneralNames(names);
}

From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java

License:Open Source License

private GeneralNames createRequestedSubjectAltNames(final X500Name requestedSubject,
        final X500Name grantedSubject, final Extensions requestedExtensions) throws BadCertTemplateException {
    ASN1Encodable extValue = (requestedExtensions == null) ? null
            : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName);

    if (extValue == null && subjectToSubjectAltNameModes == null) {
        return null;
    }//from   w  ww .  j  av a  2  s  .  c  o  m

    GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue);
    if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) {
        return reqNames;
    }

    List<GeneralName> grantedNames = new LinkedList<>();
    // copy the required attributes of Subject
    if (subjectToSubjectAltNameModes != null) {
        for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
            GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType);

            RDN[] rdns = grantedSubject.getRDNs(attrType);
            if (rdns == null) {
                rdns = requestedSubject.getRDNs(attrType);
            }

            if (rdns == null) {
                continue;
            }

            for (RDN rdn : rdns) {
                String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
                switch (tag) {
                case rfc822Name:
                case dNSName:
                case uniformResourceIdentifier:
                case iPAddress:
                case directoryName:
                case registeredID:
                    grantedNames.add(new GeneralName(tag.getTag(), rdnValue));
                    break;
                default:
                    throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag);
                } // end switch (tag)
            }
        }
    }

    // copy the requested SubjectAltName entries
    if (reqNames != null) {
        GeneralName[] reqL = reqNames.getNames();
        for (int i = 0; i < reqL.length; i++) {
            grantedNames.add(X509CertprofileUtil.createGeneralName(reqL[i], subjectAltNameModes));
        }
    }

    return grantedNames.isEmpty() ? null : new GeneralNames(grantedNames.toArray(new GeneralName[0]));
}