Search in sources :

Example 26 with RDN

use of org.openecard.bouncycastle.asn1.x500.RDN in project xipki by xipki.

the class XmlX509Certprofile method initialize0.

// method initialize
private void initialize0(X509ProfileType conf) throws CertprofileException {
    if (conf.getVersion() != null) {
        String versionText = conf.getVersion();
        this.version = X509CertVersion.forName(versionText);
        if (this.version == null) {
            throw new CertprofileException(String.format("invalid version '%s'", versionText));
        }
    } else {
        this.version = X509CertVersion.v3;
    }
    if (conf.getSignatureAlgorithms() != null) {
        List<String> algoNames = conf.getSignatureAlgorithms().getAlgorithm();
        List<String> list = new ArrayList<>(algoNames.size());
        for (String algoName : algoNames) {
            try {
                list.add(AlgorithmUtil.canonicalizeSignatureAlgo(algoName));
            } catch (NoSuchAlgorithmException ex) {
                throw new CertprofileException(ex.getMessage(), ex);
            }
        }
        this.signatureAlgorithms = Collections.unmodifiableList(list);
    }
    this.raOnly = conf.isRaOnly();
    this.maxSize = conf.getMaxSize();
    this.validity = CertValidity.getInstance(conf.getValidity());
    String str = conf.getCertLevel();
    if ("RootCA".equalsIgnoreCase(str)) {
        this.certLevel = X509CertLevel.RootCA;
    } else if ("SubCA".equalsIgnoreCase(str)) {
        this.certLevel = X509CertLevel.SubCA;
    } else if ("EndEntity".equalsIgnoreCase(str)) {
        this.certLevel = X509CertLevel.EndEntity;
    } else {
        throw new CertprofileException("invalid CertLevel '" + str + "'");
    }
    str = conf.getNotBeforeTime();
    if ("midnight".equalsIgnoreCase(str)) {
        this.notBeforeMidnight = true;
    } else if ("current".equalsIgnoreCase(str)) {
        this.notBeforeMidnight = false;
    } else {
        throw new CertprofileException("invalid notBefore '" + str + "'");
    }
    String specBehavior = conf.getSpecialBehavior();
    if (specBehavior != null) {
        this.specialBehavior = SpecialX509CertprofileBehavior.forName(specBehavior);
    }
    this.duplicateKeyPermitted = conf.isDuplicateKey();
    this.serialNumberInReqPermitted = conf.isSerialNumberInReq();
    // KeyAlgorithms
    KeyAlgorithms keyAlgos = conf.getKeyAlgorithms();
    if (keyAlgos != null) {
        this.keyAlgorithms = XmlX509CertprofileUtil.buildKeyAlgorithms(keyAlgos);
    }
    // parameters
    Parameters confParams = conf.getParameters();
    if (confParams == null) {
        parameters = null;
    } else {
        Map<String, String> tmpMap = new HashMap<>();
        for (NameValueType nv : confParams.getParameter()) {
            tmpMap.put(nv.getName(), nv.getValue());
        }
        parameters = Collections.unmodifiableMap(tmpMap);
    }
    // Subject
    Subject subject = conf.getSubject();
    duplicateSubjectPermitted = subject.isDuplicateSubjectPermitted();
    List<RdnControl> subjectDnControls = new LinkedList<>();
    for (RdnType rdn : subject.getRdn()) {
        ASN1ObjectIdentifier type = new ASN1ObjectIdentifier(rdn.getType().getValue());
        List<Pattern> patterns = null;
        if (CollectionUtil.isNonEmpty(rdn.getRegex())) {
            patterns = new LinkedList<>();
            for (String regex : rdn.getRegex()) {
                Pattern pattern = Pattern.compile(regex);
                patterns.add(pattern);
            }
        }
        if (patterns == null) {
            Pattern pattern = SubjectDnSpec.getPattern(type);
            if (pattern != null) {
                patterns = Arrays.asList(pattern);
            }
        }
        Range range = (rdn.getMinLen() != null || rdn.getMaxLen() != null) ? new Range(rdn.getMinLen(), rdn.getMaxLen()) : null;
        RdnControl rdnControl = new RdnControl(type, rdn.getMinOccurs(), rdn.getMaxOccurs());
        subjectDnControls.add(rdnControl);
        StringType stringType = XmlX509CertprofileUtil.convertStringType(rdn.getStringType());
        rdnControl.setStringType(stringType);
        rdnControl.setStringLengthRange(range);
        rdnControl.setPatterns(patterns);
        rdnControl.setPrefix(rdn.getPrefix());
        rdnControl.setSuffix(rdn.getSuffix());
        rdnControl.setGroup(rdn.getGroup());
        SubjectDnSpec.fixRdnControl(rdnControl);
    }
    this.subjectControl = new SubjectControl(subjectDnControls, subject.isKeepRdnOrder());
    this.incSerialNoIfSubjectExists = subject.isIncSerialNumber();
    // Extensions
    ExtensionsType extensionsType = conf.getExtensions();
    // Extension controls
    this.extensionControls = XmlX509CertprofileUtil.buildExtensionControls(extensionsType);
    Set<ASN1ObjectIdentifier> extnIds = new HashSet<>(this.extensionControls.keySet());
    // SubjectToSubjectAltName
    initSubjectToSubjectAltNames(extensionsType);
    // AdditionalInformation
    initAdditionalInformation(extnIds, extensionsType);
    // Admission
    initAdmission(extnIds, extensionsType);
    // AuthorityInfoAccess
    initAuthorityInfoAccess(extnIds, extensionsType);
    // AuthorityKeyIdentifier
    initAuthorityKeyIdentifier(extnIds, extensionsType);
    // AuthorizationTemplate
    initAuthorizationTemplate(extnIds, extensionsType);
    // BasicConstrains
    initBasicConstraints(extnIds, extensionsType);
    // BiometricInfo
    initBiometricInfo(extnIds, extensionsType);
    // Certificate Policies
    initCertificatePolicies(extnIds, extensionsType);
    // ExtendedKeyUsage
    initExtendedKeyUsage(extnIds, extensionsType);
    // Inhibit anyPolicy
    initInhibitAnyPolicy(extnIds, extensionsType);
    // KeyUsage
    initKeyUsage(extnIds, extensionsType);
    // Name Constrains
    initNameConstraints(extnIds, extensionsType);
    // Policy Constraints
    initPolicyConstraints(extnIds, extensionsType);
    // Policy Mappings
    initPolicyMappings(extnIds, extensionsType);
    // PrivateKeyUsagePeriod
    initPrivateKeyUsagePeriod(extnIds, extensionsType);
    // QCStatements
    initQcStatements(extnIds, extensionsType);
    // Restriction
    initRestriction(extnIds, extensionsType);
    // SMIMECapatibilities
    initSmimeCapabilities(extnIds, extensionsType);
    // SubjectAltNameMode
    initSubjectAlternativeName(extnIds, extensionsType);
    // SubjectInfoAccess
    initSubjectInfoAccess(extnIds, extensionsType);
    // TlsFeature
    initTlsFeature(extnIds, extensionsType);
    // validityModel
    initValidityModel(extnIds, extensionsType);
    // SubjectDirectoryAttributes
    initSubjectDirAttrs(extnIds, extensionsType);
    // constant extensions
    this.constantExtensions = XmlX509CertprofileUtil.buildConstantExtesions(extensionsType);
    if (this.constantExtensions != null) {
        extnIds.removeAll(this.constantExtensions.keySet());
    }
    // validate the configuration
    if (subjectToSubjectAltNameModes != null) {
        ASN1ObjectIdentifier type = Extension.subjectAlternativeName;
        if (!extensionControls.containsKey(type)) {
            throw new CertprofileException("subjectToSubjectAltNames cannot be configured if extension" + " subjectAltNames is not permitted");
        }
        if (subjectAltNameModes != null) {
            for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
                GeneralNameTag nameTag = subjectToSubjectAltNameModes.get(attrType);
                boolean allowed = false;
                for (GeneralNameMode m : subjectAltNameModes) {
                    if (m.getTag() == nameTag) {
                        allowed = true;
                        break;
                    }
                }
                if (!allowed) {
                    throw new CertprofileException("target SubjectAltName type " + nameTag + " is not allowed");
                }
            }
        }
    }
    // Remove the extension processed not be the CertProfile, but by the CA
    extnIds.remove(Extension.issuerAlternativeName);
    extnIds.remove(Extension.authorityInfoAccess);
    extnIds.remove(Extension.cRLDistributionPoints);
    extnIds.remove(Extension.freshestCRL);
    extnIds.remove(Extension.subjectKeyIdentifier);
    extnIds.remove(Extension.subjectInfoAccess);
    extnIds.remove(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    Set<ASN1ObjectIdentifier> copyOfExtnIds = new HashSet<>(extnIds);
    for (ASN1ObjectIdentifier extnId : copyOfExtnIds) {
        Object extnValue = getExtensionValue(extnId, extensionsType, Object.class);
        boolean processed = initExtraExtension(extnId, extensionControls.get(extnId), extnValue);
        if (processed) {
            extnIds.remove(extnId);
        }
    }
    if (!extnIds.isEmpty()) {
        throw new CertprofileException("Cannot process the extensions: " + extnIds);
    }
}
Also used : NameValueType(org.xipki.ca.certprofile.x509.jaxb.NameValueType) HashMap(java.util.HashMap) DirectoryStringType(org.xipki.ca.api.profile.DirectoryStringType) StringType(org.xipki.ca.api.profile.StringType) ArrayList(java.util.ArrayList) KeyAlgorithms(org.xipki.ca.certprofile.x509.jaxb.X509ProfileType.KeyAlgorithms) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RdnControl(org.xipki.ca.api.profile.RdnControl) CertprofileException(org.xipki.ca.api.profile.CertprofileException) SubjectControl(org.xipki.ca.api.profile.x509.SubjectControl) ExtensionsType(org.xipki.ca.certprofile.x509.jaxb.ExtensionsType) HashSet(java.util.HashSet) Pattern(java.util.regex.Pattern) GeneralNameMode(org.xipki.ca.api.profile.GeneralNameMode) Parameters(org.xipki.ca.certprofile.x509.jaxb.X509ProfileType.Parameters) GeneralNameTag(org.xipki.ca.api.profile.GeneralNameTag) Range(org.xipki.ca.api.profile.Range) Subject(org.xipki.ca.certprofile.x509.jaxb.X509ProfileType.Subject) LinkedList(java.util.LinkedList) RdnType(org.xipki.ca.certprofile.x509.jaxb.RdnType) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 27 with RDN

