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

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

Introduction

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

Prototype

public X500Name getSubject() 

Source Link

Usage

From source file:com.ah.be.cloudauth.HmCloudAuthCertMgmtImpl.java

@SuppressWarnings("rawtypes")
private void verifyCSRContent(BeRadSecCertCreationResultEvent result, String commonName)
        throws HmCloudAuthException {
    String methodName = "verifyCSRContent";
    if (result.isCreateError()) {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_CREATE_ERR);
    }/*from  ww w.j av  a 2  s . co m*/
    if (result.isNeedCreate()) {
        byte[] csrContent = result.getCsrContent();
        final List pemItems = org.apache.commons.ssl.PEMUtil.decode(csrContent);
        if (pemItems.isEmpty()) {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }

        final PEMItem csrPemItem = (PEMItem) pemItems.get(0);
        if (csrPemItem.pemType.startsWith(CERTIFICATE_REQUEST)) {
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrPemItem.getDerBytes());
            CertificationRequestInfo requestInfo = csr.getCertificationRequestInfo();
            X509Name subject = requestInfo.getSubject();

            Vector commondNameVector = subject.getValues(X509Name.CN);
            Vector countryVector = subject.getValues(X509Name.C);
            Vector organizationVector = subject.getValues(X509Name.O);
            if (commondNameVector.isEmpty() || countryVector.isEmpty() || organizationVector.isEmpty()) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_FORMAT_ERR);
            }
            if (!commonName.equalsIgnoreCase(commondNameVector.get(0).toString())
                    || !ORGANIZATION.equals(organizationVector.get(0).toString())
                    || !COUNTRY.equals(countryVector.get(0).toString())) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_VERIFY_ERR);
            }
        } else {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }
    } else {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_STATUS_ERR);
    }
    return;
}

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

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {/*from   ww  w . j  a v a  2 s.  c om*/
        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//from   w w w. j av  a  2  s.  c  o  m
        return AuthorizationOutcome.REJECT;
}

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

License:Open Source License

/**
 * @see IRequestMessage#getRequestX509Name()
 *//*from   w w w .  j  av a 2 s  .c  o m*/
public X509Name getRequestX509Name() {
    try {
        if (pkcs10 == null) {
            init();
        }
    } catch (IllegalArgumentException e) {
        log.error("PKCS10 not inited!");
        return null;
    }
    X509Name ret = null;
    // Get subject name from request
    CertificationRequestInfo info = pkcs10.getCertificationRequestInfo();
    if (info != null) {
        ret = info.getSubject();
    }
    return ret;
}

From source file:org.glite.slcs.caclient.impl.CMPRequest.java

License:eu-egee.org license

private static CertTemplate makeCertTemplate(CertificateRequest certRequest, String issuerDN) {
    PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(certRequest.getDEREncoded());
    CertificationRequestInfo pkcs10info = pkcs10.getCertificationRequestInfo();

    log.debug("Constructing CMP CertTemplate...");
    CertTemplate certTemplate = new CertTemplate();
    certTemplate.setPublicKey(pkcs10info.getSubjectPublicKeyInfo());
    certTemplate.setSubject(pkcs10info.getSubject());
    certTemplate.setIssuer(new X509Name(issuerDN));

    // validity/*from  w  ww . ja v a 2 s .  c o m*/
    OptionalValidity validity = new OptionalValidity();
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // five minutes extra to before/after
    date.add(Calendar.MINUTE, -5);
    Time notBefore = new Time(date.getTime());
    date.add(Calendar.MINUTE, 5);
    // TODO: lifetime fixed to 1 mio seconds, should be possible to configure by user
    date.add(Calendar.SECOND, 1000000);
    Time notAfter = new Time(date.getTime());
    validity.setNotBefore(notBefore);
    validity.setNotAfter(notAfter);
    certTemplate.setValidity(validity);

    log.debug("Constructed " + certTemplate.toString());

    return certTemplate;
}

From source file:org.ntnu.utility.NorduGridCertificateRequest.java

License:Open Source License

/**
 * Reads a certificate request file in PKCS10 and PEM format.
 */// ww  w.j a va 2  s.  co m
public boolean readFromFile(String filepath) {

    try {

        String base64string;
        base64string = getCertFileContent(filepath);

        byte[] certData = Base64.decode(base64string);
        certreq = new PKCS10CertificationRequest(certData);

        // read info from cert request
        CertificationRequestInfo certinfo = certreq.getCertificationRequestInfo();
        X509Name x509name = certinfo.getSubject();

        readAttributes(x509name);

        this.publickey = certreq.getPublicKey();

    } catch (Exception e) {
        //e.printStackTrace();
        return false;
    }

    populated = true;
    return true;

}

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  w  w.java 2 s  .  c o  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);/*w  w w . j a v a2  s . co 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.  ja  v a 2s  .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);
}

From source file:org.xipki.pki.ca.qa.shell.CheckCertCmd.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    Set<String> issuerNames = qaSystemManager.getIssuerNames();
    if (isEmpty(issuerNames)) {
        throw new IllegalCmdParamException("no issuer is configured");
    }//from w ww . j  a  v a  2s .co  m

    if (issuerName == null) {
        if (issuerNames.size() != 1) {
            throw new IllegalCmdParamException("no issuer is specified");
        }

        issuerName = issuerNames.iterator().next();
    }

    if (!issuerNames.contains(issuerName)) {
        throw new IllegalCmdParamException(
                "issuer " + issuerName + " is not within the configured issuers " + issuerNames);
    }

    X509IssuerInfo issuerInfo = qaSystemManager.getIssuer(issuerName);

    X509CertprofileQa qa = qaSystemManager.getCertprofile(profileName);
    if (qa == null) {
        throw new IllegalCmdParamException("found no certificate profile named '" + profileName + "'");
    }

    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    Extensions extensions = null;
    CertificationRequestInfo reqInfo = csr.getCertificationRequestInfo();
    ASN1Set attrs = reqInfo.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]);
        }
    }

    byte[] certBytes = IoUtil.read(certFile);
    ValidationResult result = qa.checkCert(certBytes, issuerInfo, reqInfo.getSubject(),
            reqInfo.getSubjectPublicKeyInfo(), extensions);
    StringBuilder sb = new StringBuilder();

    sb.append(certFile).append(" (certprofile ").append(profileName).append(")\n");
    sb.append("\tcertificate is ");
    sb.append(result.isAllSuccessful() ? "valid" : "invalid");

    if (verbose.booleanValue()) {
        for (ValidationIssue issue : result.getValidationIssues()) {
            sb.append("\n");
            format(issue, "    ", sb);
        }
    }

    println(sb.toString());
    if (!result.isAllSuccessful()) {
        throw new CmdFailure("certificate is invalid");
    }
    return null;
}