Search in sources :

Example 76 with X500Name

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

the class BaseX509Certprofile method getSubject.

@Override
public SubjectInfo getSubject(X500Name requestedSubject) throws CertprofileException, BadCertTemplateException {
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    verifySubjectDnOccurence(requestedSubject);
    RDN[] requstedRdns = requestedSubject.getRDNs();
    SubjectControl scontrol = getSubjectControl();
    List<RDN> rdns = new LinkedList<>();
    for (ASN1ObjectIdentifier type : scontrol.getTypes()) {
        RdnControl control = scontrol.getControl(type);
        if (control == null) {
            continue;
        }
        RDN[] thisRdns = getRdns(requstedRdns, type);
        if (thisRdns == null) {
            continue;
        }
        int len = thisRdns.length;
        if (len == 0) {
            continue;
        }
        if (ObjectIdentifiers.DN_EmailAddress.equals(type)) {
            throw new BadCertTemplateException("emailAddress is not allowed");
        }
        if (len == 1) {
            ASN1Encodable rdnValue = thisRdns[0].getFirst().getValue();
            RDN rdn;
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                rdn = createDateOfBirthRdn(type, rdnValue);
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                rdn = createPostalAddressRdn(type, rdnValue, control, 0);
            } else {
                String value = X509Util.rdnValueToString(rdnValue);
                rdn = createSubjectRdn(value, type, control, 0);
            }
            if (rdn != null) {
                rdns.add(rdn);
            }
        } else {
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createDateOfBirthRdn(type, thisRdns[i].getFirst().getValue());
                    rdns.add(rdn);
                }
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createPostalAddressRdn(type, thisRdns[i].getFirst().getValue(), control, i);
                    rdns.add(rdn);
                }
            } else {
                String[] values = new String[len];
                for (int i = 0; i < len; i++) {
                    values[i] = X509Util.rdnValueToString(thisRdns[i].getFirst().getValue());
                }
                values = sortRdns(control, values);
                int idx = 0;
                for (String value : values) {
                    rdns.add(createSubjectRdn(value, type, control, idx++));
                }
            }
        // if
        }
    // if
    }
    // for
    Set<String> subjectDnGroups = scontrol.getGroups();
    if (CollectionUtil.isNonEmpty(subjectDnGroups)) {
        Set<String> consideredGroups = new HashSet<>();
        final int n = rdns.size();
        List<RDN> newRdns = new ArrayList<>(rdns.size());
        for (int i = 0; i < n; i++) {
            RDN rdn = rdns.get(i);
            ASN1ObjectIdentifier type = rdn.getFirst().getType();
            String group = scontrol.getGroup(type);
            if (group == null) {
                newRdns.add(rdn);
            } else if (!consideredGroups.contains(group)) {
                List<AttributeTypeAndValue> atvs = new LinkedList<>();
                atvs.add(rdn.getFirst());
                for (int j = i + 1; j < n; j++) {
                    RDN rdn2 = rdns.get(j);
                    ASN1ObjectIdentifier type2 = rdn2.getFirst().getType();
                    String group2 = scontrol.getGroup(type2);
                    if (group.equals(group2)) {
                        atvs.add(rdn2.getFirst());
                    }
                }
                newRdns.add(new RDN(atvs.toArray(new AttributeTypeAndValue[0])));
                consideredGroups.add(group);
            }
        }
        // for
        rdns = newRdns;
    }
    // if
    X500Name grantedSubject = new X500Name(rdns.toArray(new RDN[0]));
    return new SubjectInfo(grantedSubject, null);
}
Also used : ArrayList(java.util.ArrayList) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) X500Name(org.bouncycastle.asn1.x500.X500Name) LinkedList(java.util.LinkedList) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) RdnControl(org.xipki.ca.api.profile.RdnControl) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) HashSet(java.util.HashSet)

Example 77 with X500Name

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

the class X509Util method canonicalizName.