use of org.openecard.bouncycastle.asn1.x500.RDN in project xipki by xipki.

the class XmlX509Certprofile method createRequestedSubjectAltNames.

private GeneralNames createRequestedSubjectAltNames(X500Name requestedSubject, X500Name grantedSubject, Extensions requestedExtensions) throws BadCertTemplateException {
    ASN1Encodable extValue = (requestedExtensions == null) ? null : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName);
    if (extValue == null && subjectToSubjectAltNameModes == null) {
        return null;
    }
    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]));
}
Also used : GeneralNameTag(org.xipki.ca.api.profile.GeneralNameTag) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) LinkedList(java.util.LinkedList) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 28 with RDN

use of org.openecard.bouncycastle.asn1.x500.RDN in project open-ecard by ecsec.

the class ListCertificates method getUniqueIdentifier.

private String getUniqueIdentifier(X509Certificate cert) {
    // try to get SERIALNUMBER from subject
    X500Name sub = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());
    RDN[] serials = sub.getRDNs(BCStyle.SERIALNUMBER);
    if (serials.length >= 1) {
        AttributeTypeAndValue serialValueType = serials[0].getFirst();
        ASN1Encodable serialValue = serialValueType.getValue();
        if (ASN1String.class.isInstance(serialValue)) {
            return ASN1String.class.cast(serialValue).getString();
        }
    }
    // no SERIALNUMBER, hash subject and cross fingers that this is unique across replacement cards
    try {
        SHA256Digest digest = new SHA256Digest();
        byte[] subData = sub.getEncoded();
        digest.update(subData, 0, subData.length);
        byte[] hashResult = new byte[digest.getDigestSize()];
        digest.doFinal(hashResult, 0);
        String hashedSub = ByteUtils.toWebSafeBase64String(hashResult);
        return hashedSub;
    } catch (IOException ex) {
        throw new RuntimeException("Failed to encode subject.", ex);
    }
}
Also used : SHA256Digest(org.openecard.bouncycastle.crypto.digests.SHA256Digest) X500Name(org.openecard.bouncycastle.asn1.x500.X500Name) ASN1Encodable(org.openecard.bouncycastle.asn1.ASN1Encodable) ASN1String(org.openecard.bouncycastle.asn1.ASN1String) ASN1String(org.openecard.bouncycastle.asn1.ASN1String) ASN1OctetString(org.openecard.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) RDN(org.openecard.bouncycastle.asn1.x500.RDN) AttributeTypeAndValue(org.openecard.bouncycastle.asn1.x500.AttributeTypeAndValue)

