Example usage for org.bouncycastle.asn1.pkcs CertificationRequestInfo getAttributes

List of usage examples for org.bouncycastle.asn1.pkcs CertificationRequestInfo getAttributes

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs CertificationRequestInfo getAttributes.

Prototype

public ASN1Set getAttributes() 

Source Link

Usage

From source file:edu.washington.iam.tools.IamCertificateHelper.java

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {// w w  w.  ja  v a  2s .  c o m
        PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest));
        PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();
        if (request == null)
            throw new IamCertificateException("invalid CSR (request)");
        CertificationRequestInfo info = request.getCertificationRequestInfo();
        if (info == null)
            throw new IamCertificateException("invalid CSR (info)");

        X509Name dn = info.getSubject();
        if (dn == null)
            throw new IamCertificateException("invalid CSR (dn)");
        log.debug("dn=" + dn.toString());
        cert.dn = dn.toString();
        try {
            List cns = dn.getValues(X509Name.CN);
            cert.cn = (String) (cns.get(0));
            log.debug("cn=" + cert.cn);
            cert.names.add(cert.cn); // first entry for names is always cn
            cns = dn.getValues(X509Name.C);
            cert.dnC = (String) (cns.get(0));
            cns = dn.getValues(X509Name.ST);
            cert.dnST = (String) (cns.get(0));
        } catch (Exception e) {
            log.debug("get cn error: " + e);
            throw new IamCertificateException("invalid CSR");
        }

        // see if we've got alt names (in extensions)

        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            for (int a = 0; a < attrs.size(); a++) {
                Attribute attr = Attribute.getInstance(attrs.getObjectAt(a));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {

                    // is the extension
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

                    // get the subAltName extension
                    DERObjectIdentifier sanoid = new DERObjectIdentifier(
                            X509Extensions.SubjectAlternativeName.getId());
                    X509Extension xext = extensions.getExtension(sanoid);
                    if (xext != null) {
                        log.debug("processing altname extensions");
                        ASN1Object asn1 = X509Extension.convertValueToObject(xext);
                        Enumeration dit = DERSequence.getInstance(asn1).getObjects();
                        while (dit.hasMoreElements()) {
                            GeneralName gn = GeneralName.getInstance(dit.nextElement());
                            log.debug("altname tag=" + gn.getTagNo());
                            log.debug("altname name=" + gn.getName().toString());
                            if (gn.getTagNo() == GeneralName.dNSName)
                                cert.names.add(gn.getName().toString());
                        }
                    }

                }
            }
        }

        // check key size
        PublicKey pk = request.getPublicKey();
        log.debug("key alg = " + pk.getAlgorithm());
        log.debug("key fmt = " + pk.getFormat());
        if (pk.getAlgorithm().equals("RSA")) {
            RSAPublicKey rpk = (RSAPublicKey) pk;
            cert.keySize = rpk.getModulus().bitLength();
            log.debug("key size = " + cert.keySize);
        }

    } catch (IOException e) {
        log.debug("ioerror: " + e);
        throw new IamCertificateException("invalid CSR " + e.getMessage());
    } catch (Exception e) {
        log.debug("excp: " + e);
        throw new IamCertificateException("invalid CSR");
    }
    return 1;
}

From source file:me.it_result.ca.bouncycastle.ChallengePasswordAuthorization.java

License:Open Source License

@Override
public AuthorizationOutcome isAuthorized(CertificationRequest certificationRequest) throws Exception {
    CertificationRequestInfo requestInfo = certificationRequest.getCertificationRequestInfo();
    X509Name subject = requestInfo.getSubject();
    String alias = Utils.generateAlias(subject);
    String expectedPassword = readPassword(alias);
    String actualPassword = Utils.extractChallengePassword(requestInfo.getAttributes());
    if (actualPassword != null && expectedPassword != null && actualPassword.equals(expectedPassword))
        return AuthorizationOutcome.ACCEPT;
    else/* w w w  . j  a  v a2s .  c  om*/
        return AuthorizationOutcome.REJECT;
}

From source file:org.deviceconnect.android.ssl.CertificateAuthority.java

License:MIT License

/**
 * ???? Subject Alternative Names (SANs) ??.
 *
 * @param request ???//from  w ww  .  j av  a2s .  c  o m
 * @return SubjectAlternativeNames? {@link GeneralNames} 
 * @throws IOException ?????
 */
