Search in sources :

Example 66 with Request

use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.

the class InstanceClientRefresh method main.

public static void main(String[] args) throws MalformedURLException, IOException {
    // parse our command line to retrieve required input
    CommandLine cmd = parseCommandLine(args);
    String domainName = cmd.getOptionValue("domain").toLowerCase();
    String serviceName = cmd.getOptionValue("service").toLowerCase();
    String provider = cmd.getOptionValue("provider").toLowerCase();
    String instance = cmd.getOptionValue("instance");
    String dnsSuffix = cmd.getOptionValue("dnssuffix");
    String instanceKeyPath = cmd.getOptionValue("instancekey");
    String ztsUrl = cmd.getOptionValue("ztsurl");
    // now we need to generate our CSR so we can get
    // a TLS certificate for our instance
    PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
    String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);
    if (csr == null) {
        System.err.println("Unable to generate CSR for instance");
        System.exit(1);
    }
    System.out.println("CSR: \n" + csr + "\n");
    // now let's generate our instance refresh object that will be sent
    // to the ZTS Server
    InstanceRefreshInformation info = new InstanceRefreshInformation().setToken(true).setCsr(csr);
    // now contact zts server to request identity for instance
    InstanceIdentity identity = null;
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
        identity = ztsClient.postInstanceRefreshInformation(provider, domainName, serviceName, instance, info);
    } catch (ZTSClientException ex) {
        System.out.println("Unable to register instance: " + ex.getMessage());
        System.exit(2);
    }
    System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
}
Also used : CommandLine(org.apache.commons.cli.CommandLine) InstanceRefreshInformation(com.yahoo.athenz.zts.InstanceRefreshInformation) PrivateKey(java.security.PrivateKey) ZTSClient(com.yahoo.athenz.zts.ZTSClient) ZTSClientException(com.yahoo.athenz.zts.ZTSClientException) DERIA5String(org.bouncycastle.asn1.DERIA5String) File(java.io.File) InstanceIdentity(com.yahoo.athenz.zts.InstanceIdentity)

Example 67 with Request

use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.

the class Crypto method generateX509CSR.

public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey, String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException {
    // Create Distinguished Name
    X500Principal subject = new X500Principal(x500Principal);
    // Create ContentSigner
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256);
    ContentSigner signer = csBuilder.build(privateKey);
    // Create the CSR
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
    if (sanArray != null) {
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        GeneralNames subjectAltNames = new GeneralNames(sanArray);
        extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    }
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    // write to openssl PEM format
    PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());
    StringWriter strWriter;
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) {
        pemWriter.writeObject(pemObject);
    }
    return strWriter.toString();
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) PemObject(org.bouncycastle.util.io.pem.PemObject) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) StringWriter(java.io.StringWriter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Principal(javax.security.auth.x500.X500Principal) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 68 with Request

use of org.bouncycastle.asn1.ocsp.Request in project wso2-synapse by wso2.

the class OCSPVerifierTest method generateOCSPResponse.

/**
 * This makes the corresponding OCSP response to the OCSP request which is sent to the fake CA. If the request
 * has a certificateID which is marked as revoked by the CA, the OCSP response will say that the certificate
 * which is referred to by the request, is revoked.
 *
 * @param request the OCSP request which asks if the certificate is revoked.
 * @param caPrivateKey privateKey of the fake CA.
 * @param caPublicKey  publicKey of the fake CA
 * @param revokedID the ID at fake CA which is checked against the certificateId in the request.
 * @return the created OCSP response by the fake CA.
 * @throws NoSuchProviderException
 * @throws OCSPException
 * @throws OperatorCreationException
 */
private OCSPResp generateOCSPResponse(OCSPReq request, X509CertificateHolder certificateHolder, PrivateKey caPrivateKey, PublicKey caPublicKey, CertificateID revokedID) throws NoSuchProviderException, OCSPException, OperatorCreationException {
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(new RespID(certificateHolder.getSubject()));
    Extension extension = request.getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp.getId()));
    if (extension != null) {
        basicOCSPRespBuilder.setResponseExtensions(new Extensions(extension));
    }
    Req[] requests = request.getRequestList();
    for (Req req : requests) {
        CertificateID certID = req.getCertID();
        if (certID.equals(revokedID)) {
            RevokedStatus revokedStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
            Date nextUpdate = new Date(new Date().getTime() + TestConstants.NEXT_UPDATE_PERIOD);
            basicOCSPRespBuilder.addResponse(certID, revokedStatus, nextUpdate, null);
        } else {
            basicOCSPRespBuilder.addResponse(certID, CertificateStatus.GOOD);
        }
    }
    X509CertificateHolder[] chain = { certificateHolder };
    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caPrivateKey);
    BasicOCSPResp basicResp = basicOCSPRespBuilder.build(signer, chain, new Date());
    OCSPRespBuilder builder = new OCSPRespBuilder();
    return builder.build(OCSPRespBuilder.SUCCESSFUL, basicResp);
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) Date(java.util.Date) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 69 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class CaManagerImpl method generateCertificate.

