Example usage for org.bouncycastle.asn1.pkcs CertificationRequest getCertificationRequestInfo

List of usage examples for org.bouncycastle.asn1.pkcs CertificationRequest getCertificationRequestInfo

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs CertificationRequest getCertificationRequestInfo.

Prototype

public CertificationRequestInfo getCertificationRequestInfo() 

Source Link

Usage

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  a v  a 2s. co  m
        return AuthorizationOutcome.REJECT;
}

From source file:me.it_result.ca.scep.ScepCAClientIntegrationTest.java

License:Open Source License

@Test
public void testManualEnrollment() throws CAException {
    // When server is configured for manual enrollment
    server.getContext().setAuthorization(new ManualAuthorization());
    // And enrollCertificate is invoked a few times
    UserCertificateParameters params = new UserCertificateParameters();
    params.setSubjectDN(SUBJECT_DN);/*from   www  . ja v  a  2 s  .com*/
    scepClient.enrollCertificate(params);
    X509Certificate cert = scepClient.enrollCertificate(params);
    // Then no certificate should be returned due to manual enrollment is required
    assertNull(cert);
    // And CSR should be scheduled for manual enrollment
    Collection<CertificationRequest> csrs = server.getManuallyAuthorizedCsrs();
    assertEquals(1, csrs.size());
    CertificationRequest csr = csrs.iterator().next();
    assertEquals(Utils.generateAlias(SUBJECT_DN),
            Utils.generateAlias(csr.getCertificationRequestInfo().getSubject()));
    // When the CSR is approved manually
    server.authorizeManually(csr, AuthorizationOutcome.ACCEPT);
    // And enrollCertificate is invoked again
    cert = scepClient.enrollCertificate(params);
    // Then the signed certificate should be returned by the server
    assertNotNull(cert);
}

From source file:me.it_result.ca.scep.ScepServlet.java

License:Open Source License

