Example usage for org.bouncycastle.asn1.cmp PKIBody TYPE_ERROR

List of usage examples for org.bouncycastle.asn1.cmp PKIBody TYPE_ERROR

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIBody TYPE_ERROR.

Prototype

int TYPE_ERROR

To view the source code for org.bouncycastle.asn1.cmp PKIBody TYPE_ERROR.

Click Source Link

Usage

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

License:Open Source License

/**
 * 1- Sends a CRMF request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a CRMF request signed by RA1Admin to RA2. Expected: Fail
 * //  w  ww.  j  av  a  2 s .c  om
 * @throws Exception
 */
@Test
public void test01RA1FailedCRMF() throws Exception {

    // Send CRMF message signed by RA2Admin to RA1
    String testUsername = "ra1testuser";
    X500Name testUserDN = new X500Name("CN=" + testUsername);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid,
            false, null, null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    CMPCertificate[] extraCert = getCMPCert(ra2admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra2admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    boolean verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
    checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    PKIBody body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    // Send CRMF message signed by RA1Admin to RA2
    testUsername = "ra2testuser";
    testUserDN = new X500Name("CN=" + testUsername);
    keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null,
            null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    extraCert = getCMPCert(ra1admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra1admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(msg);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, RA2_ALIAS);
    checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "'CN=" + RA1_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

}

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

License:Open Source License

/**
 * 1- Sends a revocation request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a revocation request signed by RA1Admin to RA1. Expected: Success
 * //from w  w w . j av  a 2  s. c  om
 * @throws Exception
 */
@Test
public void test03RevocationRequest() throws Exception {

    String username = "ra1testuser";
    String fingerprintCert = null;
    try {

        // Issue a cert by CA1
        String userDN = "CN=" + username;
        createUser(username, userDN, "foo123", true, ca1.getCAId(),
                endEntityProfileSession.getEndEntityProfileId(EEP1),
                certProfileSession.getCertificateProfileId(CP1));
        KeyPair userkeys = KeyTools.genKeys("1024", "RSA");
        Certificate cert = signSession.createCertificate(ADMIN, username, "foo123",
                new PublicKeyWrapper(userkeys.getPublic()));
        assertNotNull("No certificate to revoke.", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert),
                ca1.getCACertificate(), nonce, transid, false, pAlg, null);
        assertNotNull("Generating revocation request failed.", msg);

        // Sign the revocation request with RA2 Admin
        CMPCertificate[] extraCert = getCMPCert(ra2admincert);
        PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert,
                ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed.", protectedMsg);

        // Send the CMP request to RA1. Expected: Fail
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, null);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        final PKIMessage respObject;
        try {
            respObject = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull("Reading CMP response failed.", respObject);
        PKIBody body = respObject.getBody();
        assertEquals(PKIBody.TYPE_ERROR, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
        assertEquals(expectedErrMsg, errMsg);

        // Sign the revocation request with RA1 Admin
        extraCert = getCMPCert(ra1admincert);
        protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed.", protectedMsg);

        // Send the CMP request to RA1. Expected: Success
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, RA1_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ca1.getSubjectDN(), CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);
    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused);
    }
}

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

License:Open Source License

/**
 * Sends a revocation request signed by RA2Admin to revoke a certificate issued by a CA RA2Admin is not authorized to. Expected: Fail
 * /*  www  .  j  a va 2s. c o  m*/
 * @throws Exception
 */
