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

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

Introduction

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

Prototype

X509DefaultEntryConverter

Source Link

Usage

From source file:org.cesecore.certificates.util.cert.SubjectDirAttrExtension.java

License:Open Source License

/**
 * From subjectDirAttributes string as defined in getSubjectDirAttribute 
 * @param dirAttr string of SubjectDirectoryAttributes
 * @return A Collection of ASN.1 Attribute (org.bouncycastle.asn1.x509), or an empty Collection, never null
 * @see #getSubjectDirectoryAttributes(Certificate)
 *//*from   ww  w.ja  v  a2s. c  o  m*/
public static Collection<Attribute> getSubjectDirectoryAttributes(String dirAttr) {
    ArrayList<Attribute> ret = new ArrayList<Attribute>();
    Attribute attr = null;
    String value = CertTools.getPartFromDN(dirAttr, "countryOfResidence");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new ASN1ObjectIdentifier(id_pda_countryOfResidence), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "countryOfCitizenship");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new ASN1ObjectIdentifier(id_pda_countryOfCitizenship), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "gender");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new ASN1ObjectIdentifier(id_pda_gender), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "placeOfBirth");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        X509DefaultEntryConverter conv = new X509DefaultEntryConverter();
        ASN1Primitive obj = conv.getConvertedValue(new ASN1ObjectIdentifier(id_pda_placeOfBirth), value);
        vec.add(obj);
        attr = new Attribute(new ASN1ObjectIdentifier(id_pda_placeOfBirth), new DERSet(vec));
        ret.add(attr);
    }
    // dateOfBirth that is a GeneralizedTime
    // The correct format for this is YYYYMMDD, it will be padded to YYYYMMDD120000Z
    value = CertTools.getPartFromDN(dirAttr, "dateOfBirth");
    if (!StringUtils.isEmpty(value)) {
        if (value.length() == 8) {
            value += "120000Z"; // standard format according to rfc3739
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(new DERGeneralizedTime(value));
            attr = new Attribute(new ASN1ObjectIdentifier(id_pda_dateOfBirth), new DERSet(vec));
            ret.add(attr);
        } else {
            log.error("Wrong length of data for 'dateOfBirth', should be of format YYYYMMDD, skipping...");
        }
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 *//*from  w ww  .  ja  v a  2  s  .  com*/
public byte[] createRequest(Collection<DEREncodable> attributes, String signAlg, Certificate cacert,
        int signatureKeyPurpose) throws CATokenOfflineException {
    log.trace(
            ">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", " + signatureKeyPurpose);
    ASN1Set attrset = new DERSet();
    if (attributes != null) {
        log.debug("Adding attributes in the request");
        Iterator<DEREncodable> iter = attributes.iterator();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        while (iter.hasNext()) {
            DEREncodable o = (DEREncodable) iter.next();
            vec.add(o);
            attrset = new DERSet(vec);
        }
    }
    X509NameEntryConverter converter = null;
    if (getUsePrintableStringSubjectDN()) {
        converter = new PrintableStringEntryConverter();
    } else {
        converter = new X509DefaultEntryConverter();
    }
    X509Name x509dn = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
    PKCS10CertificationRequest req;
    try {
        CATokenContainer catoken = getCAToken();
        KeyPair keyPair = new KeyPair(catoken.getPublicKey(signatureKeyPurpose),
                catoken.getPrivateKey(signatureKeyPurpose));
        if (keyPair == null) {
            throw new IllegalArgumentException(
                    "Keys for key purpose " + signatureKeyPurpose + " does not exist.");
        }
        req = new PKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset,
                keyPair.getPrivate(), catoken.getProvider());
        log.trace("<createRequest");
        return req.getEncoded();
    } catch (CATokenOfflineException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/**
 * sequence is ignored by X509CA//from   w ww  .  j a v a 2s  .  c  o m
 */
public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey,
        int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions,
        String sequence, PublicKey caPublicKey, PrivateKey caPrivateKey, String provider) throws Exception {

    // We must only allow signing to take place if the CA itself if on line, even if the token is on-line.
    // We have to allow expired as well though, so we can renew expired CAs
    if ((getStatus() != SecConst.CA_ACTIVE) && ((getStatus() != SecConst.CA_EXPIRED))) {
        String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus());
        if (log.isDebugEnabled()) {
            log.debug(msg); // This is something we handle so no need to log with higher priority
        }
        throw new CAOfflineException(msg);
    }

    final String sigAlg;
    if (certProfile.getSignatureAlgorithm() == null) {
        sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();
    } else {
        sigAlg = certProfile.getSignatureAlgorithm();
    }
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    String dn = subject.getCertificateDN();
    // Check if this is a root CA we are creating
    final boolean isRootCA = certProfile.getType() == CertificateProfile.TYPE_ROOTCA;

    // Get certificate validity time notBefore and notAfter
    final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert,
            isRootCA);

    final X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();
    {
        // Serialnumber is either random bits, where random generator is initialized by the serno generator.
        // Or a custom serial number defined in the end entity object
        final ExtendedInformation ei = subject.getExtendedinformation();
        BigInteger customSN = ei != null ? ei.certificateSerialNumber() : null;
        if (customSN != null) {
            if (!certProfile.getAllowCertSerialNumberOverride()) {
                final String msg = intres.getLocalizedMessage(
                        "signsession.certprof_not_allowing_cert_sn_override_using_normal",
                        customSN.toString(16));
                log.info(msg);
                customSN = null;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using custom serial number: " + customSN.toString(16));
                }
            }
        }
        final BigInteger serno = customSN != null ? customSN : SernoGenerator.instance().getSerno();
        certgen.setSerialNumber(serno);
    }
    certgen.setNotBefore(val.getNotBefore());
    certgen.setNotAfter(val.getNotAfter());
    certgen.setSignatureAlgorithm(sigAlg);

    // Make DNs
    if (certProfile.getUseSubjectDNSubSet()) {
        dn = certProfile.createSubjectDNSubSet(dn);
    }

    if (certProfile.getUseCNPostfix()) {
        dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix());
    }

    X509NameEntryConverter converter = null;
    if (getUsePrintableStringSubjectDN()) {
        converter = new PrintableStringEntryConverter();
    } else {
        converter = new X509DefaultEntryConverter();
    }
    // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN
    boolean ldapdnorder = true;
    if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) {
        ldapdnorder = false;
    }
    X509Name subjectDNName = CertTools.stringToBcX509Name(dn, converter, ldapdnorder);
    if (certProfile.getAllowDNOverride() && (requestX509Name != null)) {
        subjectDNName = requestX509Name;
        if (log.isDebugEnabled()) {
            log.debug("Using X509Name from request instead of user's registered.");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Using subjectDN: " + subjectDNName.toString());
    }
    certgen.setSubjectDN(subjectDNName);
    // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN
    // which many applications do not like.
    if (isRootCA) {
        // This will be an initial root CA, since no CA-certificate exists
        // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer,
        // it might have changed over the years.
        if (log.isDebugEnabled()) {
            log.debug("Using subject DN also as issuer DN, because it is a root CA");
        }
        certgen.setIssuerDN(subjectDNName);
    } else {
        javax.security.auth.x500.X500Principal issuerPrincipal = cacert.getSubjectX500Principal();
        if (log.isDebugEnabled()) {
            log.debug("Using issuer DN directly from the CA certificate: " + issuerPrincipal.getName());
        }
        certgen.setIssuerDN(issuerPrincipal);
    }
    certgen.setPublicKey(publicKey);

    //
    // X509 Certificate Extensions
    //

    // Extensions we will add to the certificate, later when we have filled the structure with 
    // everything we want.
    X509ExtensionsGenerator extgen = new X509ExtensionsGenerator();

    // First we check if there is general extension override, and add all extensions from 
    // the request in that case
    if (certProfile.getAllowExtensionOverride() && extensions != null) {
        Enumeration en = extensions.oids();
        while (en != null && en.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (log.isDebugEnabled()) {
                log.debug("Overriding extension with oid: " + oid);
            }
            extgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
        }
    }

    // Second we see if there is Key usage override
    X509Extensions overridenexts = extgen.generate();
    if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {
        if (log.isDebugEnabled()) {
            log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage);
        }
        if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) {
            X509KeyUsage ku = new X509KeyUsage(keyusage);
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(X509Extensions.KeyUsage) == null) {
                extgen.addExtension(X509Extensions.KeyUsage, certProfile.getKeyUsageCritical(), ku);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "KeyUsage was already overridden by an extension, not using KeyUsage from parameter.");
                }
            }
        }
    }

    // Third, check for standard Certificate Extensions that should be added.
    // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory
    // and implemented in package org.ejbca.core.model.certextensions.standard
    CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions();
    Iterator<String> certStdExtIter = usedStdCertExt.iterator();
    overridenexts = extgen.generate();
    while (certStdExtIter.hasNext()) {
        String oid = certStdExtIter.next();
        // We don't want to try to add standard extensions with the same oid if we have already added them 
        // from the request, if AllowExtensionOverride is enabled.
        // Two extensions with the same oid is not allowed in the standard.
        if (overridenexts.getExtension(new DERObjectIdentifier(oid)) == null) {
            CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile);
            if (certExt != null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Extension with oid " + oid
                        + " has been overridden, standard extension will not be added.");
            }
        }
    }

    // Fourth, check for custom Certificate Extensions that should be added.
    // Custom certificate extensions is defined in certextensions.properties
    fact = CertificateExtensionFactory.getInstance();
    List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions();
    Iterator<Integer> certExtIter = usedCertExt.iterator();
    while (certExtIter.hasNext()) {
        Integer id = certExtIter.next();
        CertificateExtension certExt = fact.getCertificateExtensions(id);
        if (certExt != null) {
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(new DERObjectIdentifier(certExt.getOID())) == null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Extension with oid " + certExt.getOID()
                            + " has been overridden, custom extension will not be added.");
                }
            }
        }
    }

    // Finally add extensions to certificate generator
    X509Extensions exts = extgen.generate();
    Enumeration en = exts.oids();
    while (en.hasMoreElements()) {
        DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
        X509Extension ext = exts.getExtension(oid);
        certgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
    }

    //
    // End of extensions
    //

    X509Certificate cert;
    if (log.isTraceEnabled()) {
        log.trace(">certgen.generate");
    }
    cert = certgen.generate(caPrivateKey, provider);
    if (log.isTraceEnabled()) {
        log.trace("<certgen.generate");
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert
    // because something is wrong...
    PublicKey verifyKey;
    // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing
    // the keys. In this case the _new_ key will not match the current CA certificate.
    if ((cacert != null) && (!isRootCA)) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = caPublicKey;
    }
    cert.verify(verifyKey);

    // If we have a CA-certificate, verify that we have all path verification stuff correct
    if (cacert != null) {
        byte[] aki = CertTools.getAuthorityKeyId(cert);
        byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert);
        if ((aki != null) && (ski != null)) {
            boolean eq = Arrays.equals(aki, ski);
            if (!eq) {
                String akistr = new String(Hex.encode(aki));
                String skistr = new String(Hex.encode(ski));
                log.error(intres.getLocalizedMessage("signsession.errorpathverifykeyid", akistr, skistr));
            }
        }
        Principal issuerDN = cert.getIssuerX500Principal();
        Principal subjectDN = cacert.getSubjectX500Principal();
        if ((issuerDN != null) && (subjectDN != null)) {
            boolean eq = issuerDN.equals(subjectDN);
            if (!eq) {
                log.error(intres.getLocalizedMessage("signsession.errorpathverifydn", issuerDN.getName(),
                        subjectDN.getName()));
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: "
                + subject.getCertificateDN());
    }
    return cert;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/** Generate a CRL or a deltaCRL
 * //w w  w .  ja v a  2  s  .  c o m
 * @param certs list of revoked certificates
 * @param crlnumber CRLNumber for this CRL
 * @param isDeltaCRL true if we should generate a DeltaCRL
 * @param basecrlnumber caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CATokenOfflineException
 * @throws IllegalKeyStoreException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private CRL generateCRL(Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL,
        int basecrlnumber)
        throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }
    Date thisUpdate = new Date();
    Date nextUpdate = new Date();

    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
    crlgen.setThisUpdate(thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    crlgen.setSignatureAlgorithm(sigAlg);
    // Make DNs
    X509Certificate cacert = (X509Certificate) getCACertificate();
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        X509NameEntryConverter converter = null;
        if (getUsePrintableStringSubjectDN()) {
            converter = new PrintableStringEntryConverter();
        } else {
            converter = new X509DefaultEntryConverter();
        }

        X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
        crlgen.setIssuerDN(caname);
    } else {
        crlgen.setIssuerDN(cacert.getSubjectX500Principal());
    }
    if (certs != null) {
        Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(
                new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded()))
                        .readObject());
        AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
        crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(),
                aki);
    }
    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(X509Extensions.CRLNumber.getId(), this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(X509Extensions.DeltaCRLIndicator.getId(), true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(X509Extensions.IssuingDistributionPoint.getId(),
                    getCrlDistributionPointOnCrlCritical(), idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(X509Extensions.FreshestCRL.getId(), false, ext);
            }

        }
    }

    X509CRL crl;
    crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),
            getCAToken().getProvider());
    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN);
    }
    crl.verify(verifyKey);

    return crl;
}

From source file:org.ejbca.util.cert.SubjectDirAttrExtension.java

License:Open Source License

/**
 * From subjectDirAttributes string as defined in getSubjectDirAttribute 
 * @param dirAttr string of SubjectDirectoryAttributes
 * @return A Collection of ASN.1 Attribute (org.bouncycastle.asn1.x509), or an empty Collection, never null
 * @see #getSubjectDirectoryAttributes(Certificate)
 *//*  w  w w.  j  av a  2  s  .com*/