private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException {
    List<ASN1Encodable> generalNames = new ArrayList<>();

    CertificationRequestInfo info = request.getCertificationRequestInfo();
    ASN1Set attributes = info.getAttributes();
    for (int i = 0; i < attributes.size(); i++) {
        DEREncodable extensionRequestObj = attributes.getObjectAt(i);
        if (!(extensionRequestObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensionRequest = (DERSequence) extensionRequestObj;
        if (extensionRequest.size() != 2) {
            continue;
        }
        DEREncodable idObj = extensionRequest.getObjectAt(0);
        DEREncodable contentObj = extensionRequest.getObjectAt(1);
        if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) {
            continue;
        }
        ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj;
        DERSet content = (DERSet) contentObj;
        if (!id.getId().equals("1.2.840.113549.1.9.14")) {
            continue;
        }
        if (content.size() < 1) {
            continue;
        }
        DEREncodable extensionsObj = content.getObjectAt(0);
        if (!(extensionsObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensions = (DERSequence) extensionsObj;

        for (int k = 0; k < extensions.size(); k++) {
            DEREncodable extensionObj = extensions.getObjectAt(k);
            if (!(extensionObj instanceof DERSequence)) {
                continue;
            }
            DERSequence extension = (DERSequence) extensionObj;
            if (extension.size() != 2) {
                continue;
            }
            DEREncodable extensionIdObj = extension.getObjectAt(0);
            DEREncodable extensionContentObj = extension.getObjectAt(1);
            if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) {
                continue;
            }
            ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj;
            if (extensionId.getId().equals("2.5.29.17")) {
                DEROctetString san = (DEROctetString) extensionContentObj;

                ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream());
                DEREncodable namesObj = sanParser.readObject().getDERObject();
                if (namesObj instanceof DERSequence) {
                    DERSequence names = (DERSequence) namesObj;
                    for (int m = 0; m < names.size(); m++) {
                        DEREncodable nameObj = names.getObjectAt(m);
                        if (nameObj instanceof DERTaggedObject) {
                            DERTaggedObject name = (DERTaggedObject) nameObj;
                            switch (name.getTagNo()) {
                            case GeneralName.dNSName:
                                generalNames.add(new GeneralName(GeneralName.dNSName,
                                        DERIA5String.getInstance(name, false)));
                                break;
                            case GeneralName.iPAddress:
                                generalNames.add(new GeneralName(GeneralName.iPAddress,
                                        DEROctetString.getInstance(name, true)));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (generalNames.size() > 0) {
        return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[generalNames.size()])));
    }
    return null;
}

From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java

License:Open Source License

/**
 * Returns the challenge password from the certificattion request.
 *
 * @return challenge password from certification request or null if none exist in the request.
 *//*from  ww  w  . ja  va 2s.  c  om*/
public String getPassword() {
    if (password != null) {
        return password;
    }
    try {
        if (pkcs10 == null) {
            init();
        }
    } catch (IllegalArgumentException e) {
        log.error("PKCS10 not inited!");
        return null;
    }

    String ret = null;

    // Get attributes
    // The password attribute can be either a pkcs_9_at_challengePassword directly
    // or
    // a pkcs_9_at_extensionRequest containing a pkcs_9_at_challengePassword as a
    // X509Extension.
    AttributeTable attributes = null;
    CertificationRequestInfo info = pkcs10.getCertificationRequestInfo();
    if (info != null) {
        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            attributes = new AttributeTable(attrs);
        }
    }
    if (attributes == null) {
        return null;
    }
    Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    DEREncodable obj = null;
    if (attr == null) {
        // See if we have it embedded in an extension request instead
        attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (attr == null) {
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug("got extension request");
        }
        ASN1Set values = attr.getAttrValues();
        if (values.size() == 0) {
            return null;
        }
        X509Extensions exts = X509Extensions.getInstance(values.getObjectAt(0));
        X509Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
        if (ext == null) {
            if (log.isDebugEnabled()) {
                log.debug("no challenge password extension");
            }
            return null;
        }
        obj = ext.getValue();
    } else {
        // If it is a challengePassword directly, it's just to grab the value
        ASN1Set values = attr.getAttrValues();
        obj = values.getObjectAt(0);
    }

    if (obj != null) {
        DERString str = null;

        try {
            str = DERPrintableString.getInstance((obj));
        } catch (IllegalArgumentException ie) {
            // This was not printable string, should be utf8string then according to pkcs#9 v2.0
            str = DERUTF8String.getInstance((obj));
        }

        if (str != null) {
            ret = str.getString();
        }
    }

    return ret;
}

From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java

License:Open Source License

/**
 * @see org.ejbca.core.protocol.IRequestMessage
 *///  w  w  w  .  ja v  a 2 s  . c  om
public X509Extensions getRequestExtensions() {
    try {
        if (pkcs10 == null) {
            init();
        }
    } catch (IllegalArgumentException e) {
        log.error("PKCS10 not inited!");
        return null;
    }
    X509Extensions ret = null;

    // Get attributes
    // The X509 extension is in a a pkcs_9_at_extensionRequest
    AttributeTable attributes = null;
    CertificationRequestInfo info = pkcs10.getCertificationRequestInfo();
    if (info != null) {
        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            attributes = new AttributeTable(attrs);
        }
    }
    if (attributes != null) {
        // See if we have it embedded in an extension request instead
        Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (attr != null) {
            if (log.isDebugEnabled()) {
                log.debug("got request extension");
            }
            ASN1Set values = attr.getAttrValues();
            if (values.size() > 0) {
                try {
                    ret = X509Extensions.getInstance(values.getObjectAt(0));
                } catch (IllegalArgumentException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request.");
                    }
                }
            }
        }
    }
    return ret;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public void test19getAltNameStringFromExtension() throws Exception {
    PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(p10ReqWithAltNames);
    CertificationRequestInfo info = p10.getCertificationRequestInfo();
    ASN1Set set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest
    Enumeration<Object> en = set.getObjects();
    boolean found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;/*  w  w w .  j ava  2s  .com*/
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames);
            }
        }
    }
    assertTrue(found);

    p10 = new PKCS10CertificationRequest(p10ReqWithAltNames2);
    info = p10.getCertificationRequestInfo();
    set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest

    en = set.getObjects();
    found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames);
            }
        }
    }
    assertTrue(found);

}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public List<X509ExtensionHolder> extractRequestedExtensions(PKCS10CertificationRequest pkcs10) {
    final List<X509ExtensionHolder> extractedExtensions = new ArrayList<X509ExtensionHolder>();
    final CertificationRequestInfo certificationRequestInfo = pkcs10.getCertificationRequestInfo();
    final ASN1Set attributesAsn1Set = certificationRequestInfo.getAttributes();
    if (attributesAsn1Set == null) {
        return extractedExtensions;
    }//from  w w  w.ja  v a 2 s . c om
    // The `Extension Request` attribute is contained within an ASN.1 Set,
    // usually as the first element.
    X509Extensions requestedExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));

            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();

                // The X509Extensions are contained as a value of the ASN.1 Set.
                // WARN Assuming that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    DEREncodable extensionsDEREncodable = attributeValues.getObjectAt(0);
                    ASN1Sequence extensionsASN1Sequence = (ASN1Sequence) extensionsDEREncodable;
                    requestedExtensions = new X509Extensions(extensionsASN1Sequence);
                    // No need to search any more.
                    break;
                }
            }
        }
    }
    if (requestedExtensions != null) {
        Enumeration<?> e = requestedExtensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension extension = requestedExtensions.getExtension(oid);
            extractedExtensions.add(new X509ExtensionHolder(oid, extension.isCritical(),
                    X509Extension.convertValueToObject(extension)));
        }
    }
    return extractedExtensions;
}