public static String canonicalizName(X500Name name) {
    ParamUtil.requireNonNull("name", name);
    ASN1ObjectIdentifier[] tmpTypes = name.getAttributeTypes();
    int len = tmpTypes.length;
    List<String> types = new ArrayList<>(len);
    for (ASN1ObjectIdentifier type : tmpTypes) {
        types.add(type.getId());
    }
    Collections.sort(types);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        String type = types.get(i);
        if (i > 0) {
            sb.append(",");
        }
        sb.append(type).append("=");
        RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier(type));
        List<String> values = new ArrayList<>(1);
        for (int j = 0; j < rdns.length; j++) {
            RDN rdn = rdns[j];
            if (rdn.isMultiValued()) {
                AttributeTypeAndValue[] atvs = rdn.getTypesAndValues();
                for (AttributeTypeAndValue atv : atvs) {
                    if (type.equals(atv.getType().getId())) {
                        String textValue = IETFUtils.valueToString(atv.getValue()).toLowerCase();
                        values.add(textValue);
                    }
                }
            } else {
                String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()).toLowerCase();
                values.add(textValue);
            }
        }
        // end for(j)
        sb.append(values.get(0));
        final int n2 = values.size();
        if (n2 > 1) {
            for (int j = 1; j < n2; j++) {
                sb.append(";").append(values.get(j));
            }
        }
    }
    return sb.toString();
}
Also used : ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue)

Example 78 with X500Name

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

the class X509Util method createGeneralName.

/**
 * Creates {@link GeneralName} from the tagged value.
 * @param taggedValue [tag]value, and the value for tags otherName and ediPartyName is
 *     type=value.
 * @return the created {@link GeneralName}
 * @throws BadInputException
 *         if the {@code taggedValue} is invalid.
 */
public static GeneralName createGeneralName(String taggedValue) throws BadInputException {
    ParamUtil.requireNonBlank("taggedValue", taggedValue);
    int tag = -1;
    String value = null;
    if (taggedValue.charAt(0) == '[') {
        int idx = taggedValue.indexOf(']', 1);
        if (idx > 1 && idx < taggedValue.length() - 1) {
            String tagS = taggedValue.substring(1, idx);
            try {
                tag = Integer.parseInt(tagS);
                value = taggedValue.substring(idx + 1);
            } catch (NumberFormatException ex) {
                throw new BadInputException("invalid tag '" + tagS + "'");
            }
        }
    }
    if (tag == -1) {
        throw new BadInputException("invalid taggedValue " + taggedValue);
    }
    switch(tag) {
        case GeneralName.otherName:
            if (value == null) {
                throw new BadInputException("invalid otherName: no value specified");
            }
            int idxSep = value.indexOf("=");
            if (idxSep == -1 || idxSep == 0 || idxSep == value.length() - 1) {
                throw new BadInputException("invalid otherName " + value);
            }
            String otherTypeOid = value.substring(0, idxSep);
            ASN1ObjectIdentifier type = new ASN1ObjectIdentifier(otherTypeOid);
            String otherValue = value.substring(idxSep + 1);
            ASN1EncodableVector vector = new ASN1EncodableVector();
            vector.add(type);
            vector.add(new DERTaggedObject(true, 0, new DERUTF8String(otherValue)));
            DERSequence seq = new DERSequence(vector);
            return new GeneralName(GeneralName.otherName, seq);
        case GeneralName.rfc822Name:
            return new GeneralName(tag, value);
        case GeneralName.dNSName:
            return new GeneralName(tag, value);
        case GeneralName.directoryName:
            X500Name x500Name = reverse(new X500Name(value));
            return new GeneralName(GeneralName.directoryName, x500Name);
        case GeneralName.ediPartyName:
            if (value == null) {
                throw new BadInputException("invalid ediPartyName: no value specified");
            }
            idxSep = value.indexOf("=");
            if (idxSep == -1 || idxSep == value.length() - 1) {
                throw new BadInputException("invalid ediPartyName " + value);
            }
            String nameAssigner = (idxSep == 0) ? null : value.substring(0, idxSep);
            String partyName = value.substring(idxSep + 1);
            vector = new ASN1EncodableVector();
            if (nameAssigner != null) {
                vector.add(new DERTaggedObject(false, 0, new DirectoryString(nameAssigner)));
            }
            vector.add(new DERTaggedObject(false, 1, new DirectoryString(partyName)));
            seq = new DERSequence(vector);
            return new GeneralName(GeneralName.ediPartyName, seq);
        case GeneralName.uniformResourceIdentifier:
            return new GeneralName(tag, value);
        case GeneralName.iPAddress:
            return new GeneralName(tag, value);
        case GeneralName.registeredID:
            return new GeneralName(tag, value);
        default:
            throw new RuntimeException("unsupported tag " + tag);
    }
// end switch (tag)
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) X500Name(org.bouncycastle.asn1.x500.X500Name) BadInputException(org.xipki.security.exception.BadInputException) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) GeneralName(org.bouncycastle.asn1.x509.GeneralName) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 79 with X500Name

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