Example 29 with RDN

use of org.openecard.bouncycastle.asn1.x500.RDN in project credhub by cloudfoundry-incubator.

the class UserContext method parseAppIdentifier.

private String parseAppIdentifier(String subjectDn) {
    final X500Name dnName = new X500Name(subjectDn);
    final RDN[] rdNs = dnName.getRDNs(BCStyle.OU);
    return rdNs[0].getFirst().getValue().toString();
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN)

Example 30 with RDN

use of org.openecard.bouncycastle.asn1.x500.RDN in project jruby-openssl by jruby.

the class X509Extension method formatGeneralName.

@SuppressWarnings("unchecked")
private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) {
    final ASN1Encodable obj = name.getName();
    String val;
    boolean tagged = false;
    switch(name.getTagNo()) {
        case GeneralName.rfc822Name:
            if (!tagged)
                out.append('e').append('m').append('a').append('i').append('l').append(':');
            tagged = true;
        case GeneralName.dNSName:
            if (!tagged)
                out.append('D').append('N').append('S').append(':');
            tagged = true;
        case GeneralName.uniformResourceIdentifier:
            if (!tagged)
                out.append('U').append('R').append('I').append(':');
            val = DERIA5String.getInstance(obj).getString();
            out.append(ByteList.plain(val));
            break;
        case GeneralName.directoryName:
            out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':');
            final X500Name dirName = X500Name.getInstance(obj);
            if (slashed) {
                final RDN[] rdns = dirName.getRDNs();
                final Hashtable defaultSymbols = getDefaultSymbols();
                for (int i = 0; i < rdns.length; i++) {
                    appendRDN(out.append('/'), rdns[i], defaultSymbols);
                }
            } else {
                out.append(ByteList.plain(dirName.toString()));
            }
            break;
        case GeneralName.iPAddress:
            out.append('I').append('P').append(':');
            final byte[] ip = ((ASN1OctetString) name.getName()).getOctets();
            int len = ip.length;
            boolean ip4 = len == 4;
            if (ip4) {
                for (int i = 0; i < ip.length; i++) {
                    out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff));
                    if (i != len - 1)
                        out.append('.');
                }
            } else {
                for (int i = 0; i < ip.length; i += 2) {
                    out.append(ConvertBytes.intToHexBytes(((ip[i] & 0xff) << 8 | (ip[i + 1] & 0xff))));
                    if (i != len - 2)
                        out.append(':');
                }
            }
            break;
        case GeneralName.otherName:
            out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m').append('e').append(':');
            out.append(ByteList.plain(obj.toString()));
            return true;
        // tagged = true;
        case GeneralName.registeredID:
            out.append('R').append('I').append('D').append(':');
        // tagged = true;
        default:
            out.append(ByteList.plain(obj.toString()));
    }
    return false;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Hashtable(java.util.Hashtable) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) RubyString(org.jruby.RubyString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN)

Aggregations

RDN (org.bouncycastle.asn1.x500.RDN)55 X500Name (org.bouncycastle.asn1.x500.X500Name)33 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)18 ArrayList (java.util.ArrayList)15 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)15 X509Certificate (java.security.cert.X509Certificate)13 DERIA5String (org.bouncycastle.asn1.DERIA5String)13 AttributeTypeAndValue (org.bouncycastle.asn1.x500.AttributeTypeAndValue)13 IOException (java.io.IOException)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)12 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)12 LinkedList (java.util.LinkedList)10 DEROctetString (org.bouncycastle.asn1.DEROctetString)10 JcaX509CertificateHolder (org.bouncycastle.cert.jcajce.JcaX509CertificateHolder)10 KeyStoreException (java.security.KeyStoreException)8 List (java.util.List)8 InputStream (java.io.InputStream)7 KeyStore (java.security.KeyStore)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 CertificateException (java.security.cert.CertificateException)7