Example usage for org.bouncycastle.asn1.cmp PKIStatus GRANTED

List of usage examples for org.bouncycastle.asn1.cmp PKIStatus GRANTED

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIStatus GRANTED.

Prototype

int GRANTED

To view the source code for org.bouncycastle.asn1.cmp PKIStatus GRANTED.

Click Source Link

Usage

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

License:Open Source License

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/*from w  ww.  j a v  a 2 s.com*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

From source file:ee.ria.xroad.proxy.messagelog.TimestamperUtil.java

License:Open Source License

static TimeStampResponse getTimestampResponse(InputStream in) throws Exception {
    TimeStampResp response = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());

    if (response == null) {
        throw new RuntimeException("Could not read time-stamp response");
    }/*from  w  w w .  j  a  va 2 s.  c  om*/

    BigInteger status = response.getStatus().getStatus();

    log.trace("getTimestampDer() - TimeStampResp.status: {}", status);

    if (!PKIStatus.granted.getValue().equals(status) && !PKIStatus.grantedWithMods.getValue().equals(status)) {
        PKIFreeText statusString = response.getStatus().getStatusString();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < statusString.size(); i++) {
            if (i > 0) {
                sb.append(", ");
            }

            sb.append("\"" + statusString.getStringAt(i) + "\"");
        }

        log.error("getTimestampDer() - TimeStampResp.status is not "
                + "\"granted\" neither \"grantedWithMods\": {}, {}", status, sb);

        throw new RuntimeException("TimeStampResp.status: " + status + ", .statusString: " + sb);
    }

    return new TimeStampResponse(response);
}

From source file:ee.sk.digidoc.factory.BouncyCastleTimestampFactory.java

License:Open Source License

/**
 * Verifies this one timestamp//from ww w.ja v a 2  s  . co  m
 * @param ts TimestampInfo object
 * @param tsaCert TSA certificate
 * @returns result of verification
 */
public boolean verifyTimestamp(TimestampInfo ts, X509Certificate tsaCert) throws DigiDocException {
    boolean bOk = false;

    if (m_logger.isDebugEnabled())
        m_logger.debug("Verifying TS: " + ts.getId() + " nr: " + ts.getSerialNumber());
    if (!SignedDoc.compareDigests(ts.getMessageImprint(), ts.getHash())) {
        m_logger.error("TS digest: " + Base64Util.encode(ts.getMessageImprint()) + " real digest: "
                + Base64Util.encode(ts.getHash()));
        throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                "Bad digest for timestamp: " + ts.getId(), null);
    }
    TimeStampResponse resp = ts.getTimeStampResponse();
    if (resp != null) {
        if (m_logger.isDebugEnabled())
            m_logger.debug("TS status: " + resp.getStatus());
        if (resp.getStatus() == PKIStatus.GRANTED || resp.getStatus() == PKIStatus.GRANTED_WITH_MODS) {
            try {
                resp.getTimeStampToken().validate(tsaCert, "BC");
                bOk = true;
            } catch (Exception ex) {
                bOk = false;
                m_logger.error("Timestamp verification error: " + ex);
                throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                        "Invalid timestamp: " + ex.getMessage(), ex);
            }
        } else
            throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                    "Invalid timestamp status: " + resp.getStatus(), null);
    }

    return bOk;
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createInitializationRespons1(byte[] senderNonce, byte[] transactionId) throws CMPException,
        CertificateEncodingException, OperatorCreationException, PKICMPMessageException, IOException {
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(pki.getTestUser3Cert());

    // Body//from   www. ja  v a2s  .  c o m
    CertResponse certResponse = new CertResponse(new ASN1Integer(0), new PKIStatusInfo(PKIStatus.granted),
            new CertifiedKeyPair(
                    new CertOrEncCert(new CMPCertificate(x509CertificateHolder.toASN1Structure()))),
            null);
    CertResponse[] certResponses = new CertResponse[1];
    certResponses[0] = certResponse;

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REP,
            new CertRepMessage(pkiKeyStoreCA.getCMPCertificateChain(), certResponses));

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createInitializationRespons2(byte[] senderNonce, byte[] transactionId) throws CMPException,
        CertificateEncodingException, OperatorException, PKICMPMessageException, IOException, CRMFException {
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(pki.getTestUser3Cert());

    //encrypt Private Key
    KeyWrapper keyWrapper = new JceAsymmetricKeyWrapper(pkiKeyStoreCA.getRecipientCertificate().getPublicKey())
            .setProvider("BC");
    OutputEncryptor encryptor = new JceCRMFEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC")
            .build();/*  ww  w  .  ja  va 2 s . c om*/
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    OutputStream eOut = encryptor.getOutputStream(bOut);
    eOut.write(pki.getTestUser3CertPrivateKey().getEncoded());
    eOut.close();

    AlgorithmIdentifier intendedAlg = null;
    AlgorithmIdentifier symmAlg = encryptor.getAlgorithmIdentifier();
    DERBitString encSymmKey;
    keyWrapper.generateWrappedKey(encryptor.getKey());
    encSymmKey = new DERBitString(keyWrapper.generateWrappedKey(encryptor.getKey()));

    AlgorithmIdentifier keyAlg = keyWrapper.getAlgorithmIdentifier();
    ASN1OctetString valueHint = null;
    DERBitString encValue = new DERBitString(bOut.toByteArray());

    EncryptedValue encryptedPrivateKey = new EncryptedValue(intendedAlg, symmAlg, encSymmKey, keyAlg, valueHint,
            encValue);

    // Body
    CertResponse certResponse = new CertResponse(new ASN1Integer(0), new PKIStatusInfo(PKIStatus.granted),
            new CertifiedKeyPair(new CertOrEncCert(new CMPCertificate(x509CertificateHolder.toASN1Structure())),
                    encryptedPrivateKey, null),
            null);
    CertResponse[] certResponses = new CertResponse[1];
    certResponses[0] = certResponse;

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REP,
            new CertRepMessage(pkiKeyStoreCA.getCMPCertificateChain(), certResponses));

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createRevocationRespons1(byte[] senderNonce, byte[] transactionId)
        throws CRLException, CMPException, CertificateEncodingException, OperatorCreationException,
        PKICMPMessageException, IOException {

    RevRepContentBuilder revRepContentBuilder = new RevRepContentBuilder();
    revRepContentBuilder.add(new PKIStatusInfo(PKIStatus.granted),
            new CertId(new GeneralName(JcaX500NameUtil.getIssuer(pki.getRevokedCert())),
                    pki.getRevokedCert().getSerialNumber()));
    revRepContentBuilder.addCrl(new JcaX509CRLHolder(pki.getX509CRL()).toASN1Structure());

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_REVOCATION_REP, revRepContentBuilder.build());

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;/*from   w w  w  . j a  v a  2 s  .  c o m*/
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(),
            getSenderNonce(), getRecipientNonce(), getTransactionId());
    PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
    if (status != ResponseStatus.SUCCESS && status != ResponseStatus.GRANTED_WITH_MODS) {
        if (log.isDebugEnabled()) {
            log.debug("Creating a rejection message");
        }/*from  w  w  w.  jav  a2  s  .  c o m*/
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, null,
                CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        if (failText != null && failInfo != null) {
            myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(failText),
                    CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        }
    }
    RevRepContentBuilder revBuilder = new RevRepContentBuilder();
    revBuilder.add(myPKIStatusInfo);
    RevRepContent myRevrepMessage = revBuilder.build();

    PKIBody myPKIBody = new PKIBody(CmpPKIBodyConstants.REVOCATIONRESPONSE, myRevrepMessage);
    PKIMessage myPKIMessage;

    if ((getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null)) {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digestAlg));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        try {
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digestAlg,
                    provider);
        } catch (CertificateEncodingException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SecurityException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SignatureException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        }
    }
    return true;
}

