Example usage for org.bouncycastle.asn1.cmp PKIMessage getExtraCerts

List of usage examples for org.bouncycastle.asn1.cmp PKIMessage getExtraCerts

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIMessage getExtraCerts.

Prototype

public CMPCertificate[] getExtraCerts() 

Source Link

Usage

From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java

License:Open Source License

private Certificate getExtraCert(final PKIMessage msg) {
    final CMPCertificate[] extraCerts = msg.getExtraCerts();
    if ((extraCerts == null) || (extraCerts.length == 0)) {
        if (log.isDebugEnabled()) {
            log.debug("There is no certificate in the extraCert field in the PKIMessage");
        }//from   w  w  w.  j a  v  a2  s  . co  m
        return null;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("A certificate is found in the extraCert field in the CMP message");
        }
    }

    //Read the extraCert
    CMPCertificate cmpcert = extraCerts[0];
    Certificate excert = null;
    try {
        excert = CertTools.getCertfromByteArray(cmpcert.getEncoded());
        if (log.isDebugEnabled()) {
            log.debug("Obtaning the certificate from extraCert field was done successfully");
        }
    } catch (CertificateException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage(), e);
        }
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage(), e);
        }
    }
    return excert;
}

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

License:Open Source License

public static byte[] protectPKIMessageWithPBE(PKIMessage msg, String keyId, String raSecret, String digestAlgId,
        String macAlgId, int iterationCount)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">protectPKIMessageWithPBE()");
    }//from  ww  w  . jav  a 2s. c o m
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    byte[] keyIdBytes;
    try {
        keyIdBytes = keyId.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        keyIdBytes = keyId.getBytes();
        LOG.info("UTF-8 not available, using platform default encoding for keyIdBytes.");
    }
    head.setSenderKID(new DEROctetString(keyIdBytes));
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(digestAlgId);
    // iterations, usually something like 1024
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(macAlgId);
    // We need some random bytes for the nonce
    byte[] saltbytes = createSenderNonce();
    DEROctetString derSalt = new DEROctetString(saltbytes);

    // Create the new protected return message
    //String objectId = "1.2.840.113533.7.66.13" = passwordBasedMac;
    String objectId = CMPObjectIdentifiers.passwordBasedMac.getId();
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);

    // Calculate the protection bits
    byte[] rasecret = raSecret.getBytes();
    byte[] basekey = new byte[rasecret.length + saltbytes.length];
    System.arraycopy(rasecret, 0, basekey, 0, rasecret.length);
    System.arraycopy(saltbytes, 0, basekey, rasecret.length, saltbytes.length);
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }

    PKIHeader pkiHeader = head.build();
    // Do the mac
    String macOid = macAlg.getAlgorithm().getId();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(pkiHeader, msg.getBody()); //ret.getProtectedBytes();
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    if (LOG.isTraceEnabled()) {
        LOG.trace("<protectPKIMessageWithPBE()");
    }
    // Return response as byte array 
    return CmpMessageHelper
            .pkiMessageToByteArray(new PKIMessage(pkiHeader, msg.getBody(), bs, msg.getExtraCerts()));
}

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

License:Open Source License

@Test
public void test11IncludingCertChainInSignedCMPResponse() throws Exception {

    //---------- Create SubCA signed by testx509ca (rootCA) ------------- //
    String subcaDN = "CN=SubTestCA";
    int subcaID = subcaDN.hashCode();
    int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(ADMIN, null, true, false, subcaDN, "1024");
    final String username = "cmptest";
    try {/*from   w  w w .  j  a v  a  2s. co  m*/
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA256_WITH_RSA, AlgorithmConstants.SIGALG_SHA256_WITH_RSA);
        final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2);
        extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
        String caname = CertTools.getPartFromDN(subcaDN, "CN");
        boolean ldapOrder = !CertTools.isDNReversed(subcaDN);
        X509CAInfo cainfo = new X509CAInfo(subcaDN, caname, CAConstants.CA_ACTIVE,
                CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 3650, this.caid,
                this.testx509ca.getCertificateChain(), catoken);
        cainfo.setDescription("JUnit RSA SubCA");
        cainfo.setExtendedCAServiceInfos(extendedCaServices);
        cainfo.setUseLdapDnOrder(ldapOrder);
        cainfo.setCmpRaAuthSecret("foo123");

        CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CAAdminSessionRemote.class);
        caAdminSession.createCA(ADMIN, cainfo);
        assertTrue(this.caSession.existsCa(subcaID));
        cainfo = (X509CAInfo) this.caSession.getCAInfo(ADMIN, subcaID);
        X509Certificate subcaCert = (X509Certificate) cainfo.getCertificateChain().iterator().next();

        // --------- Create a user ----------------- //
        boolean userExists = false;
        final X500Name userDN = new X500Name("C=SE,O=PrimeKey,CN=cmptest");
        EndEntityInformation user = new EndEntityInformation("cmptest", userDN.toString(), subcaID, null,
                "cmptest@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER),
                //                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, 
                this.eepDnOverrideId, this.cpDnOverrideId, SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        try {
            this.endEntityManagementSession.addUser(ADMIN, user, true);
            log.debug("created user: cmptest, foo123, " + userDN);
        } catch (Exception e) {
            userExists = true;
        }

        if (userExists) {
            log.debug("User cmptest already exists.");
            this.endEntityManagementSession.changeUser(ADMIN, user, true);
            this.endEntityManagementSession.setUserStatus(ADMIN, "cmptest", EndEntityConstants.STATUS_NEW);
            log.debug("Reset status to NEW");
        }

        assertTrue(this.endEntityManagementSession.existsUser("cmptest"));
        EndEntityAccessSessionRemote eeAccessSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(EndEntityAccessSessionRemote.class);
        EndEntityInformation ee = eeAccessSession.findUser(ADMIN, "cmptest");
        assertEquals(subcaID, ee.getCAId());

        // -------- generate and send a CMP request -------------- //
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        PKIMessage req = genCertReq(subcaDN, userDN, this.keys, subcaCert, nonce, transid, false, null, null,
                null, null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, subcaDN, userDN, subcaCert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        final X509Certificate cert = checkCmpCertRepMessage(userDN, subcaCert, resp, reqId);
        assertNotNull(cert);

        // ------- Check that the entire certificate chain is in the extraCerts field in the response
        PKIMessage respMsg = null;
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            respMsg = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull(respMsg);

        CMPCertificate[] certChain = respMsg.getExtraCerts();
        assertEquals(2, certChain.length);
        assertEquals(subcaDN, certChain[0].getX509v3PKCert().getSubject().toString());
        assertEquals(ISSUER_DN, certChain[1].getX509v3PKCert().getSubject().toString());
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, username);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete user: " + username);
        }
        CryptoTokenTestUtils.removeCryptoToken(null, cryptoTokenId);
        // Remove CA certificate of CA that we will remove
        Collection<Certificate> certs = this.caSession.getCAInfo(ADMIN, subcaID).getCertificateChain();
        this.internalCertStoreSession.removeCertificate(certs.iterator().next());
        // Remove the CA itself
        this.caSession.removeCA(ADMIN, subcaID);
    }
}