Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpPerfTest.java

License:Open Source License

private SingleResp sendOCSPPost(byte[] ocspPackage, String nonce) throws IOException, OCSPException,
        NoSuchProviderException, OperatorCreationException, CertificateException {
    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceOcsp);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);/*from   ww w  . j  a  v  a2s.c  om*/
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = con.getOutputStream();
    os.write(ocspPackage);
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    assertEquals("Content-Type", "application/ocsp-response", con.getContentType());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and OCSP requests are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    OCSPResp response = new OCSPResp(respBytes);
    assertEquals("Response status not zero.", response.getStatus(), 0);
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    // Check nonce (if we sent one)
    if (nonce != null) {
        byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
                .getEncoded();
        assertNotNull(noncerep);
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        assertEquals(nonce, new String(oct.getOctets()));
    }
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    SingleResp singleResp = singleResps[0];
    return singleResp;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/**
 * This test tests that the OCSP response for a status unknown contains the header "cache-control" with the value "no-cache, must-revalidate"
 * /*from ww w .  ja v  a  2s  . co  m*/
 * @throws Exception
 */
@Test
public void testUnknownStatusCacheControlHeader() throws Exception {

    // set ocsp configuration
    Map<String, String> map = new HashMap<String, String>();
    map.put(OcspConfiguration.UNTIL_NEXT_UPDATE, "1");
    this.helper.alterConfig(map);

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1")));
    OCSPReq req = gen.build();

    String sBaseURL = httpReqPath + '/' + resourceOcsp;
    String urlEnding = "";
    String b64 = new String(Base64.encode(req.getEncoded(), false));
    //String urls = URLEncoder.encode(b64, "UTF-8");    // JBoss/Tomcat will not accept escaped '/'-characters by default
    URL url = new URL(sBaseURL + '/' + b64 + urlEnding);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    if (con.getResponseCode() != 200) {
        log.info("URL when request gave unexpected result: " + url.toString() + " Message was: "
                + con.getResponseMessage());
    }
    assertEquals("Response code did not match. ", 200, con.getResponseCode());
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));

    assertNotNull("No Cache-Control in reply.", con.getHeaderField("Cache-Control"));
    assertEquals("no-cache, must-revalidate", con.getHeaderField("Cache-Control"));

    // Create a GET request using Nonce extension, in this case we should have no cache-control header
    gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1")));
    Extension[] extensions = new Extension[1];
    extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    req = gen.build();
    b64 = new String(Base64.encode(req.getEncoded(), false));
    url = new URL(sBaseURL + '/' + b64 + urlEnding);
    con = (HttpURLConnection) url.openConnection();
    if (con.getResponseCode() != 200) {
        log.info("URL when request gave unexpected result: " + url.toString() + " Message was: "
                + con.getResponseMessage());
    }
    assertEquals("Response code did not match. ", 200, con.getResponseCode());
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue().getEncoded();
    // Make sure we have a nonce in the response, we should have since we sent one in the request
    assertNotNull("Response should have nonce since we sent a nonce in the request", noncerep);
    ASN1InputStream ain = new ASN1InputStream(noncerep);
    ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
    ain.close();
    assertEquals("Response Nonce was not the same as the request Nonce, it must be", "123456789",
            new String(oct.getOctets()));
    assertNull(
            "Cache-Control in reply although we used Nonce in the request. Responses with Nonce should not have a Cache-control header.",
            con.getHeaderField("Cache-Control"));
}

From source file:org.ejbca.core.protocol.scep.ScepRequestMessage.java

License:Open Source License