From source file:org.votingsystem.model.currency.Currency.java

License:Open Source License

public Currency(PKCS10CertificationRequest csr) throws ExceptionVS, IOException {
    this.csr = csr;
    CertificationRequestInfo info = csr.getCertificationRequestInfo();
    Enumeration csrAttributes = info.getAttributes().getObjects();
    CurrencyCertExtensionDto certExtensionDto = null;
    while (csrAttributes.hasMoreElements()) {
        DERTaggedObject attribute = (DERTaggedObject) csrAttributes.nextElement();
        switch (attribute.getTagNo()) {
        case ContextVS.CURRENCY_TAG:
            String certAttributeJSONStr = ((DERUTF8String) attribute.getObject()).getString();
            certExtensionDto = JSON.getMapper().readValue(certAttributeJSONStr, CurrencyCertExtensionDto.class);
            break;
        }/*from   w  ww  .ja v  a2 s  .  co  m*/
    }
    initCertData(certExtensionDto, info.getSubject().toString());
}

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

License:Open Source License

@Override
public X509Certificate generateCertificate(final String caName, final String profileName, final String user,
        final byte[] encodedPkcs10Request) throws CAMgmtException {
    ParamChecker.assertNotBlank("caName", caName);
    ParamChecker.assertNotBlank("profileName", profileName);
    ParamChecker.assertNotNull("encodedPkcs10Request", encodedPkcs10Request);

    X509CA ca = getX509CA(caName);/*from  ww  w .ja va2  s .  c o  m*/
    CertificationRequest p10cr;
    try {
        p10cr = CertificationRequest.getInstance(encodedPkcs10Request);
    } catch (Exception e) {
        throw new CAMgmtException("invalid PKCS#10 request. ERROR: " + e.getMessage());
    }

    if (securityFactory.verifyPOPO(p10cr) == false) {
        throw new CAMgmtException("could not validate POP for the pkcs#10 requst");
    }

    CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
    Extensions extensions = null;
    ASN1Set attrs = certTemp.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }

    X500Name subject = certTemp.getSubject();
    SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

    X509CertificateInfo certInfo;
    try {
        certInfo = ca.generateCertificate(false, null, profileName, user, subject, publicKeyInfo, null, null,
                extensions);
    } catch (OperationException e) {
        throw new CAMgmtException(e.getMessage(), e);
    }

    return certInfo.getCert().getCert();
}

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

