Example usage for org.bouncycastle.asn1.cmp GenRepContent GenRepContent

List of usage examples for org.bouncycastle.asn1.cmp GenRepContent GenRepContent

Introduction

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

Prototype

public GenRepContent(InfoTypeAndValue[] itvs) 

Source Link

Usage

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

private PKIBody cmpGeneralMsg(final PKIHeaderBuilder respHeader, final CmpControl cmpControl,
        final PKIHeader reqHeader, final PKIBody reqBody, final CmpRequestorInfo requestor, final String user,
        final ASN1OctetString tid, final AuditEvent auditEvent) throws InsuffientPermissionException {
    GenMsgContent genMsgBody = (GenMsgContent) reqBody.getContent();
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;/*from ww  w.  jav a2s . c  o m*/
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue _itv : itvs) {
            String itvType = _itv.getInfoType().getId();
            if (knownGenMsgIds.contains(itvType)) {
                itv = _itv;
                break;
            }
        }
    }

    if (itv == null) {
        String statusMessage = "PKIBody type " + PKIBody.TYPE_GEN_MSG + " is only supported with the sub-types "
                + knownGenMsgIds.toString();
        return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
    }

    InfoTypeAndValue itvResp = null;
    ASN1ObjectIdentifier infoType = itv.getInfoType();

    int failureInfo;
    try {
        X509CA ca = getCA();
        if (CMPObjectIdentifiers.it_currentCRL.equals(infoType)) {
            addAutitEventType(auditEvent, "CRL_DOWNLOAD");
            checkPermission(requestor, Permission.GET_CRL);
            CertificateList crl = ca.getCurrentCRL();

            if (itv.getInfoValue() == null) { // as defined in RFC 4210
                crl = ca.getCurrentCRL();
            } else {
                // xipki extension
                ASN1Integer crlNumber = ASN1Integer.getInstance(itv.getInfoValue());
                crl = ca.getCRL(crlNumber.getPositiveValue());
            }

            if (crl == null) {
                String statusMessage = "no CRL is available";
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
            }

            itvResp = new InfoTypeAndValue(infoType, crl);
        } else if (ObjectIdentifiers.id_xipki_cmp.equals(infoType)) {
            ASN1Encodable asn1 = itv.getInfoValue();
            ASN1Integer asn1Code = null;
            ASN1Encodable reqValue = null;

            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
                asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0));
                if (seq.size() > 1) {
                    reqValue = seq.getObjectAt(1);
                }
            } catch (IllegalArgumentException e) {
                String statusMessage = "invalid value of the InfoTypeAndValue for "
                        + ObjectIdentifiers.id_xipki_cmp.getId();
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            }

            ASN1Encodable respValue;

            int action = asn1Code.getPositiveValue().intValue();
            switch (action) {
            case XipkiCmpConstants.ACTION_GEN_CRL:
                addAutitEventType(auditEvent, "CRL_GEN_ONDEMAND");
                checkPermission(requestor, Permission.GEN_CRL);
                X509CRL _crl = ca.generateCRLonDemand(auditEvent);
                if (_crl == null) {
                    String statusMessage = "CRL generation is not activated";
                    return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure,
                            statusMessage);
                } else {
                    respValue = CertificateList.getInstance(_crl.getEncoded());
                }
                break;
            case XipkiCmpConstants.ACTION_GET_CRL_WITH_SN:
                addAutitEventType(auditEvent, "CRL_DOWNLOAD_WITH_SN");
                checkPermission(requestor, Permission.GET_CRL);

                ASN1Integer crlNumber = ASN1Integer.getInstance(reqValue);
                respValue = ca.getCRL(crlNumber.getPositiveValue());
                if (respValue == null) {
                    String statusMessage = "no CRL is available";
                    return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure,
                            statusMessage);
                }
                break;
            case XipkiCmpConstants.ACTION_GET_CAINFO:
                addAutitEventType(auditEvent, "GET_SYSTEMINFO");
                Set<Integer> acceptVersions = new HashSet<>();
                if (reqValue != null) {
                    ASN1Sequence seq = DERSequence.getInstance(reqValue);
                    int size = seq.size();
                    for (int i = 0; i < size; i++) {
                        ASN1Integer a = ASN1Integer.getInstance(seq.getObjectAt(i));
                        acceptVersions.add(a.getPositiveValue().intValue());
                    }
                }

                if (CollectionUtil.isEmpty(acceptVersions)) {
                    acceptVersions.add(1);
                }

                String systemInfo = getSystemInfo(requestor, acceptVersions);
                respValue = new DERUTF8String(systemInfo);
                break;
            case XipkiCmpConstants.ACTION_REMOVE_EXPIRED_CERTS:
                checkPermission(requestor, Permission.REMOVE_CERT);

                String info = removeExpiredCerts(requestor, itv.getInfoValue());
                respValue = new DERUTF8String(info);
                break;
            default:
                String statusMessage = "unsupported XiPKI action code '" + action + "'";
                return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            } // end switch(action)

            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(asn1Code);
            if (respValue != null) {
                v.add(respValue);
            }
            itvResp = new InfoTypeAndValue(infoType, new DERSequence(v));
        }

        GenRepContent genRepContent = new GenRepContent(itvResp);
        return new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    } catch (OperationException e) {
        failureInfo = PKIFailureInfo.systemFailure;
        String statusMessage = null;
        ErrorCode code = e.getErrorCode();
        switch (code) {
        case BAD_REQUEST:
            failureInfo = PKIFailureInfo.badRequest;
            statusMessage = e.getErrorMessage();
            break;
        case DATABASE_FAILURE:
        case SYSTEM_FAILURE:
            statusMessage = code.name();
            break;
        default:
            statusMessage = code.name() + ": " + e.getErrorMessage();
            break;
        } // end switch(code)

        return createErrorMsgPKIBody(PKIStatus.rejection, failureInfo, statusMessage);
    } catch (CRLException e) {
        String statusMessage = "CRLException: " + e.getMessage();
        return createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
    }
}