@Override
protected List<X509Certificate> doEnroll(CertificationRequest certificationRequest)
        throws OperationFailureException {
    // Is csr signed already?
    try {//from w w  w .ja  v  a2 s .  com
        for (X509Certificate cert : ca().listCertificates()) {
            String certAlias = Utils.generateAlias(cert.getSubjectX500Principal());
            String csrAlias = Utils
                    .generateAlias(certificationRequest.getCertificationRequestInfo().getSubject());
            // TODO: compare keys, etc?
            if (certAlias.equals(csrAlias))
                return Collections.singletonList(cert);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // Was csr manually rejected?
    boolean rejected;
    try {
        Database db = getDatabase();
        byte[] csrBytes = certificationRequest.getEncoded();
        String alias = Utils.sha1(csrBytes);
        rejected = db.readBytes(alias, REJECTED_CSR_PROPERTY) != null;
        db.removeProperty(alias, REJECTED_CSR_PROPERTY);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (rejected)
        throw new OperationFailureException(FailInfo.badMessageCheck);
    // execute request
    AuthorizationOutcome outcome = authorize(certificationRequest);
    if (outcome == AuthorizationOutcome.REJECT)
        throw new OperationFailureException(FailInfo.badMessageCheck);
    try {
        byte[] csrBytes = certificationRequest.getEncoded();
        if (outcome == AuthorizationOutcome.ACCEPT) {
            X509Certificate certificate = ca().signCertificate(csrBytes);
            return Collections.singletonList(certificate);
        } else {
            String alias = Utils.sha1(csrBytes);
            getDatabase().writeBytes(alias, MANUAL_AUTHORIZATION_CSR_PROPERTY, csrBytes);
            return Collections.emptyList();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jruby.ext.openssl.impl.PKCS10Request.java

License:LGPL

public PKCS10Request(CertificationRequest req) {

    subject = req.getCertificationRequestInfo().getSubject();
    publicKeyInfo = req.getCertificationRequestInfo().getSubjectPublicKeyInfo();
    signedRequest = new PKCS10CertificationRequest(req);
    valid = true;/* w  ww.  j  av  a2  s  .  c om*/
}

From source file:org.jscep.x509.X509Util.java

License:Open Source License

public static PublicKey getPublicKey(CertificationRequest csr) throws IOException {
    SubjectPublicKeyInfo pubKeyInfo = csr.getCertificationRequestInfo().getSubjectPublicKeyInfo();
    RSAKeyParameters keyParams = (RSAKeyParameters) PublicKeyFactory.createKey(pubKeyInfo);
    KeySpec keySpec = new RSAPublicKeySpec(keyParams.getModulus(), keyParams.getExponent());

    try {//  w  ww . j a  va  2  s  .  co  m
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(keySpec);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.xipki.ca.qa.shell.CheckCertCommand.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");
    }// w  w  w  . j  a v  a2s. co m

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

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

    if (issuerNames.contains(issuerName) == false) {
        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 p10Req = CertificationRequest.getInstance(IoUtil.read(p10File));
    Extensions extensions = null;
    ASN1Set attrs = p10Req.getCertificationRequestInfo().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,
            p10Req.getCertificationRequestInfo().getSubject(),
            p10Req.getCertificationRequestInfo().getSubjectPublicKeyInfo(), extensions);
    StringBuilder sb = new StringBuilder();

    sb.append("certificate is ");
    sb.append(result.isAllSuccessful() ? "valid" : "invalid");

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

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

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. c om
    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/*  w  ww  .j a  va 2 s . com*/
 *
 */
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.ca.server.impl.X509SelfSignedCertBuilder.java

License:Open Source License

private static X509Certificate generateCertificate(final ConcurrentContentSigner signer,
        final IdentifiedX509Certprofile certprofile, final CertificationRequest p10Request,
        final long serialNumber, SubjectPublicKeyInfo publicKeyInfo, final List<String> cacertUris,
        final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris)
        throws OperationException {
    try {/*ww w .  ja v  a2s.  c  o  m*/
        publicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
    } catch (InvalidKeySpecException e) {
        LOG.warn("SecurityUtil.toRfc3279Style", e);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage());
    }

    try {
        certprofile.checkPublicKey(publicKeyInfo);
    } catch (BadCertTemplateException e) {
        LOG.warn("certprofile.checkPublicKey", e);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage());
    }

    X500Name requestedSubject = p10Request.getCertificationRequestInfo().getSubject();

    SubjectInfo subjectInfo;
    // subject
    try {
        subjectInfo = certprofile.getSubject(requestedSubject);
    } catch (CertprofileException e) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                "exception in cert profile " + certprofile.getName());
    } catch (BadCertTemplateException e) {
        LOG.warn("certprofile.getSubject", e);
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage());
    }

    Date notBefore = certprofile.getNotBefore(null);
    if (notBefore == null) {
        notBefore = new Date();
    }

    CertValidity validity = certprofile.getValidity();
    if (validity == null) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE,
                "no validity specified in the profile " + certprofile.getName());
    }

    Date notAfter = validity.add(notBefore);

    X500Name grantedSubject = subjectInfo.getGrantedSubject();

    BigInteger _serialNumber = BigInteger.valueOf(serialNumber);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, _serialNumber,
            notBefore, notAfter, grantedSubject, publicKeyInfo);

    PublicCAInfo publicCaInfo = new PublicCAInfo(grantedSubject, _serialNumber, null, null, cacertUris,
            ocspUris, crlUris, deltaCrlUris);

    Extensions extensions = null;
    ASN1Set attrs = p10Request.getCertificationRequestInfo().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]);
        }
    }

    try {
        addExtensions(certBuilder, certprofile, requestedSubject, extensions, publicKeyInfo, publicCaInfo);

        ContentSigner contentSigner = signer.borrowContentSigner();

        Certificate bcCert;
        try {
            bcCert = certBuilder.build(contentSigner).toASN1Structure();
        } finally {
            signer.returnContentSigner(contentSigner);
        }

        byte[] encodedCert = bcCert.getEncoded();

        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(encodedCert));
    } catch (BadCertTemplateException e) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage());
    } catch (NoIdleSignerException | CertificateException | IOException | CertprofileException
            | NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, e.getClass().getName() + ": " + e.getMessage());
    }
}

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 w w .ja  va  2  s .  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;
}