public static Collection<Attribute> getSubjectDirectoryAttributes(String dirAttr) {
    ArrayList<Attribute> ret = new ArrayList<Attribute>();
    Attribute attr = null;
    String value = CertTools.getPartFromDN(dirAttr, "countryOfResidence");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_countryOfResidence), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "countryOfCitizenship");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_countryOfCitizenship), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "gender");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_gender), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "placeOfBirth");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        X509DefaultEntryConverter conv = new X509DefaultEntryConverter();
        DERObject obj = conv.getConvertedValue(new DERObjectIdentifier(id_pda_placeOfBirth), value);
        vec.add(obj);
        attr = new Attribute(new DERObjectIdentifier(id_pda_placeOfBirth), new DERSet(vec));
        ret.add(attr);
    }
    // dateOfBirth that is a GeneralizedTime
    // The correct format for this is YYYYMMDD, it will be padded to YYYYMMDD120000Z
    value = CertTools.getPartFromDN(dirAttr, "dateOfBirth");
    if (!StringUtils.isEmpty(value)) {
        if (value.length() == 8) {
            value += "120000Z"; // standard format according to rfc3739
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(new DERGeneralizedTime(value));
            attr = new Attribute(new DERObjectIdentifier(id_pda_dateOfBirth), new DERSet(vec));
            ret.add(attr);
        } else {
            log.error("Wrong length of data for 'dateOfBirth', should be of format YYYYMMDD, skipping...");
        }
    }
    return ret;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/** See stringToBcX509Name(String, X509NameEntryConverter, boolean), this method uses the default BC converter (X509DefaultEntryConverter) and ldap order
 * @see #stringToBcX509Name(String, X509NameEntryConverter, boolean)
 * @param dn String containing DN that will be transformed into X509Name, The
 *          DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in
 *          the string will be added to the end positions of OID array.
 * /*from   www  . j  a v  a2 s .c  om*/
 * @return X509Name or null if input is null
 */