private void init() throws IOException {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }//from   w w w .  j a v  a  2 s.c o  m
    try {
        CMSSignedData csd = new CMSSignedData(scepmsg);
        SignerInformationStore infoStore = csd.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> signers = infoStore.getSigners();
        Iterator<SignerInformation> iter = signers.iterator();
        if (iter.hasNext()) {
            SignerInformation si = (SignerInformation) iter.next();
            preferredDigestAlg = si.getDigestAlgOID();
            log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP");
        }
    } catch (CMSException e) {
        // ignore, use default digest algo
        log.error("CMSException trying to get preferred digest algorithm: ", e);
    }
    // Parse and verify the integrity of the PKIOperation message PKCS#7
    /* If this would have been done using the newer CMS it would have made me so much happier... */
    ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg));
    ASN1Sequence seq = null;
    try {
        seq = (ASN1Sequence) seqAsn1InputStream.readObject();
    } finally {
        seqAsn1InputStream.close();
    }
    ContentInfo ci = ContentInfo.getInstance(seq);
    String ctoid = ci.getContentType().getId();

    if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) {
        // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned
        // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side
        // Try to find out what kind of message this is
        sd = SignedData.getInstance((ASN1Sequence) ci.getContent());
        // Get self signed cert to identify the senders public key
        ASN1Set certs = sd.getCertificates();
        if (certs.size() > 0) {
            // There should be only one...
            ASN1Encodable dercert = certs.getObjectAt(0);
            if (dercert != null) {
                // Requester's self-signed certificate is requestKeyInfo
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                DEROutputStream dOut = new DEROutputStream(bOut);
                dOut.writeObject(dercert);
                if (bOut.size() > 0) {
                    requestKeyInfo = bOut.toByteArray();
                    //Create Certificate used for debugging
                    try {
                        signercert = CertTools.getCertfromByteArray(requestKeyInfo);
                        if (log.isDebugEnabled()) {
                            log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert)
                                    + ", Serial=" + CertTools.getSerialNumberAsString(signercert)
                                    + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString());
                        }
                    } catch (CertificateException e) {
                        log.error("Error parsing requestKeyInfo : ", e);
                    }

                }
            }
        }

        Enumeration<?> sis = sd.getSignerInfos().getObjects();

        if (sis.hasMoreElements()) {
            SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement());
            Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects();

            while (attr.hasMoreElements()) {
                Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement());
                if (log.isDebugEnabled()) {
                    log.debug("Found attribute: " + a.getAttrType().getId());
                }
                if (a.getAttrType().getId().equals(id_senderNonce)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement());
                    senderNonce = new String(Base64.encode(str.getOctets(), false));
                    if (log.isDebugEnabled()) {
                        log.debug("senderNonce = " + senderNonce);
                    }
                }
                if (a.getAttrType().getId().equals(id_transId)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    transactionId = str.getString();
                    if (log.isDebugEnabled()) {
                        log.debug("transactionId = " + transactionId);
                    }
                }
                if (a.getAttrType().getId().equals(id_messageType)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    messageType = Integer.parseInt(str.getString());
                    if (log.isDebugEnabled()) {
                        log.debug("messagetype = " + messageType);
                    }
                }
            }
        }

        // If this is a PKCSReq
        if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) {
            // Extract the contents, which is an encrypted PKCS10 if messageType == 19
            // , and an encrypted issuer and subject if messageType == 20 (not extracted)
            // and an encrypted IssuerAndSerialNumber if messageType == 22
            ci = sd.getEncapContentInfo();
            ctoid = ci.getContentType().getId();

            if (ctoid.equals(CMSObjectIdentifiers.data.getId())) {
                ASN1OctetString content = (ASN1OctetString) ci.getContent();
                if (log.isDebugEnabled()) {
                    log.debug("envelopedData is " + content.getOctets().length + " bytes.");
                }
                ASN1InputStream seq1Asn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(content.getOctets()));
                ASN1Sequence seq1 = null;
                try {
                    seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject();
                } finally {
                    seq1Asn1InputStream.close();
                }
                envEncData = ContentInfo.getInstance(seq1);
                ctoid = envEncData.getContentType().getId();

                if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) {
                    envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent());
                    ASN1Set recipientInfos = envData.getRecipientInfos();
                    Enumeration<?> e = recipientInfos.getObjects();
                    while (e.hasMoreElements()) {
                        RecipientInfo ri = RecipientInfo.getInstance(e.nextElement());
                        KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo());
                        RecipientIdentifier rid = recipientInfo.getRecipientIdentifier();
                        IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId());
                        issuerDN = iasn.getName().toString();
                        serialNo = iasn.getSerialNumber().getValue();
                        if (log.isDebugEnabled()) {
                            log.debug("IssuerDN: " + issuerDN);
                            log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16));
                        }
                    }
                } else {
                    errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: ";
                    log.error(errorText + ctoid);
                    error = 2;
                }
            } else {
                errorText = "EncapsulatedContentInfo is not of type 'data': ";
                log.error(errorText + ctoid);
                error = 3;
            }
        } else {
            errorText = "This is not a certification request!";
            log.error(errorText);
            error = 4;
        }
    } else {
        errorText = "PKCSReq does not contain 'signedData': ";
        log.error(errorText + ctoid);
        error = 1;
    }

    log.trace("<init");
}