From source file:org.xipki.commons.remotep11.server.CmpResponder.java

License:Open Source License

private PKIMessage doProcessPkiMessage(final LocalP11CryptServicePool p11CryptServicePool,
        final String moduleName, final InfoTypeAndValue itv, final PKIHeader respHeader)
        throws BadAsn1ObjectException, P11TokenException, CertificateException, XiSecurityException,
        InvalidKeyException {/*from www.  j a v a  2  s .co m*/
    ASN1Sequence seq = Asn1Util.getSequence(itv.getInfoValue());
    Asn1Util.requireRange(seq, 3, 3);
    int protocolVersion = Asn1Util.getInteger(seq.getObjectAt(0)).intValue();
    int action = Asn1Util.getInteger(seq.getObjectAt(1)).intValue();
    ASN1Encodable reqValue = seq.getObjectAt(2);

    P11CryptService p11CryptService = p11CryptServicePool.getP11CryptService(moduleName);
    ASN1Encodable respItvInfoValue = null;

    if (P11ProxyConstants.ACTION_addCert == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        X509Certificate cert = X509Util.toX509Cert(asn1.getCertificate());
        slot.addCert(asn1.getEntityId().getObjectId().getObjectId(), cert);
    } else if (P11ProxyConstants.ACTION_genKeypair_DSA == action) {
        Asn1GenDSAKeypairParams asn1 = Asn1GenDSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_EC == action) {
        Asn1GenECKeypairParams asn1 = Asn1GenECKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateECKeypair(asn1.getCurveId().getId(), asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_genKeypair_RSA == action) {
        Asn1GenRSAKeypairParams asn1 = Asn1GenRSAKeypairParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        P11ObjectIdentifier keyId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(),
                asn1.getLabel());
        respItvInfoValue = new Asn1P11EntityIdentifier(asn1.getSlotId().getSlotId(), keyId);
    } else if (P11ProxyConstants.ACTION_getCertificate == action) {
        P11EntityIdentifier entityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        X509Certificate cert = p11CryptService.getIdentity(entityId).getCertificate();
        respItvInfoValue = Certificate.getInstance(cert.getEncoded());
    } else if (P11ProxyConstants.ACTION_getCertIdentifiers == action
            || P11ProxyConstants.ACTION_getIdentityIdentifiers == action) {
        Asn1P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue);
        P11Slot slot = p11CryptService.getModule().getSlot(slotId.getSlotId());
        Set<P11ObjectIdentifier> objectIds;
        if (P11ProxyConstants.ACTION_getCertIdentifiers == action) {
            objectIds = slot.getCertIdentifiers();
        } else {
            objectIds = slot.getIdentityIdentifiers();
        }
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (P11ObjectIdentifier objectId : objectIds) {
            vec.add(new Asn1P11ObjectIdentifier(objectId));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getMechanisms == action) {
        P11SlotIdentifier slotId = Asn1P11SlotIdentifier.getInstance(reqValue).getSlotId();
        Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (Long mech : mechs) {
            vec.add(new ASN1Integer(mech));
        }
        respItvInfoValue = new DERSequence(vec);
    } else if (P11ProxyConstants.ACTION_getPublicKey == action) {
        P11EntityIdentifier identityId = Asn1P11EntityIdentifier.getInstance(reqValue).getEntityId();
        PublicKey pubKey = p11CryptService.getIdentity(identityId).getPublicKey();
        if (pubKey == null) {
            throw new P11UnknownEntityException(identityId);
        }

        respItvInfoValue = KeyUtil.createSubjectPublicKeyInfo(pubKey);
    } else if (P11ProxyConstants.ACTION_getSlotIds == action) {
        List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIdentifiers();

        ASN1EncodableVector vector = new ASN1EncodableVector();
        for (P11SlotIdentifier slotId : slotIds) {
            vector.add(new Asn1P11SlotIdentifier(slotId));
        }
        respItvInfoValue = new DERSequence(vector);
    } else if (P11ProxyConstants.ACTION_removeCerts == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeCerts(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_removeIdentity == action) {
        Asn1P11EntityIdentifier asn1 = Asn1P11EntityIdentifier.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1);
        slot.removeIdentity(asn1.getObjectId().getObjectId());
    } else if (P11ProxyConstants.ACTION_sign == action) {
        Asn1SignTemplate signTemplate = Asn1SignTemplate.getInstance(reqValue);
        long mechanism = signTemplate.getMechanism().getMechanism();
        Asn1P11Params tmpParams = signTemplate.getMechanism().getParams();
        ASN1Encodable asn1Params = null;
        if (tmpParams != null) {
            asn1Params = tmpParams.getP11Params();
        }
        P11Params params = null;
        if (asn1Params instanceof Asn1RSAPkcsPssParams) {
            params = Asn1RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
        } else if (asn1Params != null) {
            throw new BadAsn1ObjectException("unknown SignTemplate.params");
        }

        byte[] content = signTemplate.getMessage();
        P11Identity identity = p11CryptService.getIdentity(signTemplate.getIdentityId().getEntityId());
        byte[] signature = identity.sign(mechanism, params, content);
        respItvInfoValue = new DEROctetString(signature);
    } else if (P11ProxyConstants.ACTION_updateCerificate == action) {
        Asn1EntityIdAndCert asn1 = Asn1EntityIdAndCert.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getEntityId());
        slot.updateCertificate(asn1.getEntityId().getObjectId().getObjectId(),
                X509Util.toX509Cert(asn1.getCertificate()));
    } else if (P11ProxyConstants.ACTION_removeObjects == action) {
        Asn1RemoveObjectsParams asn1 = Asn1RemoveObjectsParams.getInstance(reqValue);
        P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
        int num = slot.removeObjects(asn1.getObjectId(), asn1.getObjectLabel());
        respItvInfoValue = new ASN1Integer(num);
    } else {
        final String statusMessage = "unsupported XiPKI action code '" + action + "'";
        return createRejectionPkiMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new ASN1Integer(protocolVersion));
    vec.add(new ASN1Integer(action));
    if (respItvInfoValue != null) {
        vec.add(respItvInfoValue);
    }

    InfoTypeAndValue respItv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp_cmpGenmsg,
            new DERSequence(vec));
    GenRepContent genRepContent = new GenRepContent(respItv);
    PKIBody respBody = new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    return new PKIMessage(respHeader, respBody);
}