public static X509Name stringToBcX509Name(String dn) {
    X509NameEntryConverter converter = new X509DefaultEntryConverter();
    return stringToBcX509Name(dn, converter, true);
}

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

License:Open Source License

/**
 * Tests the reversing of a DN/*from   w ww.j a  va  2  s  .co m*/
 * 
 * @throws Exception
 *             if error...
 */
public void test09TestReverseDN() throws Exception {
    log.trace(">test09TestReverse()");
    // We try to examine the that we handle modern dc components for ldap
    // correctly
    String dn1 = "dc=com,dc=bigcorp,dc=se,ou=orgunit,ou=users,cn=Tomas G";
    String dn2 = "cn=Tomas G,ou=users,ou=orgunit,dc=se,dc=bigcorp,dc=com";
    assertTrue(CertTools.isDNReversed(dn1));
    assertTrue(!CertTools.isDNReversed(dn2));
    assertTrue(CertTools.isDNReversed("C=SE,CN=Foo"));
    assertTrue(!CertTools.isDNReversed("CN=Foo,O=FooO"));
    String revdn1 = CertTools.reverseDN(dn1);
    log.debug("dn1: " + dn1);
    log.debug("revdn1: " + revdn1);
    assertEquals(dn2, revdn1);

    String dn3 = "cn=toto,cn=titi,dc=domain,dc=tld";
    String revdn3 = CertTools.reverseDN(dn3);
    assertEquals("dc=tld,dc=domain,cn=titi,cn=toto", revdn3);

    X509Name dn4 = CertTools.stringToBcX509Name(dn3, new X509DefaultEntryConverter(), true);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", dn4.toString());
    X509Name dn5 = CertTools.stringToBcX509Name(dn3, new X509DefaultEntryConverter(), false);
    assertEquals("DC=tld,DC=domain,CN=titi,CN=toto", dn5.toString());
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", CertTools.stringToBCDNString(dn3));

    String dn6 = "dc=tld,dc=domain,cn=titi,cn=toto";
    String revdn6 = CertTools.reverseDN(dn6);
    assertEquals("cn=toto,cn=titi,dc=domain,dc=tld", revdn6);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", CertTools.stringToBCDNString(dn3));

    X509Name dn7 = CertTools.stringToBcX509Name(dn6, new X509DefaultEntryConverter(), true);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", dn7.toString());
    X509Name revdn7 = CertTools.stringToBcX509Name(dn6, new X509DefaultEntryConverter(), false);
    assertEquals("DC=tld,DC=domain,CN=titi,CN=toto", revdn7.toString());

    // Test the test strings from ECA-1699, to prove that we fixed this issue
    String dn8 = "dc=org,dc=foo,o=FOO,cn=FOO Root CA";
    String dn9 = "cn=FOO Root CA,o=FOO,dc=foo,dc=org";
    String revdn8 = CertTools.reverseDN(dn8);
    assertEquals("cn=FOO Root CA,o=FOO,dc=foo,dc=org", revdn8);
    String revdn9 = CertTools.reverseDN(dn9);
    assertEquals("dc=org,dc=foo,o=FOO,cn=FOO Root CA", revdn9);
    X509Name xdn8ldap = CertTools.stringToBcX509Name(dn8, new X509DefaultEntryConverter(), true);
    X509Name xdn8x500 = CertTools.stringToBcX509Name(dn8, new X509DefaultEntryConverter(), false);
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", xdn8ldap.toString());
    assertEquals("DC=org,DC=foo,O=FOO,CN=FOO Root CA", xdn8x500.toString());
    X509Name xdn9ldap = CertTools.stringToBcX509Name(dn9, new X509DefaultEntryConverter(), true);
    X509Name xdn9x500 = CertTools.stringToBcX509Name(dn9, new X509DefaultEntryConverter(), false);
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", xdn9ldap.toString());
    assertEquals("DC=org,DC=foo,O=FOO,CN=FOO Root CA", xdn9x500.toString());
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", CertTools.stringToBCDNString(dn8));
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", CertTools.stringToBCDNString(dn9));

    // Test reversing DNs with multiple OU
    String dn10 = "CN=something,OU=A,OU=B,O=someO,C=SE";
    X509Name x509dn10 = CertTools.stringToBcX509Name(dn10, new X509DefaultEntryConverter(), true);
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", x509dn10.toString());
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", CertTools.stringToBCDNString(dn10));

    // When we order forwards (LdapOrder) from the beginning, and request !LdapOrder, everything should be reversed
    X509Name ldapdn11 = CertTools.stringToBcX509Name(dn10, new X509DefaultEntryConverter(), false);
    assertEquals("C=SE,O=someO,OU=B,OU=A,CN=something", ldapdn11.toString());

    // When we order backwards (X.509, !LdapOrder) from the beginning, we should not reorder anything
    String dn11 = "C=SE,O=someO,OU=B,OU=A,CN=something";
    X509Name x509dn11 = CertTools.stringToBcX509Name(dn11, new X509DefaultEntryConverter(), false);
    assertEquals("C=SE,O=someO,OU=B,OU=A,CN=something", x509dn11.toString());
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", CertTools.stringToBCDNString(dn11));

    log.trace("<test09TestReverse()");
}

