Example usage for org.bouncycastle.asn1 ASN1EncodableVector size

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector size

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1EncodableVector size.

Prototype

public int size() 

Source Link

Document

Return the size of the vector.

Usage

From source file:org.cesecore.certificates.certificate.certextensions.standard.CertificatePolicies.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) throws CertificateExtensionException {
    DERSequence ret = null;//from  w w w  . j a  v  a2 s . c o  m
    // The UserNotice policy qualifier can have two different character encodings,
    // the correct one (UTF8) or the wrong one (BMP) used by IE < 7.
    final X509CA x509ca = (X509CA) ca;
    int displayencoding = DisplayText.CONTENT_TYPE_BMPSTRING;
    if (x509ca.getUseUTF8PolicyText()) {
        displayencoding = DisplayText.CONTENT_TYPE_UTF8STRING;
    }
    // Iterate through policies and add oids and policy qualifiers if they exist
    final List<CertificatePolicy> policies = certProfile.getCertificatePolicies();
    final Map<ASN1ObjectIdentifier, ASN1EncodableVector> policiesMap = new HashMap<ASN1ObjectIdentifier, ASN1EncodableVector>();
    // Each Policy OID can be entered several times, with different qualifiers, 
    // because of this we make a map of oid and qualifiers, and we can add a new qualifier
    // in each round of this for loop
    for (final Iterator<CertificatePolicy> it = policies.iterator(); it.hasNext();) {
        final CertificatePolicy policy = it.next();
        final ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(policy.getPolicyID());
        final ASN1EncodableVector qualifiers;
        if (policiesMap.containsKey(oid)) {
            qualifiers = policiesMap.get(oid);
        } else {
            qualifiers = new ASN1EncodableVector();
        }
        final PolicyQualifierInfo pqi = getPolicyQualifierInformation(policy, displayencoding);
        if (pqi != null) {
            qualifiers.add(pqi);
        }
        policiesMap.put(oid, qualifiers);
    }
    final ASN1EncodableVector seq = new ASN1EncodableVector();
    for (final Iterator<ASN1ObjectIdentifier> it = policiesMap.keySet().iterator(); it.hasNext();) {
        final ASN1ObjectIdentifier oid = it.next();
        final ASN1EncodableVector qualifiers = policiesMap.get(oid);
        if (qualifiers.size() == 0) {
            seq.add(new PolicyInformation(oid, null));
        } else {
            seq.add(new PolicyInformation(oid, new DERSequence(qualifiers)));
        }
    }
    if (seq.size() > 0) {
        ret = new DERSequence(seq);
    }
    if (ret == null) {
        log.error("Certificate policies missconfigured, no policies present!");
    }
    return ret;
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.PrivateKeyUsagePeriod.java

License:Open Source License

private static DERSequence privateKeyUsagePeriod(final Date notBefore, final Date notAfter)
        throws CertificateExtensionException {
    // Create the extension.
    // PrivateKeyUsagePeriod ::= SEQUENCE {
    // notBefore [0] GeneralizedTime OPTIONAL,
    // notAfter [1] GeneralizedTime OPTIONAL }
    final ASN1EncodableVector v = new ASN1EncodableVector();
    if (notBefore != null) {
        v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore)));
    }/* ww  w .  ja  v  a2  s .  c o m*/
    if (notAfter != null) {
        v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(notAfter)));
    }
    if (v.size() == 0) {
        throw new CertificateExtensionException("At least one of notBefore and notAfter must be specified!");
    }
    return new DERSequence(v);
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.SubjectDirectoryAttributes.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) {
    ASN1Encodable ret = null;//  w w  w. j  a v  a  2 s .c om
    final String dirAttrString = subject.getExtendedinformation() != null
            ? subject.getExtendedinformation().getSubjectDirectoryAttributes()
            : null;
    if (StringUtils.isNotEmpty(dirAttrString)) {
        // Subject Directory Attributes is a sequence of Attribute
        final Collection<Attribute> attr = SubjectDirAttrExtension.getSubjectDirectoryAttributes(dirAttrString);
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        final Iterator<Attribute> iter = attr.iterator();
        while (iter.hasNext()) {
            vec.add(iter.next());
        }
        if (vec.size() > 0) {
            ret = new DERSequence(vec);
        }
    }
    if (ret == null) {
        if (log.isDebugEnabled()) {
            log.debug("No directory attributes trying to create SubjectDirectoryAttributes extension: "
                    + dirAttrString);
        }
    }
    return ret;
}

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

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName
 * /*from  w w  w . j  a  v a 2  s .  c  o  m*/
 * @param altName
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(final String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    final ASN1EncodableVector vec = new ASN1EncodableVector();

    for (final String email : CertTools.getEmailFromDN(altName)) {
        vec.add(new GeneralName(1, /*new DERIA5String(iter.next())*/email));
    }

    for (final String dns : CertTools.getPartsFromDN(altName, CertTools.DNS)) {
        vec.add(new GeneralName(2, new DERIA5String(dns)));
    }

    final String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        //final X500Name x500DirectoryName = new X500Name(directoryName);
        final X500Name x500DirectoryName = new X500Name(LDAPDN.unescapeRDN(directoryName));
        final GeneralName gn = new GeneralName(4, x500DirectoryName);
        vec.add(gn);
    }

    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }
    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI1)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }
    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI2)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }

    for (final String addr : CertTools.getPartsFromDN(altName, CertTools.IPADDR)) {
        final byte[] ipoctets = StringTools.ipStringToOctets(addr);
        if (ipoctets.length > 0) {
            final GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        } else {
            log.error("Cannot parse/encode ip address, ignoring: " + addr);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    for (final String upn : CertTools.getPartsFromDN(altName, CertTools.UPN)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID));
        v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn)));
        vec.add(GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))));
    }

    // PermanentIdentifier is an OtherName see method getPermananentIdentifier... for asn.1 definition
    for (final String permanentIdentifier : CertTools.getPartsFromDN(altName, CertTools.PERMANENTIDENTIFIER)) {
        final String[] values = getPermanentIdentifierValues(permanentIdentifier);
        final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
        v.add(new ASN1ObjectIdentifier(CertTools.PERMANENTIDENTIFIER_OBJECTID));
        // First the PermanentIdentifier sequence
        final ASN1EncodableVector piSeq = new ASN1EncodableVector();
        if (values[0] != null) {
            piSeq.add(new DERUTF8String(values[0]));
        }
        if (values[1] != null) {
            piSeq.add(new ASN1ObjectIdentifier(values[1]));
        }
        v.add(new DERTaggedObject(true, 0, new DERSequence(piSeq)));
        // GeneralName gn = new GeneralName(new DERSequence(v), 0);
        final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
        vec.add(gn);
    }

    for (final String guid : CertTools.getPartsFromDN(altName, CertTools.GUID)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        byte[] guidbytes = Hex.decode(guid);
        if (guidbytes != null) {
            v.add(new ASN1ObjectIdentifier(CertTools.GUID_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
            final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        } else {
            log.error("Cannot decode hexadecimal guid, ignoring: " + guid);
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    for (final String principalString : CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL)) {
        // Start by parsing the input string to separate it in different parts
        if (log.isDebugEnabled()) {
            log.debug("principalString: " + principalString);
        }
        // The realm is the last part moving back until an @
        final int index = principalString.lastIndexOf('@');
        String realm = "";
        if (index > 0) {
            realm = principalString.substring(index + 1);
        }
        if (log.isDebugEnabled()) {
            log.debug("realm: " + realm);
        }
        // Now we can have several principals separated by /
        final ArrayList<String> principalarr = new ArrayList<String>();
        int jndex = 0;
        int bindex = 0;
        while (jndex < index) {
            // Loop and add all strings separated by /
            jndex = principalString.indexOf('/', bindex);
            if (jndex == -1) {
                jndex = index;
            }
            String s = principalString.substring(bindex, jndex);
            if (log.isDebugEnabled()) {
                log.debug("adding principal name: " + s);
            }
            principalarr.add(s);
            bindex = jndex + 1;
        }

        // Now we must construct the rather complex asn.1...
        final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
        v.add(new ASN1ObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

        // First the Krb5PrincipalName sequence
        final ASN1EncodableVector krb5p = new ASN1EncodableVector();
        // The realm is the first tagged GeneralString
        krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
        // Second is the sequence of principal names, which is at tagged position 1 in the krb5p
        final ASN1EncodableVector principals = new ASN1EncodableVector();
        // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
        principals.add(new DERTaggedObject(true, 0, new ASN1Integer(0)));
        // The names themselves are yet another sequence
        final Iterator<String> i = principalarr.iterator();
        final ASN1EncodableVector names = new ASN1EncodableVector();
        while (i.hasNext()) {
            String principalName = (String) i.next();
            names.add(new DERGeneralString(principalName));
        }
        principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
        krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

        v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
        final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
        vec.add(gn);
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    for (final String oid : CertTools.getCustomOids(altName)) {
        for (final String oidValue : CertTools.getPartsFromDN(altName, oid)) {
            final ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(oid));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String(oidValue)));
            final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    if (vec.size() > 0) {
        return GeneralNames.getInstance(new DERSequence(vec));
    }
    return null;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.AuthorityInformationAccess.java

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    GeneralName accessLocation;//w  w  w.j a  v  a 2  s  .  c  o  m
    String url;

    // caIssuers
    final List<String> caIssuers = certProfile.getCaIssuers();
    if (caIssuers != null) {
        for (final Iterator<String> it = caIssuers.iterator(); it.hasNext();) {
            url = it.next();
            if (StringUtils.isNotEmpty(url)) {
                accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }

    // ocsp url
    final X509CA x509ca = (X509CA) ca;
    url = certProfile.getOCSPServiceLocatorURI();
    if (certProfile.getUseDefaultOCSPServiceLocator()) {
        url = x509ca.getDefaultOCSPServiceLocator();
    }
    if (StringUtils.isNotEmpty(url)) {
        accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url));
        accessList.add(new AccessDescription(AccessDescription.id_ad_ocsp, accessLocation));
    }
    org.bouncycastle.asn1.x509.AuthorityInformationAccess ret = null;
    if (accessList.size() > 0) {
        ret = new org.bouncycastle.asn1.x509.AuthorityInformationAccess(new DERSequence(accessList));
    }
    if (ret == null) {
        log.error("AuthorityInformationAccess is used, but nor caIssuers not Ocsp url are defined!");
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.CertificatePolicies.java

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    DERSequence ret = null;//from  ww  w . j a v  a  2s.c o m
    // The UserNotice policy qualifier can have two different character encodings,
    // the correct one (UTF8) or the wrong one (BMP) used by IE < 7.
    final X509CA x509ca = (X509CA) ca;
    int displayencoding = DisplayText.CONTENT_TYPE_BMPSTRING;
    if (x509ca.getUseUTF8PolicyText()) {
        displayencoding = DisplayText.CONTENT_TYPE_UTF8STRING;
    }
    // Iterate through policies and add oids and policy qualifiers if they exist
    final List policies = certProfile.getCertificatePolicies();
    final Map policiesMap = new HashMap(); //<DERObjectIdentifier, ASN1EncodableVector>
    // Each Policy OID can be entered several times, with different qualifiers, 
    // because of this we make a map of oid and qualifiers, and we can add a new qualifier
    // in each round of this for loop
    for (final Iterator it = policies.iterator(); it.hasNext();) {
        final CertificatePolicy policy = (CertificatePolicy) it.next();
        final DERObjectIdentifier oid = new DERObjectIdentifier(policy.getPolicyID());
        final ASN1EncodableVector qualifiers;
        if (policiesMap.containsKey(oid)) {
            qualifiers = (ASN1EncodableVector) policiesMap.get(oid);
        } else {
            qualifiers = new ASN1EncodableVector();
        }
        final PolicyQualifierInfo pqi = getPolicyQualifierInformation(policy, displayencoding);
        if (pqi != null) {
            qualifiers.add(pqi);
        }
        policiesMap.put(oid, qualifiers);
    }
    final ASN1EncodableVector seq = new ASN1EncodableVector();
    for (final Iterator it = policiesMap.keySet().iterator(); it.hasNext();) {
        final DERObjectIdentifier oid = (DERObjectIdentifier) it.next();
        final ASN1EncodableVector qualifiers = (ASN1EncodableVector) policiesMap.get(oid);
        if (qualifiers.size() == 0) {
            seq.add(new PolicyInformation(oid, null));
        } else {
            seq.add(new PolicyInformation(oid, new DERSequence(qualifiers)));
        }
    }
    if (seq.size() > 0) {
        ret = new DERSequence(seq);
    }
    if (ret == null) {
        log.error("Certificate policies missconfigured, no policies present!");
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.PrivateKeyUsagePeriod.java

License:Open Source License

private static DERSequence privateKeyUsagePeriod(final Date notBefore, final Date notAfter)
        throws CertificateExtentionConfigurationException {
    // Create the extension.
    // PrivateKeyUsagePeriod ::= SEQUENCE {
    //   notBefore       [0]     GeneralizedTime OPTIONAL,
    //   notAfter        [1]     GeneralizedTime OPTIONAL }
    final ASN1EncodableVector v = new ASN1EncodableVector();
    if (notBefore != null) {
        v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore)));
    }/*from   www  .ja va2  s.  c  o  m*/
    if (notAfter != null) {
        v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(notAfter)));
    }
    if (v.size() == 0) {
        throw new CertificateExtentionConfigurationException(
                "At least one of notBefore and notAfter must be specified!");
    }
    return new DERSequence(v);
}

From source file:org.ejbca.core.model.ca.certextensions.standard.SubjectDirectoryAttributes.java

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    DEREncodable ret = null;// ww w  .j a  v  a 2s.  c  o m
    final String dirAttrString = subject.getExtendedinformation() != null
            ? subject.getExtendedinformation().getSubjectDirectoryAttributes()
            : null;
    if (StringUtils.isNotEmpty(dirAttrString)) {
        // Subject Directory Attributes is a sequence of Attribute
        final Collection<Attribute> attr = SubjectDirAttrExtension.getSubjectDirectoryAttributes(dirAttrString);
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        final Iterator<Attribute> iter = attr.iterator();
        while (iter.hasNext()) {
            vec.add(iter.next());
        }
        if (vec.size() > 0) {
            ret = new DERSequence(vec);
        }
    }
    if (ret == null) {
        log.debug("No directory attributes trying to create SubjectDirectoryAttributes extension: "
                + dirAttrString);
    }
    return ret;
}

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

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName 
 * @param altName//www .  j av  a  2 s  . com
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    ASN1EncodableVector vec = new ASN1EncodableVector();

    ArrayList<String> emails = CertTools.getEmailFromDN(altName);
    if (!emails.isEmpty()) {
        Iterator<String> iter = emails.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(1, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> dns = CertTools.getPartsFromDN(altName, CertTools.DNS);
    if (!dns.isEmpty()) {
        Iterator<String> iter = dns.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(2, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        X509Name x509DirectoryName = new X509Name(directoryName);
        GeneralName gn = new GeneralName(4, x509DirectoryName);
        vec.add(gn);
    }

    ArrayList<String> uri = CertTools.getPartsFromDN(altName, CertTools.URI);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI1);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI2);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> ipstr = CertTools.getPartsFromDN(altName, CertTools.IPADDR);
    if (!ipstr.isEmpty()) {
        Iterator<String> iter = ipstr.iterator();
        while (iter.hasNext()) {
            byte[] ipoctets = StringTools.ipStringToOctets((String) iter.next());
            GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    ArrayList<String> upn = CertTools.getPartsFromDN(altName, CertTools.UPN);
    if (!upn.isEmpty()) {
        Iterator<String> iter = upn.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) iter.next())));
            //GeneralName gn = new GeneralName(new DERSequence(v), 0);
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    ArrayList<String> guid = CertTools.getPartsFromDN(altName, CertTools.GUID);
    if (!guid.isEmpty()) {
        Iterator<String> iter = guid.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            byte[] guidbytes = Hex.decode((String) iter.next());
            if (guidbytes != null) {
                v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID));
                v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                vec.add(gn);
            } else {
                log.error("Cannot decode hexadecimal guid: " + guid);
            }
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    ArrayList<String> krb5principalname = CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL);
    if (!krb5principalname.isEmpty()) {
        Iterator<String> iter = krb5principalname.iterator();
        while (iter.hasNext()) {
            // Start by parsing the input string to separate it in different parts
            String principalString = (String) iter.next();
            if (log.isDebugEnabled()) {
                log.debug("principalString: " + principalString);
            }
            // The realm is the last part moving back until an @
            int index = principalString.lastIndexOf('@');
            String realm = "";
            if (index > 0) {
                realm = principalString.substring(index + 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("realm: " + realm);
            }
            // Now we can have several principals separated by /
            ArrayList<String> principalarr = new ArrayList<String>();
            int jndex = 0;
            int bindex = 0;
            while (jndex < index) {
                // Loop and add all strings separated by /
                jndex = principalString.indexOf('/', bindex);
                if (jndex == -1) {
                    jndex = index;
                }
                String s = principalString.substring(bindex, jndex);
                if (log.isDebugEnabled()) {
                    log.debug("adding principal name: " + s);
                }
                principalarr.add(s);
                bindex = jndex + 1;
            }

            // Now we must construct the rather complex asn.1...
            ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
            v.add(new DERObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

            // First the Krb5PrincipalName sequence
            ASN1EncodableVector krb5p = new ASN1EncodableVector();
            // The realm is the first tagged GeneralString
            krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
            // Second is the sequence of principal names, which is at tagged position 1 in the krb5p 
            ASN1EncodableVector principals = new ASN1EncodableVector();
            // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
            principals.add(new DERTaggedObject(true, 0, new DERInteger(0)));
            // The names themselves are yet another sequence
            Iterator<String> i = principalarr.iterator();
            ASN1EncodableVector names = new ASN1EncodableVector();
            while (i.hasNext()) {
                String principalName = (String) i.next();
                names.add(new DERGeneralString(principalName));
            }
            principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
            krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

            v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    ArrayList<String> customoids = CertTools.getCustomOids(altName);
    if (!customoids.isEmpty()) {
        Iterator<String> iter = customoids.iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            ArrayList<String> oidval = CertTools.getPartsFromDN(altName, oid);
            if (!oidval.isEmpty()) {
                Iterator<String> valiter = oidval.iterator();
                while (valiter.hasNext()) {
                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(new DERObjectIdentifier(oid));
                    v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) valiter.next())));
                    DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                    vec.add(gn);
                }
            }
        }
    }

    GeneralNames ret = null;
    if (vec.size() > 0) {
        ret = new GeneralNames(new DERSequence(vec));
    }
    return ret;
}