@Test
public void test04RevocationRequest() throws Exception {

    String username = "ra1testuser";
    String fingerprintCert = null;
    try {

        // Issue a cert by CA1
        String userDN = "CN=" + username;
        createUser(username, userDN, "foo123", true, ca1.getCAId(),
                endEntityProfileSession.getEndEntityProfileId(EEP1),
                certProfileSession.getCertificateProfileId(CP1));
        KeyPair userkeys = KeyTools.genKeys("1024", "RSA");
        Certificate cert = signSession.createCertificate(ADMIN, username, "foo123",
                new PublicKeyWrapper(userkeys.getPublic()));
        assertNotNull("No certificate to revoke.", cert);
        fingerprintCert = CertTools.getFingerprintAsString(cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert),
                ca1.getCACertificate(), nonce, transid, false, pAlg, null);
        assertNotNull("Generating revocation request failed.", msg);

        // Sign the revocation request with RA2 Admin
        CMPCertificate[] extraCert = getCMPCert(ra2admincert);
        PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert,
                ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC");
        assertNotNull("Signing CMP message failed", protectedMsg);

        // Send the CMP request to RA2. Expected: Fail
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedMsg);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS);
        checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(),
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, null);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        final PKIMessage respObject;
        try {
            respObject = PKIMessage.getInstance(asn1InputStream.readObject());
        } finally {
            asn1InputStream.close();
        }
        assertNotNull("Reading CMP response failed.", respObject);
        PKIBody body = respObject.getBody();
        assertEquals(PKIBody.TYPE_ERROR, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
        assertEquals(expectedErrMsg, errMsg);

    } finally {
        internalCertStoreSession.removeCertificate(fingerprintCert);
        endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused);
    }
}

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/");
    }/* ww w .j  ava 2s  .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. j av 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("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;
}

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

License:Open Source License

@Override
public CommandResult handleCMPResponse(byte[] response, ParameterContainer parameters) throws Exception {
    PKIMessage respObject = null;/*from   ww w . j  av  a 2s.c om*/
    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_REVOCATION_REP) {
        log.info("Revocation response was recieved");
        RevRepContent n = (RevRepContent) body.getContent();
        PKIStatusInfo info = n.getStatus()[0];
        if (info.getStatus().intValue() == 0) {
            log.info("Revocation request have succeeded");
            return CommandResult.SUCCESS;
        } else {
            log.error("Revocation request failed with status (See PKIStatusInfo.java): "
                    + info.getStatus().intValue());
        }
    } 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).getString());
    } else {
        log.error("Recieved response with body type(See PKIBody.java): " + tag);
    }
    return CommandResult.FUNCTIONAL_FAILURE;
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

protected PKIResponse signAndSend(final PKIMessage request, final RequestResponseDebug debug)
        throws CmpRequestorException {
    PKIMessage _request;//from  w  w w.j a  v  a  2  s. c  o m
    if (signRequest) {
        _request = sign(request);
    } else {
        _request = request;
    }

    if (responderCert == null) {
        throw new CmpRequestorException("CMP responder is not configured");
    }

    byte[] encodedRequest;
    try {
        encodedRequest = _request.getEncoded();
    } catch (IOException e) {
        LOG.error("error while encode the PKI request {}", _request);
        throw new CmpRequestorException(e.getMessage(), e);
    }

    RequestResponsePair reqResp = null;
    if (debug != null) {
        reqResp = new RequestResponsePair();
        debug.add(reqResp);
        reqResp.setRequest(encodedRequest);
    }

    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException e) {
        LOG.error("error while send the PKI request {} to server", _request);
        throw new CmpRequestorException("TRANSPORT_ERROR", e);
    }

    if (reqResp != null) {
        reqResp.setResponse(encodedResponse);
    }

    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("error while decode the received PKI message: {}", Hex.toHexString(encodedResponse));
        }
        throw new CmpRequestorException(e.getMessage(), e);
    }

    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = respHeader.getTransactionID();
    GeneralName recipient = respHeader.getRecipient();
    if (sender.equals(recipient) == false) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, recipient);
    }

    PKIResponse ret = new PKIResponse(response);
    if (response.hasProtection()) {
        try {
            ProtectionVerificationResult verifyProtection = verifyProtection(Hex.toHexString(tid.getOctets()),
                    response, responderCert);
            ret.setProtectionVerificationResult(verifyProtection);
        } catch (InvalidKeyException | OperatorCreationException | CMPException e) {
            throw new CmpRequestorException(e.getMessage(), e);
        }
    } else if (signRequest) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new CmpRequestorException("response is not signed");
        }
    }

    return ret;
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