the class ScepClientExample method main.

public static void main(String[] args) {
    try {
        X509Certificate caCert = ScepUtil.parseCert(ScepUtil.read(new FileInputStream(expandPath(CA_CERT_FILE))));
        CaIdentifier tmpCaId = new CaIdentifier(CA_URL, null);
        CaCertValidator caCertValidator = new PreprovisionedCaCertValidator(caCert);
        ScepClient client = new ScepClient(tmpCaId, caCertValidator);
        client.init();
        // Self-Signed Identity Certificate
        MyKeypair keypair = generateRsaKeypair();
        CertificationRequest csr = genCsr(keypair, getSubject(), challengePassword);
        // self-signed cert must use the same subject as in CSR
        X500Name subjectDn = csr.getCertificationRequestInfo().getSubject();
        X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.valueOf(1), new Date(), new Date(System.currentTimeMillis() + 24 * 3600 * 1000), subjectDn, keypair.getPublic());
        ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
        X509Certificate selfSignedCert = ScepUtil.parseCert(certGenerator.build(signer).getEncoded());
        // Enroll certificate - RSA
        EnrolmentResponse resp = (EnrolmentResponse) client.scepEnrol(csr, keypair.getPrivate(), selfSignedCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        X509Certificate cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, Self-Signed Identity Cert)", cert);
        // Use the CA signed identity certificate
        X509Certificate identityCert = cert;
        PrivateKey identityKey = keypair.getPrivate();
        keypair = generateRsaKeypair();
        csr = genCsr(keypair, getSubject(), challengePassword);
        // Enroll certificate - RSA
        resp = (EnrolmentResponse) client.scepEnrol(csr, identityKey, identityCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, CA issued identity Cert)", cert);
        client.destroy();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CaIdentifier(org.xipki.scep.client.CaIdentifier) ContentSigner(org.bouncycastle.operator.ContentSigner) ScepClient(org.xipki.scep.client.ScepClient) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) Date(java.util.Date) CaCertValidator(org.xipki.scep.client.CaCertValidator) PreprovisionedCaCertValidator(org.xipki.scep.client.PreprovisionedCaCertValidator) PreprovisionedCaCertValidator(org.xipki.scep.client.PreprovisionedCaCertValidator) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) EnrolmentResponse(org.xipki.scep.client.EnrolmentResponse) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 80 with X500Name

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

the class CaClientExample method genCsr.

protected static CertificationRequest genCsr(MyKeypair keypair, String subject, String challengePassword) throws GeneralSecurityException, OperatorCreationException {
    X500Name subjectDn = new X500Name(subject);
    PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, keypair.publicKeyInfo);
    if (challengePassword != null && !challengePassword.isEmpty()) {
        csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
    }
    ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
    return csrBuilder.build(signer).toASN1Structure();
}
Also used : DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)193 X509Certificate (java.security.cert.X509Certificate)88 Date (java.util.Date)71 BigInteger (java.math.BigInteger)63 X500Name (sun.security.x509.X500Name)53 IOException (java.io.IOException)49 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)47 ContentSigner (org.bouncycastle.operator.ContentSigner)45 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)44 RDN (org.bouncycastle.asn1.x500.RDN)43 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)42 KeyPair (java.security.KeyPair)41 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)41 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)36 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)33 PrivateKey (java.security.PrivateKey)32 KeyPairGenerator (java.security.KeyPairGenerator)31 GeneralName (org.bouncycastle.asn1.x509.GeneralName)31 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)28 SecureRandom (java.security.SecureRandom)27