// method removeCertificate
@Override
public X509Certificate generateCertificate(String caName, String profileName, byte[] encodedCsr, Date notBefore, Date notAfter) throws CaMgmtException {
    caName = ParamUtil.requireNonBlank("caName", caName).toLowerCase();
    profileName = ParamUtil.requireNonBlank("profileName", profileName).toLowerCase();
    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);
    CertificationRequest csr;
    try {
        csr = CertificationRequest.getInstance(encodedCsr);
    } catch (Exception ex) {
        throw new CaMgmtException(concat("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, byCaRequestor, 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();
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) CertprofileException(org.xipki.ca.api.profile.CertprofileException) KeyStoreException(java.security.KeyStoreException) XiSecurityException(org.xipki.security.exception.XiSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidConfException(org.xipki.common.InvalidConfException) SocketException(java.net.SocketException) IOException(java.io.IOException) CertPublisherException(org.xipki.ca.api.publisher.CertPublisherException) OperationException(org.xipki.ca.api.OperationException) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) ObjectCreationException(org.xipki.common.ObjectCreationException) DataAccessException(org.xipki.datasource.DataAccessException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) CertificateException(java.security.cert.CertificateException) PasswordResolverException(org.xipki.password.PasswordResolverException) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) ASN1Set(org.bouncycastle.asn1.ASN1Set) CmpControl(org.xipki.ca.server.mgmt.api.CmpControl) PciAuditEvent(org.xipki.audit.PciAuditEvent) AuditEvent(org.xipki.audit.AuditEvent) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) OperationException(org.xipki.ca.api.OperationException)

Example 70 with Request

use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.

the class OcspBenchRequestor method buildRequest.

// method ask
private byte[] buildRequest(BigInteger[] serialNumbers) throws OcspRequestorException {
    boolean canCache = (serialNumbers.length == 1) && !requestOptions.isUseNonce();
    if (canCache) {
        byte[] request = requests.get(serialNumbers[0]);
        if (request != null) {
            return request;
        }
    }
    OCSPReqBuilder reqBuilder = new OCSPReqBuilder();
    if (requestOptions.isUseNonce() || extensions != null) {
        List<Extension> extns = new ArrayList<>(2);
        if (requestOptions.isUseNonce()) {
            Extension extn = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nextNonce(requestOptions.getNonceLen())));
            extns.add(extn);
        }
        if (extensions != null) {
            for (Extension extn : extensions) {
                extns.add(extn);
            }
        }
        reqBuilder.setRequestExtensions(new Extensions(extns.toArray(extnType)));
    }
    try {
        for (BigInteger serialNumber : serialNumbers) {
            CertID certId = new CertID(issuerhashAlg, issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
            reqBuilder.addRequest(new CertificateID(certId));
        }
        byte[] request = reqBuilder.build().getEncoded();
        if (canCache) {
            requests.put(serialNumbers[0], request);
        }
        return request;
    } catch (OCSPException | IOException ex) {
        throw new OcspRequestorException(ex.getMessage(), ex);
    }
}
Also used : OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) ArrayList(java.util.ArrayList) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) BigInteger(java.math.BigInteger) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder)

Aggregations

IOException (java.io.IOException)47 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)30 Date (java.util.Date)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)23 X509Certificate (java.security.cert.X509Certificate)22 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 Extension (org.bouncycastle.asn1.x509.Extension)16 Extensions (org.bouncycastle.asn1.x509.Extensions)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)11