From source file:org.xipki.pki.ca.server.impl.cmp.X509CaCmpResponder.java

License:Open Source License

private PKIBody cmpGeneralMsg(final PKIHeaderBuilder respHeader, final CmpControl cmpControl,
        final PKIHeader reqHeader, final PKIBody reqBody, final CmpRequestorInfo requestor, final String user,
        final ASN1OctetString tid, final String msgId, final AuditEvent event)
        throws InsuffientPermissionException {
    GenMsgContent genMsgBody = GenMsgContent.getInstance(reqBody.getContent());
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;/*from   w  w  w  .  java 2  s .c o m*/
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue entry : itvs) {
            String itvType = entry.getInfoType().getId();
            if (KNOWN_GENMSG_IDS.contains(itvType)) {
                itv = entry;
                break;
            }
        }
    }

    if (itv == null) {
        String statusMessage = "PKIBody type " + PKIBody.TYPE_GEN_MSG + " is only supported with the sub-types "
                + KNOWN_GENMSG_IDS.toString();
        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
    }

    InfoTypeAndValue itvResp = null;
    ASN1ObjectIdentifier infoType = itv.getInfoType();

    int failureInfo;
    try {
        X509Ca ca = getCa();
        if (CMPObjectIdentifiers.it_currentCRL.equals(infoType)) {
            event.addEventType(CaAuditConstants.TYPE_CMP_genm_currentCrl);
            checkPermission(requestor, Permission.GET_CRL);
            CertificateList crl = ca.getBcCurrentCrl();

            if (itv.getInfoValue() == null) { // as defined in RFC 4210
                crl = ca.getBcCurrentCrl();
            } else {
                // xipki extension
                ASN1Integer crlNumber = ASN1Integer.getInstance(itv.getInfoValue());
                crl = ca.getBcCrl(crlNumber.getPositiveValue());
            }

            if (crl == null) {
                String statusMessage = "no CRL is available";
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
            }

            itvResp = new InfoTypeAndValue(infoType, crl);
        } else if (ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.equals(infoType)) {
            ASN1Encodable asn1 = itv.getInfoValue();
            ASN1Integer asn1Code = null;
            ASN1Encodable reqValue = null;

            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
                asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0));
                if (seq.size() > 1) {
                    reqValue = seq.getObjectAt(1);
                }
            } catch (IllegalArgumentException ex) {
                String statusMessage = "invalid value of the InfoTypeAndValue for "
                        + ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.getId();
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            }

            ASN1Encodable respValue;

            int action = asn1Code.getPositiveValue().intValue();
            switch (action) {
            case XiSecurityConstants.CMP_ACTION_GEN_CRL:
                event.addEventType(CaAuditConstants.TYPE_CMP_genm_genCrl);
                checkPermission(requestor, Permission.GEN_CRL);
                X509CRL tmpCrl = ca.generateCrlOnDemand(msgId);
                if (tmpCrl == null) {
                    String statusMessage = "CRL generation is not activated";
                    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure,
                            statusMessage);
                } else {
                    respValue = CertificateList.getInstance(tmpCrl.getEncoded());
                }
                break;
            case XiSecurityConstants.CMP_ACTION_GET_CRL_WITH_SN:
                event.addEventType(CaAuditConstants.TYPE_CMP_genm_crlForNumber);
                checkPermission(requestor, Permission.GET_CRL);

                ASN1Integer crlNumber = ASN1Integer.getInstance(reqValue);
                respValue = ca.getBcCrl(crlNumber.getPositiveValue());
                if (respValue == null) {
                    String statusMessage = "no CRL is available";
                    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure,
                            statusMessage);
                }
                break;
            case XiSecurityConstants.CMP_ACTION_GET_CAINFO:
                event.addEventType(CaAuditConstants.TYPE_CMP_genm_cainfo);
                Set<Integer> acceptVersions = new HashSet<>();
                if (reqValue != null) {
                    ASN1Sequence seq = DERSequence.getInstance(reqValue);
                    int size = seq.size();
                    for (int i = 0; i < size; i++) {
                        ASN1Integer ai = ASN1Integer.getInstance(seq.getObjectAt(i));
                        acceptVersions.add(ai.getPositiveValue().intValue());
                    }
                }

                if (CollectionUtil.isEmpty(acceptVersions)) {
                    acceptVersions.add(1);
                }

                String systemInfo = getSystemInfo(requestor, acceptVersions);
                respValue = new DERUTF8String(systemInfo);
                break;
            default:
                String statusMessage = "unsupported XiPKI action code '" + action + "'";
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            } // end switch (action)

            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(asn1Code);
            if (respValue != null) {
                vec.add(respValue);
            }
            itvResp = new InfoTypeAndValue(infoType, new DERSequence(vec));
        }

        GenRepContent genRepContent = new GenRepContent(itvResp);
        return new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    } catch (OperationException ex) {
        failureInfo = getPKiFailureInfo(ex);
        ErrorCode code = ex.getErrorCode();

        String errorMessage;
        switch (code) {
        case DATABASE_FAILURE:
        case SYSTEM_FAILURE:
            errorMessage = code.name();
            break;
        default:
            errorMessage = code.name() + ": " + ex.getErrorMessage();
            break;
        } // end switch code

        return buildErrorMsgPkiBody(PKIStatus.rejection, failureInfo, errorMessage);
    } catch (CRLException ex) {
        String statusMessage = "CRLException: " + ex.getMessage();
        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
    }
}