From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, final ParameterContainer parameters) throws Exception {
    String dest = parameters.get(DESTINATION_KEY);
    if (dest == null) {
        dest = "dest";
        new File("./" + dest).mkdirs();
        log.info("Using default destination directory: ./dest/");
    }//  w  ww .  j a  v  a2 s  .  co  m

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(response));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    if (respObject == null) {
        log.error("ERROR. Cannot construct the response object");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();

    if (tag == PKIBody.TYPE_INIT_REP) {
        CertRepMessage c = (CertRepMessage) body.getContent();
        CertResponse resp = c.getResponse()[0];
        PKIStatusInfo status = resp.getStatus();
        if (status.getStatus().intValue() == PKIStatus.GRANTED) {
            final X509Certificate cert = getCertFromResponse(resp);
            final ArrayList<Certificate> certs = new ArrayList<>();
            certs.add(cert);
            final byte[] certBytes = CertTools.getPemFromCertificateChain(certs);

            String certFileName = getDestinationCertFile(dest, parameters.get(SUBJECTDN_KEY));
            final FileOutputStream fos = new FileOutputStream(new File(certFileName));
            fos.write(certBytes);
            fos.close();
            log.info("CRMF request successful. Received certificate stored in " + certFileName);
            return CommandResult.SUCCESS;
        } else {
            final String errMsg = status.getStatusString().getStringAt(0).getString();
            log.error("Recieved CRMF response with status '" + status.getStatus().intValue()
                    + "' and error message: " + errMsg);
        }
    } else if (tag == PKIBody.TYPE_ERROR) {
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        log.error("Revceived CMP Error Message: " + errMsg);
    } else {
        log.error("Received PKIMessage with body tag " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, ParameterContainer parameters) throws Exception {
    String dest = parameters.get(DESTINATION_KEY);
    if (dest == null) {
        dest = "dest";
        new File("./" + dest).mkdirs();
        log.info("Using default destination directory: ./dest/");
    }//  ww w .ja va  2 s.c  o m

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(response));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    if (respObject == null) {
        log.error("Cannot construct response object");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();
    if (tag == PKIBody.TYPE_KEY_UPDATE_REP) {
        CertRepMessage c = (CertRepMessage) body.getContent();
        CertResponse resp = c.getResponse()[0];
        PKIStatusInfo status = resp.getStatus();

        if (status.getStatus().intValue() == PKIStatus.GRANTED) {
            final X509Certificate cert = getCertFromResponse(resp);
            final ArrayList<Certificate> certs = new ArrayList<>();
            certs.add(cert);
            final byte[] certBytes = CertTools.getPemFromCertificateChain(certs);

            String certFileName = getDestinationCertFile(dest, parameters.get(SUBJECTDN_KEY));
            final FileOutputStream fos = new FileOutputStream(new File(certFileName));
            fos.write(certBytes);
            fos.close();
            log.info("CRMF request successful. Received certificate stored in " + certFileName);
            return CommandResult.SUCCESS;
        } else {
            final String errMsg = status.getStatusString().getStringAt(0).getString();
            log.error("Recieved CRMF response with status '" + status.getStatus().intValue()
                    + "' and error message: " + errMsg);
        }

    } else if (tag == PKIBody.TYPE_ERROR) {
        log.error("Error response was recieved");
        ErrorMsgContent c = (ErrorMsgContent) body.getContent();
        PKIStatusInfo info = c.getPKIStatusInfo();
        log.error("Error message: " + info.getStatusString().getStringAt(0));
    } else {
        log.error("Recieved response with body type(See PKIBody.java): " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}