Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest.

Prototype

ASN1ObjectIdentifier pkcs_9_at_extensionRequest

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest.

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.14

Usage

From source file:org.sipfoundry.sipxconfig.cert.CertificateRequestGenerator.java

License:Contributor Agreement License

/**
 * Take an existing certificate and private key and generate a CSR from that with new company
 * details but use cert's public key and other details.
 *
 * Many deprecated calls, but there's no documentation on what the new calls are
 *//*from   w w  w.j a v  a  2 s  .  c  om*/
public String getCertificateRequestText(String certTxt, String keyTxt) {
    X509Certificate cert = CertificateUtils.readCertificate(certTxt);
    PrivateKey key = CertificateUtils.readCertificateKey(keyTxt);
    X509Principal subject = new X509Principal(getSubject());
    try {
        Vector<ASN1ObjectIdentifier> oids = new Vector<ASN1ObjectIdentifier>();
        Vector<X509Extension> values = new Vector<X509Extension>();
        copyExtensions(cert, cert.getNonCriticalExtensionOIDs(), false, oids, values);
        copyExtensions(cert, cert.getCriticalExtensionOIDs(), true, oids, values);
        X509Extensions extensions = new X509Extensions(oids, values);
        Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                new DERSet(extensions));
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(m_algorithm, subject,
                cert.getPublicKey(), new DERSet(attribute), key);
        StringWriter data = new StringWriter();
        CertificateUtils.writeObject(data, csr, null);
        return data.toString();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 Certificate from CSR//from  w ww.  ja  v a2  s . c o m
 */
public static X509Certificate generateV3EndEntityCertFromCsr(PKCS10CertificationRequest csr, PrivateKey caKey,
        X509Certificate caCert, Date dateBegin, Date dateFinish, String strSubjectDN,
        DERTaggedObject... certExtensions) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    PublicKey requestPublicKey = csr.getPublicKey();
    X509Principal x509Principal = new X509Principal(strSubjectDN);
    certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno());
    log.info("generateV3EndEntityCertFromCsr - SubjectX500Principal(): " + caCert.getSubjectX500Principal());
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(dateBegin);
    certGen.setNotAfter(dateFinish);
    certGen.setSubjectDN(x509Principal);
    certGen.setPublicKey(requestPublicKey);
    certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(requestPublicKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));//Certificado final
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
    if (attributes != null) {
        for (int i = 0; i != attributes.size(); i++) {
            if (attributes.getObjectAt(i) instanceof DERTaggedObject) {
                DERTaggedObject taggedObject = (DERTaggedObject) attributes.getObjectAt(i);
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
                        ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo());
                certGen.addExtension(oid, true, taggedObject);
            } else {
                Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                    Enumeration e = extensions.oids();
                    while (e.hasMoreElements()) {
                        DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                        X509Extension ext = extensions.getExtension(oid);
                        certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
                    }
                }
            }
        }
    }
    if (certExtensions != null) {
        for (DERTaggedObject taggedObject : certExtensions) {
            if (taggedObject != null) {
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
                        ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo());
                certGen.addExtension(oid, true, taggedObject);
            }
            log.log(Level.FINE, "null taggedObject");
        }
    }
    X509Certificate cert = certGen.generate(caKey, ContextVS.PROVIDER);
    cert.verify(caCert.getPublicKey());
    return cert;
}

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");
    }//from w w  w.ja  v a 2 s . c  o 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 ww  . j  a  va  2  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  w w  .  j  a  va2 s  . co  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.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 {// w w  w.j  a v  a 2 s .  c  om
        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.commons.security.shell.CertRequestGenCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }//from   w  w  w. ja  v a2  s.co  m

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    if (wantExtensionTypes == null) {
        wantExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();

    ASN1OctetString extnValue = createExtnValueSubjectAltName();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // SubjectInfoAccess
    extnValue = createExtnValueSubjectInfoAccess();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();

                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }

                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);

                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue,
                        monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }

        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType)
                ? new TypeOfBiometricData(Integer.parseInt(biometricType))
                : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));

        ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
        md.reset();
        byte[] tmpBiometricDataHash = md.digest(biometricBytes);

        DERIA5String tmpSourceDataUri = null;
        if (biometricUri != null) {
            tmpSourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(tmpBiometricType,
                new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash),
                tmpSourceDataUri);

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);

        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
        // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)"
                + " must be set or none of them should be set");
    }

    for (Extension addExt : getAdditionalExtensions()) {
        extensions.add(addExt);
    }

    needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
    wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes),
                textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain));

    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
    if (CollectionUtil.isNonEmpty(extensions)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                new Extensions(extensions.toArray(new Extension[0])));
    }

    if (StringUtil.isNotBlank(challengePassword)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
                new DERPrintableString(challengePassword));
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo;
    if (signer.getCertificate() != null) {
        Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
        subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
    } else {
        subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
    }

    X500Name subjectDn = getSubject(subject);
    PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);

    File file = new File(outputFilename);
    saveVerbose("saved CSR to file", file, csr.getEncoded());
    return null;
}

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 av a 2  s  .c o  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;
}

From source file:org.xipki.pki.ca.server.impl.CaManagerImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final String caName, final String profileName, final String user,
        final byte[] encodedCsr, Date notBefore, Date notAfter) throws CaMgmtException {
    ParamUtil.requireNonBlank("caName", caName);
    ParamUtil.requireNonBlank("profileName", profileName);
    ParamUtil.requireNonNull("encodedCsr", encodedCsr);

    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventType("CAMGMT_CRL_GEN_ONDEMAND");

    X509Ca ca = getX509Ca(caName);//from   w w  w  .  j a  va  2  s  .c  om
    CertificationRequest csr;
    try {
        csr = CertificationRequest.getInstance(encodedCsr);
    } catch (Exception ex) {
        throw new CaMgmtException("invalid CSR request. ERROR: " + ex.getMessage());
    }

    CmpControl cmpControl = getCmpControlObject(ca.getCaInfo().getCmpControlName());
    if (!securityFactory.verifyPopo(csr, cmpControl.getPopoAlgoValidator())) {
        throw new CaMgmtException("could not validate POP for the CSR");
    }

    CertificationRequestInfo certTemp = csr.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();

    CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter,
            extensions, profileName);

    X509CertificateInfo certInfo;
    try {
        certInfo = ca.generateCertificate(certTemplateData, false, null, user, RequestType.CA, (byte[]) null,
                CaAuditConstants.MSGID_CA_mgmt);
    } catch (OperationException ex) {
        throw new CaMgmtException(ex.getMessage(), ex);
    }

    if (ca.getCaInfo().isSaveRequest()) {
        try {
            long dbId = ca.addRequest(encodedCsr);
            ca.addRequestCert(dbId, certInfo.getCert().getCertId());
        } catch (OperationException ex) {
            LogUtil.warn(LOG, ex, "could not save request");
        }
    }

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

From source file:org.xipki.pki.ca.server.impl.util.CaUtil.java

License:Open Source License

public static Extensions getExtensions(final CertificationRequestInfo csr) {
    ParamUtil.requireNonNull("csr", csr);
    ASN1Set attrs = csr.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())) {
            return Extensions.getInstance(attr.getAttributeValues()[0]);
        }//from w  w  w . ja  va 2 s  .com
    }
    return null;
}