From source file:org.signserver.module.tsa.TimeStampSignerTest.java

License:Open Source License

private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception {
    int reqid = random.nextInt();
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo,
            new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100));

    byte[] requestBytes = timeStampRequest.getEncoded();

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

    final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER1, signRequest,
            new RequestContext());

    final CertificateFactory factory = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes())));

    TimeStampResponse timeStampResponse = null;
    try {/*from  ww w  . j  ava2s  .  c o  m*/
        // check response
        timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
        timeStampResponse.validate(timeStampRequest);

        if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
            // return early and don't attempt to get a token
            return timeStampResponse.getStatus();
        }

        // check the hash value from the response
        TimeStampToken token = timeStampResponse.getTimeStampToken();
        AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm();
        assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm());

        Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners();

        // there should be one SignerInfo
        assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size());

        for (Object o : signerInfos) {
            SignerInformation si = (SignerInformation) o;

            // test the response signature algorithm
            assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(),
                    si.getDigestAlgOID());
            assertEquals("Timestamp is signed with unexpected signature encryption algorithm",
                    "1.2.840.113549.1.1.1", si.getEncryptionAlgOID());

            final AttributeTable attrs = si.getSignedAttributes();
            final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate);

            assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size());

            TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert);
        }

    } catch (TSPException e) {
        fail("Failed to verify response");
    } catch (IOException e) {
        fail("Failed to verify response");
    }

    final TimeStampToken token = timeStampResponse.getTimeStampToken();

    try {

        token.validate(cert, "BC");

    } catch (TSPException e) {
        fail("Failed to validate response token");
    }

    return timeStampResponse.getStatus();
}