From source file:org.xipki.remotep11.server.impl.CmpResponder.java

License:Open Source License

PKIMessage processPKIMessage(final LocalP11CryptServicePool localP11CryptServicePool, final String moduleName,
        final PKIMessage pkiMessage) {
    GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);

    PKIHeader reqHeader = message.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();

    if (tid == null) {
        byte[] randomBytes = randomTransactionId();
        tid = new DEROctetString(randomBytes);
    }/*from   w w w  .  j a  v  a  2s .c om*/
    String tidStr = Hex.toHexString(tid.getOctets());

    PKIHeaderBuilder respHeaderBuilder = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), sender,
            reqHeader.getSender());
    respHeaderBuilder.setTransactionID(tid);

    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    PKIHeader respHeader = respHeaderBuilder.build();

    if (type != PKIBody.TYPE_GEN_MSG) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText("unsupported type " + type), new PKIFailureInfo(PKIFailureInfo.badRequest)));

        PKIBody respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);

        return new PKIMessage(respHeader, respBody);
    }

    GenMsgContent genMsgBody = (GenMsgContent) reqBody.getContent();
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();

    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue m : itvs) {
            ASN1ObjectIdentifier itvType = m.getInfoType();
            if (ObjectIdentifiers.id_xipki_cmp.equals(itvType)) {
                itv = m;
                break;
            }
        }
    }

    if (itv == null) {
        final String statusMessage = String.format("PKIBody type %s is only supported with the sub-knownTypes",
                ObjectIdentifiers.id_xipki_cmp.getId());
        return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
    }

    try {
        ASN1Encodable asn1 = itv.getInfoValue();
        ASN1Integer asn1Code = null;
        ASN1Encodable reqValue = null;

        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0));
            if (seq.size() > 1) {
                reqValue = seq.getObjectAt(1);
            }
        } catch (IllegalArgumentException e) {
            final String statusMessage = "invalid value of the InfoTypeAndValue for "
                    + ObjectIdentifiers.id_xipki_cmp.getId();
            return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
        }

        int action = asn1Code.getPositiveValue().intValue();
        ASN1Encodable respItvInfoValue;

        P11CryptService p11CryptService = localP11CryptServicePool.getP11CryptService(moduleName);

        switch (action) {
        case XipkiCmpConstants.ACTION_RP11_VERSION: {
            respItvInfoValue = new ASN1Integer(localP11CryptServicePool.getVersion());
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_PSO_DSA_PLAIN:
        case XipkiCmpConstants.ACTION_RP11_PSO_DSA_X962:
        case XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_PLAIN:
        case XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_X962:
        case XipkiCmpConstants.ACTION_RP11_PSO_RSA_PKCS:
        case XipkiCmpConstants.ACTION_RP11_PSO_RSA_X509: {
            byte[] psoMessage = null;
            P11SlotIdentifier slot = null;
            P11KeyIdentifier keyId = null;
            {
                try {
                    PSOTemplate psoTemplate = PSOTemplate.getInstance(reqValue);
                    psoMessage = psoTemplate.getMessage();
                    SlotAndKeyIdentifer slotAndKeyIdentifier = psoTemplate.getSlotAndKeyIdentifer();
                    slot = slotAndKeyIdentifier.getSlotIdentifier().getSlotId();
                    KeyIdentifier keyIdentifier = slotAndKeyIdentifier.getKeyIdentifier();
                    keyId = keyIdentifier.getKeyId();
                } catch (IllegalArgumentException e) {
                    final String statusMessage = "invalid PSOTemplate";
                    return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
                }
            }

            byte[] signature;

            if (XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_PLAIN == action) {
                signature = p11CryptService.CKM_ECDSA_Plain(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_ECDSA_X962 == action) {
                signature = p11CryptService.CKM_ECDSA_X962(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_DSA_PLAIN == action) {
                signature = p11CryptService.CKM_DSA_Plain(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_DSA_X962 == action) {
                signature = p11CryptService.CKM_DSA_X962(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_RSA_X509 == action) {
                signature = p11CryptService.CKM_RSA_X509(psoMessage, slot, keyId);
            } else if (XipkiCmpConstants.ACTION_RP11_PSO_RSA_PKCS == action) {
                signature = p11CryptService.CKM_RSA_PKCS(psoMessage, slot, keyId);
            } else {
                throw new RuntimeException("should not reach here");
            }

            respItvInfoValue = new DEROctetString(signature);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_GET_CERTIFICATE:
        case XipkiCmpConstants.ACTION_RP11_GET_PUBLICKEY: {
            P11SlotIdentifier slot = null;
            P11KeyIdentifier keyId = null;
            try {
                SlotAndKeyIdentifer slotAndKeyIdentifier = SlotAndKeyIdentifer.getInstance(reqValue);
                slot = slotAndKeyIdentifier.getSlotIdentifier().getSlotId();
                KeyIdentifier keyIdentifier = slotAndKeyIdentifier.getKeyIdentifier();
                keyId = keyIdentifier.getKeyId();
            } catch (IllegalArgumentException e) {
                final String statusMessage = "invalid SlotAndKeyIdentifier";
                return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
            }

            byte[] encodeCertOrKey;
            if (XipkiCmpConstants.ACTION_RP11_GET_CERTIFICATE == action) {
                encodeCertOrKey = p11CryptService.getCertificate(slot, keyId).getEncoded();
            } else if (XipkiCmpConstants.ACTION_RP11_GET_PUBLICKEY == action) {
                encodeCertOrKey = p11CryptService.getPublicKey(slot, keyId).getEncoded();
            } else {
                throw new RuntimeException("should not reach here");
            }

            respItvInfoValue = new DEROctetString(encodeCertOrKey);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_LIST_SLOTS: {
            P11SlotIdentifier[] slotIds = p11CryptService.getSlotIdentifiers();

            ASN1EncodableVector vector = new ASN1EncodableVector();
            for (P11SlotIdentifier slotId : slotIds) {
                vector.add(new SlotIdentifier(slotId));
            }
            respItvInfoValue = new DERSequence(vector);
            break;
        }
        case XipkiCmpConstants.ACTION_RP11_LIST_KEYLABELS: {
            SlotIdentifier slotId = SlotIdentifier.getInstance(reqValue);
            String[] keyLabels = p11CryptService.getKeyLabels(slotId.getSlotId());

            ASN1EncodableVector vector = new ASN1EncodableVector();
            for (String keyLabel : keyLabels) {
                vector.add(new DERUTF8String(keyLabel));
            }
            respItvInfoValue = new DERSequence(vector);
            break;
        }
        default: {
            final String statusMessage = "unsupported XiPKI action code '" + action + "'";
            return createRejectionPKIMessage(respHeader, PKIFailureInfo.badRequest, statusMessage);
        }
        } // end switch(code)

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(action));
        if (respItvInfoValue != null) {
            v.add(respItvInfoValue);
        }
        InfoTypeAndValue respItv = new InfoTypeAndValue(ObjectIdentifiers.id_xipki_cmp, new DERSequence(v));
        GenRepContent genRepContent = new GenRepContent(respItv);
        PKIBody respBody = new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
        return new PKIMessage(respHeader, respBody);
    } catch (Throwable t) {
        LOG.error("error while processing CMP message {}, message: {}", tidStr, t.getMessage());
        LOG.debug("error while processing CMP message " + tidStr, t);
        return createRejectionPKIMessage(respHeader, PKIFailureInfo.systemFailure, t.getMessage());
    }
}