From source file:org.glite.slcs.pki.bouncycastle.X509PrincipalUtil.java

License:eu-egee.org license

/**
 * Builds a {@link X509Principal}, based on the given vectors.
 * /*from w w  w  .  j a v a 2 s  . c o m*/
 * @param ordering
 * @param values
 * @param added
 * @return the {@link X509Principal} or <code>null</code> if an error
 *         occurs.
 * @throws IOException
 *             if a DER encoding error occurs.
 */
private X509Principal buildX509Principal(Vector<DERObjectIdentifier> ordering, Vector<Object> values,
        Vector<Boolean> added) throws IOException {
    X509NameEntryConverter converter = new X509DefaultEntryConverter();
    ASN1EncodableVector vec = new ASN1EncodableVector();
    ASN1EncodableVector sVec = new ASN1EncodableVector();
    DERObjectIdentifier lstOid = null;
    // Bouncycastle's code
    for (int i = 0; i != ordering.size(); i++) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        DERObjectIdentifier oid = ordering.elementAt(i);
        v.add(oid);
        String str = (String) values.elementAt(i);
        v.add(converter.getConvertedValue(oid, str));
        if (lstOid == null || added.elementAt(i)) {
            sVec.add(new DERSequence(v));
        } else {
            vec.add(new DERSet(sVec));
            sVec = new ASN1EncodableVector();
            sVec.add(new DERSequence(v));
        }

        lstOid = oid;
    }
    vec.add(new DERSet(sVec));
    DERSequence seq = new DERSequence(vec);
    byte[] bytes = seq.getDEREncoded();
    return new X509Principal(bytes);
}

From source file:org.jruby.ext.openssl.X509Name.java

License:LGPL

private ASN1Primitive convert(ASN1ObjectIdentifier oid, String value, int type) {
    try {//from  www.  j  a  va2  s  .co m
        Class<? extends ASN1Encodable> clzz = ASN1.classForId(type);
        if (clzz != null) {
            java.lang.reflect.Constructor<?> ctor = clzz.getConstructor(new Class[] { String.class });
            if (null != ctor) {
                return (ASN1Primitive) ctor.newInstance(new Object[] { value });
            }
        }
        return new X509DefaultEntryConverter().getConvertedValue(oid, value);
    } catch (Exception e) {
        throw newX509NameError(getRuntime(), e.getMessage());
    }
}