Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

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

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

License:Open Source License

/**
 * Test the error message returned when CMP request missing a signature in RA mode (operationmode=ra) and EndEntityCertificate authentication is configured. 
 * //from  w  ww .j av a2 s .  c  o m
 * @throws Exception on some errors
 */
@Test
public void test20NoEECAuthentication() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, new DEROctetString(this.nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        String expectedErrMsg = "PKI Message is not athenticated properly. No PKI protection is found.";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

License:Open Source License

/**
 * Sending a Crmf Request in RA mode. The request is authenticated using HMAC and is expected to contain the EndEntityProfile 'EMPTY' in the KeyId field.
 * The request should fail because specifying 'EMPTY' or 'ENDUSER' as the KeyId is not allowed in combination with RA mode and HMAC authentication module 
 * /*ww w .j  a v a  2  s. c  om*/
 * The test is only done for HMAC and not EndEntityCertificate because in the later, the use of profiles can be restricted through Administrator privileges.
 * Other authentication modules are not used in RA mode
 * 
 * @throws Exception
 */
@Test
public void test24HMACUnacceptedKeyId() throws Exception {

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123hmac");
    this.cmpConfiguration.setRAEEProfile(ALIAS, "KeyId");
    this.cmpConfiguration.setRACertProfile(ALIAS, "ProfileDefault");
    this.cmpConfiguration.setRACAName(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, null, null);
    assertNotNull("Generating CrmfRequest failed.", msg);
    PKIMessage req = protectPKIMessage(msg, false, "foo123hmac", "EMPTY", 567);
    assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, req.getHeader().getSenderNonce().getOctets(),
            req.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "Unaccepted KeyId 'EMPTY' in CMP request";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

License:Open Source License

private static CMPCertificate[] getCMPCert(Certificate cert) throws CertificateEncodingException, IOException {
    ASN1InputStream ins = new ASN1InputStream(cert.getEncoded());
    ASN1Primitive pcert = ins.readObject();
    ins.close();//w  ww.ja  va2  s  .  c o m
    org.bouncycastle.asn1.x509.Certificate c = org.bouncycastle.asn1.x509.Certificate
            .getInstance(pcert.toASN1Primitive());
    CMPCertificate[] res = { new CMPCertificate(c) };
    return res;
}

From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java

License:Open Source License

public GeneralName getRecipient() {
    if (recipient == null && recipientBytes != null) {
        ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(recipientBytes));
        try {//from  w  w  w .  j  ava  2s  .  c o  m
            recipient = GeneralName.getInstance(ais.readObject());
            ais.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return recipient;
}

From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java

License:Open Source License

public GeneralName getSender() {
    if (sender == null && senderBytes != null) {
        ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(senderBytes));
        try {/*from w w  w.  j a  va  2 s .  c o m*/
            sender = GeneralName.getInstance(ais.readObject());
            ais.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return sender;
}

From source file:org.ejbca.core.protocol.cmp.CmpAliasTest.java

License:Open Source License

/**
 * Sends a CMP request with the alias requestAlias in the URL and expects a CMP error message 
 * that extractedAlias does not  exist.//from   www  . j a v a2 s.c  o m
 * 
 * @param requestAlias the alias that is  specified in the URL
 * @param extractedAlias the alias that EJBCA will use to handle the CMP request
 * @throws Exception
 */
private void sendCmpRequest(CmpConfiguration cmpconfig, String requestAlias, String extractedAlias)
        throws Exception {

    if (cmpconfig.aliasExists(extractedAlias)) {
        cmpconfig.renameAlias(extractedAlias, "backUpAlias" + extractedAlias + "ForAliasTesting001122334455");
        this.globalConfigurationSession.saveConfiguration(ADMIN, cmpconfig);
    }

    try {
        String urlString = this.httpReqPath + '/' + this.baseResource;
        if (requestAlias != null) {
            urlString += "/" + requestAlias;
        }
        log.info("http URL: " + urlString);
        URL url = new URL(urlString);
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/pkixcmp");
        con.connect();
        assertEquals("Unexpected HTTP response code.", 200, con.getResponseCode()); // OK response (will use alias "alias123")

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and CMP requests are small enough
        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();
        assertNotNull(respBytes);
        assertTrue(respBytes.length > 0);

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(respBytes));
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "Wrong URL. CMP alias '" + extractedAlias + "' does not exist";
        assertEquals(expectedErrMsg, errMsg);
        inputStream.close();
    } finally {
        if (cmpconfig.aliasExists("backUpAlias" + extractedAlias + "ForAliasTesting001122334455")) {
            cmpconfig.renameAlias("backUpAlias" + extractedAlias + "ForAliasTesting001122334455",
                    extractedAlias);
            this.globalConfigurationSession.saveConfiguration(ADMIN, cmpconfig);
        }
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageDispatcherSessionBean.java

License:Open Source License

private ASN1Primitive getDERObject(byte[] ba) throws IOException {
    ASN1InputStream ins = new ASN1InputStream(ba);
    try {//  ww w  .j av  a  2 s  .c  o  m
        ASN1Primitive obj = ins.readObject();
        return obj;
    } finally {
        ins.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

License:Open Source License

public static byte[] signPKIMessage(PKIMessage myPKIMessage, Collection<Certificate> signCertChain,
        PrivateKey signKey, String digestAlg, String provider)
        throws InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, SecurityException,
        SignatureException, CertificateEncodingException {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">signPKIMessage()");
    }/*w  w  w  .  j  av  a2  s  . c om*/
    CMPCertificate[] extraCerts = new CMPCertificate[signCertChain.size()];
    Iterator<Certificate> itr = signCertChain.iterator();
    int i = 0;
    while (itr.hasNext()) {
        X509Certificate tmp = (X509Certificate) itr.next();
        ASN1InputStream asn1InputStream = null;
        try {
            try {
                asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(tmp.getEncoded()));
                CMPCertificate signStruct = CMPCertificate.getInstance(asn1InputStream.readObject());
                extraCerts[i] = signStruct;
            } finally {
                asn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Caught unexpected IOException", e);
        }
        i++;
    }
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, extraCerts, signKey, digestAlg,
            provider);
    if (LOG.isTraceEnabled()) {
        LOG.trace("<signPKIMessage()");
    }
    // Return response as byte array 
    return CmpMessageHelper.pkiMessageToByteArray(myPKIMessage);

}

From source file:org.ejbca.core.protocol.cmp.CmpRaThrowAwayTest.java

License:Open Source License

@Test
public void testLegacyEncodedRequestOverride() throws Exception {
    reconfigureCA(false, false, false);//  w w  w.  jav  a 2  s  . com
    // Setup "Allow subject DN override" and "Allow certificate serial number override" in used cert profile
    reconfigureCertificateProfile(true, true);
    final String issuerDn = CertTools.getSubjectDN(getTestCACert(TESTCA_NAME));
    final X500Name issuerX500Name = new X500Name(issuerDn);
    final org.bouncycastle.asn1.crmf.CertTemplateBuilder certTemplate = new org.bouncycastle.asn1.crmf.CertTemplateBuilder();
    certTemplate.setIssuer(issuerX500Name);
    final KeyPair keyPair = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final String serialNumber = "88883311121333FF33012345";
    final byte[] transactionId = new byte[16];
    final byte[] senderNonce = new byte[16];
    final Random random = new Random();
    random.nextBytes(transactionId);
    random.nextBytes(senderNonce);
    final String subjectDn = "C=SE,O=PrimeKey,OU=Labs,CN=Sec_" + serialNumber;
    final X500Name subjectX500Name = CertTools.stringToBcX500Name(subjectDn, new TeletexNamingStyle(), false);
    certTemplate.setSubject(subjectX500Name);
    final byte[] bytes = keyPair.getPublic().getEncoded();
    final ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    final org.bouncycastle.asn1.ASN1InputStream asn1InputStream = new org.bouncycastle.asn1.ASN1InputStream(
            bIn);
    final org.bouncycastle.asn1.x509.SubjectPublicKeyInfo keyInfo = new org.bouncycastle.asn1.x509.SubjectPublicKeyInfo(
            (org.bouncycastle.asn1.ASN1Sequence) asn1InputStream.readObject());
    asn1InputStream.close();
    certTemplate.setPublicKey(keyInfo);
    // Request a custom certificate serial number
    certTemplate.setSerialNumber(new ASN1Integer(new BigInteger(serialNumber, 16)));
    final org.bouncycastle.asn1.crmf.ProofOfPossession myProofOfPossession = new org.bouncycastle.asn1.crmf.ProofOfPossession();
    final CertRequest certRequest = new CertRequest(4, certTemplate.build(), null);
    final AttributeTypeAndValue[] avs = { new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(PBE_SECRET)) };
    final CertReqMsg certReqMsg = new CertReqMsg(certRequest, myProofOfPossession, avs);
    final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg);
    PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder(2, new GeneralName(subjectX500Name),
            new GeneralName(new X500Name(issuerDn)));
    pkiHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    pkiHeader.setSenderNonce(new DEROctetString(senderNonce));
    pkiHeader.setTransactionID(new DEROctetString(transactionId));
    pkiHeader.setProtectionAlg(null);
    final DEROctetString senderKID = null;
    pkiHeader.setSenderKID(senderKID);
    final PKIBody pkiBody = new PKIBody(0, certReqMessages);
    final PKIMessage pkiMessage = new PKIMessage(pkiHeader.build(), pkiBody);
    final PKIMessage req = protectPKIMessage(pkiMessage, false, PBE_SECRET, "unusedKeyId", 567);
    assertNotNull("Request was not created properly.", req);
    final CertReqMessages initializationRequest = (CertReqMessages) req.getBody().getContent();
    final int requestId = initializationRequest.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue()
            .intValue();
    final byte[] reqBytes = req.getEncoded();
    final byte[] cmpResponse = sendCmpHttp(reqBytes, 200, configAlias);
    final X509Certificate cert = checkCmpCertRepMessage(subjectX500Name, this.caCertificate, cmpResponse,
            requestId);
    LOG.debug("Request:\n" + new String(CertTools.getPEMFromCertificateRequest(certRequest.getEncoded())));
    LOG.debug("Result:\n" + new String(
            CertTools.getPemFromCertificateChain(new ArrayList<Certificate>(Arrays.asList(cert)))));
    final byte[] requestSubjectyX500Principal = cert.getSubjectX500Principal().getEncoded();
    final byte[] responeSubjectyX500Principal = subjectX500Name.getEncoded();
    assertTrue("Requested X500Name was not returned the same way as requested.",
            Arrays.equals(requestSubjectyX500Principal, responeSubjectyX500Principal));
    // We cannot assume that the unique serial number index is enabled, and hence we cant be sure that our serial number override was allowed, but at least we can print it
    LOG.info("Requested serial number: " + serialNumber);
    LOG.info("Response serial number:  " + CertTools.getSerialNumberAsString(cert));
}

From source file:org.ejbca.core.protocol.cmp.CmpRAUnidTest.java

License:Open Source License

private void doTest(Connection dbConn) throws Exception {

    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    final String unid;
    {//from w w w .  j a v a2s . c o  m
        // In this test SUBJECT_DN contains special, escaped characters to verify
        // that that works with CMP RA as well
        final PKIMessage one = genCertReq(CmpRAUnidTest.issuerDN, SUBJECT_DN, this.keys, this.cacert, nonce,
                transid, true, null, null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, CPNAME, 567);
        assertNotNull(req);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, configAlias);

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            PKIBody body = respObject.getBody();
            if (body.getContent() instanceof ErrorMsgContent) {
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                log.error(errMsg);
                fail("CMP ErrorMsg received: " + errMsg);
                unid = null;
            } else {
                checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid,
                        false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                final X509Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqId);
                final X500Name name = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());
                unid = IETFUtils.valueToString(name.getRDNs(BCStyle.SN)[0].getFirst().getValue());
                log.debug("Unid received in certificate response: " + unid);
            }
        } finally {
            inputStream.close();
        }
    }
    {
        final PreparedStatement ps = dbConn.prepareStatement("select fnr from UnidFnrMapping where unid=?");
        ps.setString(1, unid);
        final ResultSet result = ps.executeQuery();
        assertTrue("Unid '" + unid + "' not found in DB.", result.next());
        final String fnr = result.getString(1);
        result.close();
        ps.close();
        log.debug("FNR read from DB: " + fnr);
        assertEquals("Right FNR not found in DB.", FNR, fnr);
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage confirm = genCertConfirm(SUBJECT_DN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        final PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, CPNAME, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req1);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, configAlias);
        checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false,
                PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(SUBJECT_DN, this.cacert, resp);
    }
}