private ASN1Encodable extractGeneralRepContent(final PKIResponse response, final String exepectedType,
        final boolean requireProtectionCheck) throws CmpRequestorException, PKIErrorException {
    if (requireProtectionCheck) {
        checkProtection(response);/*  w  ww. ja  va2 s  .  co m*/
    }

    PKIBody respBody = response.getPkiMessage().getBody();
    int bodyType = respBody.getType();

    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = (ErrorMsgContent) respBody.getContent();
        throw new CmpRequestorException(SecurityUtil.formatPKIStatusInfo(content.getPKIStatusInfo()));
    } else if (PKIBody.TYPE_GEN_REP != bodyType) {
        throw new CmpRequestorException("unknown PKI body type " + bodyType + " instead the exceptected ["
                + PKIBody.TYPE_GEN_REP + ", " + PKIBody.TYPE_ERROR + "]");
    }

    GenRepContent genRep = (GenRepContent) respBody.getContent();

    InfoTypeAndValue[] itvs = genRep.toInfoTypeAndValueArray();
    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue _itv : itvs) {
            if (exepectedType.equals(_itv.getInfoType().getId())) {
                itv = _itv;
                break;
            }
        }
    }
    if (itv == null) {
        throw new CmpRequestorException("the response does not contain InfoTypeAndValue " + exepectedType);
    }

    return itv.getInfoValue();
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private CRLResultType evaluateCRLResponse(final PKIResponse response, final Integer xipkiAction)
        throws CmpRequestorException, PKIErrorException {
    checkProtection(response);//from  www  . j a  v  a  2 s  . c om

    PKIBody respBody = response.getPkiMessage().getBody();
    int bodyType = respBody.getType();

    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = (ErrorMsgContent) respBody.getContent();
        throw new PKIErrorException(content.getPKIStatusInfo());
    } else if (PKIBody.TYPE_GEN_REP != bodyType) {
        throw new CmpRequestorException("unknown PKI body type " + bodyType + " instead the exceptected ["
                + PKIBody.TYPE_GEN_REP + ", " + PKIBody.TYPE_ERROR + "]");
    }

    ASN1ObjectIdentifier expectedType = xipkiAction == null ? CMPObjectIdentifiers.it_currentCRL
            : ObjectIdentifiers.id_xipki_cmp;

    GenRepContent genRep = (GenRepContent) respBody.getContent();

    InfoTypeAndValue[] itvs = genRep.toInfoTypeAndValueArray();
    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            if (expectedType.equals(m.getInfoType())) {
                itv = m;
                break;
            }
        }
    }
    if (itv == null) {
        throw new CmpRequestorException("the response does not contain InfoTypeAndValue " + expectedType);
    }

    ASN1Encodable certListAsn1Object;
    if (xipkiAction == null) {
        certListAsn1Object = itv.getInfoValue();
    } else {
        certListAsn1Object = extractXipkiActionContent(itv.getInfoValue(), xipkiAction);
    }

    CertificateList certList = CertificateList.getInstance(certListAsn1Object);

    X509CRL crl;
    try {
        crl = new X509CRLObject(certList);
    } catch (CRLException e) {
        throw new CmpRequestorException("returned CRL is invalid: " + e.getMessage());
    }

    CRLResultType result = new CRLResultType();
    result.setCRL(crl);
    return result;
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private RevokeCertResultType parse(final PKIResponse response,
        final List<? extends IssuerSerialEntryType> reqEntries)
        throws CmpRequestorException, PKIErrorException {
    checkProtection(response);/*from  w  w  w.j  ava  2s  .co m*/

    PKIBody respBody = response.getPkiMessage().getBody();
    int bodyType = respBody.getType();

    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = (ErrorMsgContent) respBody.getContent();
        throw new PKIErrorException(content.getPKIStatusInfo());
    } else if (PKIBody.TYPE_REVOCATION_REP != bodyType) {
        throw new CmpRequestorException("unknown PKI body type " + bodyType + " instead the exceptected ["
                + PKIBody.TYPE_REVOCATION_REP + ", " + PKIBody.TYPE_ERROR + "]");
    }

    RevRepContent content = (RevRepContent) respBody.getContent();
    PKIStatusInfo[] statuses = content.getStatus();
    if (statuses == null || statuses.length != reqEntries.size()) {
        throw new CmpRequestorException("incorrect number of status entries in response '" + statuses.length
                + "' instead the exceptected '" + reqEntries.size() + "'");
    }

    CertId[] revCerts = content.getRevCerts();

    RevokeCertResultType result = new RevokeCertResultType();
    for (int i = 0; i < statuses.length; i++) {
        PKIStatusInfo statusInfo = statuses[i];
        int status = statusInfo.getStatus().intValue();
        IssuerSerialEntryType re = reqEntries.get(i);

        if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
            PKIFreeText text = statusInfo.getStatusString();
            String statusString = text == null ? null : text.getStringAt(0).getString();

            ResultEntryType resultEntry = new ErrorResultEntryType(re.getId(), status,
                    statusInfo.getFailInfo().intValue(), statusString);
            result.addResultEntry(resultEntry);
            continue;
        }

        CertId certId = null;
        if (revCerts != null) {
            for (CertId _certId : revCerts) {
                if (re.getIssuer().equals(_certId.getIssuer().getName())
                        && re.getSerialNumber().equals(_certId.getSerialNumber().getValue())) {
                    certId = _certId;
                    break;
                }
            }
        }

        if (certId == null) {
            LOG.warn("certId is not present in response for (issuer='{}', serialNumber={})",
                    X509Util.getRFC4519Name(re.getIssuer()), re.getSerialNumber());
            certId = new CertId(new GeneralName(re.getIssuer()), re.getSerialNumber());
            continue;
        }

        ResultEntryType resultEntry = new RevokeCertResultEntryType(re.getId(), certId);
        result.addResultEntry(resultEntry);
    }

    return result;
}