License:Open Source License

/**
 * handle the PKI body with the choice {@code p10cr}<br/>
 * Since it is not possible to add attribute to the PKCS#10 request, the certificate profile
 * must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
 * PKIHeader.generalInfo//from   ww  w  .j  a va2 s .  c o m
 *
 */
private PKIBody processP10cr(final CmpRequestorInfo requestor, final String user, final ASN1OctetString tid,
        final PKIHeader reqHeader, final CertificationRequest p10cr, final long confirmWaitTime,
        final boolean sendCaCert, final AuditEvent auditEvent) throws InsuffientPermissionException {
    // verify the POP first
    CertResponse certResp;
    ASN1Integer certReqId = new ASN1Integer(-1);

    AuditChildEvent childAuditEvent = null;
    if (auditEvent != null) {
        childAuditEvent = new AuditChildEvent();
        auditEvent.addChildAuditEvent(childAuditEvent);
    }

    if (securityFactory.verifyPOPO(p10cr) == false) {
        LOG.warn("could not validate POP for the pkcs#10 requst");
        PKIStatusInfo status = generateCmpRejectionStatus(PKIFailureInfo.badPOP, null);
        certResp = new CertResponse(certReqId, status);
        if (childAuditEvent != null) {
            childAuditEvent.setStatus(AuditStatus.FAILED);
            childAuditEvent.addEventData(new AuditEventData("message", "invalid POP"));
        }
    } else {
        CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
        Extensions extensions = null;
        ASN1Set attrs = certTemp.getAttributes();
        for (int i = 0; i < attrs.size(); i++) {
            Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
            if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
                extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
            }
        }

        X500Name subject = certTemp.getSubject();
        if (childAuditEvent != null) {
            childAuditEvent.addEventData(new AuditEventData("subject", X509Util.getRFC4519Name(subject)));
        }

        SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();

        try {
            CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
            String certprofileName = keyvalues == null ? null
                    : keyvalues.getValue(CmpUtf8Pairs.KEY_CERT_PROFILE);
            if (certprofileName == null) {
                throw new CMPException("no certificate profile is specified");
            }

            if (childAuditEvent != null) {
                childAuditEvent.addEventData(new AuditEventData("certprofile", certprofileName));
            }

            checkPermission(requestor, certprofileName);

            certResp = generateCertificate(requestor, user, tid, certReqId, subject, publicKeyInfo, null,
                    extensions, certprofileName, false, confirmWaitTime, childAuditEvent);
        } catch (CMPException e) {
            certResp = new CertResponse(certReqId,
                    generateCmpRejectionStatus(PKIFailureInfo.badCertTemplate, e.getMessage()));
            if (childAuditEvent != null) {
                childAuditEvent.setStatus(AuditStatus.FAILED);
                childAuditEvent.addEventData(new AuditEventData("message", "badCertTemplate"));
            }
        } // end try
    }

    CMPCertificate[] caPubs = sendCaCert ? new CMPCertificate[] { getCA().getCAInfo().getCertInCMPFormat() }
            : null;
    CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });

    return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}