Example usage for org.bouncycastle.asn1 ASN1Enumerated getValue

List of usage examples for org.bouncycastle.asn1 ASN1Enumerated getValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Enumerated getValue.

Prototype

public BigInteger getValue() 

Source Link

Usage

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static SignPolicyRef extractVerifyRefence(byte[] policy) throws IOException, ParseException {
    SignPolicyRef ret = new SignPolicyRef();

    ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(policy));
    ASN1Primitive topLevel = is.readObject();
    // SignaturePolicy ::= SEQUENCE {
    // signPolicyHashAlg AlgorithmIdentifier,
    // signPolicyInfo SignPolicyInfo,
    // signPolicyHash SignPolicyHash OPTIONAL }
    if (topLevel instanceof DLSequence) {
        DLSequence topLevelDLS = (DLSequence) topLevel;
        ASN1Encodable dseqL10 = topLevelDLS.getObjectAt(0);
        ASN1Encodable psHashAlg = null;//from   ww w  .  jav  a2s . c om
        if (dseqL10 instanceof DLSequence) {
            DLSequence dseqL10DLS = (DLSequence) dseqL10;
            psHashAlg = dseqL10DLS.getObjectAt(0);

        } else if (dseqL10 instanceof ASN1ObjectIdentifier) {
            psHashAlg = (ASN1ObjectIdentifier) dseqL10;
        } else
            return null;

        if (psHashAlg instanceof ASN1ObjectIdentifier) {
            ASN1ObjectIdentifier psHashAlgOid = (ASN1ObjectIdentifier) psHashAlg;
            ret.setPsHashAlg(psHashAlgOid.toString());
        }

        ASN1Encodable dseqL11 = topLevelDLS.getObjectAt(1);
        if (dseqL11 instanceof DLSequence) {
            // SignPolicyInfo ::= SEQUENCE {
            DLSequence dseqL11DLS = (DLSequence) dseqL11;
            ASN1Encodable psOid = dseqL11DLS.getObjectAt(0);
            // signPolicyIdentifier SignPolicyId,
            // 2.16.76.1.7.1.6.2.1
            if (psOid instanceof ASN1ObjectIdentifier) {
                ASN1ObjectIdentifier psOidOid = (ASN1ObjectIdentifier) psOid;
                ret.setPsOid(psOidOid.toString());

            }
            ASN1Encodable dateOfIssue = dseqL11DLS.getObjectAt(1);
            // dateOfIssue GeneralizedTime,
            // 2012-03-22
            if (dateOfIssue instanceof ASN1GeneralizedTime) {
                ASN1GeneralizedTime dateOfIssueGT = (ASN1GeneralizedTime) dateOfIssue;
                ret.setDateOfIssue(dateOfIssueGT.getDate());
            }

            ASN1Encodable policyIssuerName = dseqL11DLS.getObjectAt(2);
            // policyIssuerName PolicyIssuerName,
            // C=BR, O=ICP-Brasil, OU=Instituto Nacional de Tecnologia da
            // Informacao
            // - ITI
            if (policyIssuerName instanceof DLSequence) {
                DLSequence policyIssuerNameDLSeq = (DLSequence) policyIssuerName;
                ASN1Encodable policyIssuerName2 = policyIssuerNameDLSeq.getObjectAt(0);
                if (policyIssuerName2 instanceof DERTaggedObject) {
                    DERTaggedObject policyIssuerName2DTO = (DERTaggedObject) policyIssuerName2;
                    ASN1Primitive polIssuerNameObj = policyIssuerName2DTO.getObject();
                    if (polIssuerNameObj instanceof DEROctetString) {
                        String polIssuerNameStr = new String(((DEROctetString) polIssuerNameObj).getOctets());
                        ret.setPolIssuerName(polIssuerNameStr);
                    }
                }

            }

            ASN1Encodable fieldOfApplication = dseqL11DLS.getObjectAt(3);
            // fieldOfApplication FieldOfApplication,
            // Este tipo de assinatura deve ser utilizado em aplicacoes ou
            // processos
            // de negocio nos quais a assinatura digital agrega seguranca a
            // autenticacao de entidades e verificacao de integridade,
            // permitindo
            // sua validacao durante o prazo de, validade dos certificados
            // dos
            // signatarios. Uma vez que nao sao usados carimbos do tempo, a
            // validacao posterior so sera possivel se existirem referencias
            // temporais que identifiquem o momento em que ocorreu a
            // assinatura
            // digital. Nessas situacoes, deve existir legislacao especifica
            // ou um
            // acordo previo entre as partes definindo as referencias a
            // serem
            // utilizadas. Segundo esta PA, e permitido o emprego de
            // multiplas
            // assinaturas.
            if (fieldOfApplication instanceof DEROctetString) {
                DERUTF8String fieldOfApplicationDUS = (DERUTF8String) fieldOfApplication;
                ret.setFieldOfApplication(fieldOfApplicationDUS.getString());
            }
            // signatureValidationPolicy SignatureValidationPolicy,
            // signPolExtensions SignPolExtensions OPTIONAL
            // SignatureValidationPolicy ::= SEQUENCE {
            ASN1Encodable signatureValidationPolicy = dseqL11DLS.getObjectAt(4);
            if (signatureValidationPolicy instanceof DLSequence) {
                DLSequence signatureValidationPolicyDLS = (DLSequence) signatureValidationPolicy;
                // signingPeriod SigningPeriod,
                // NotBefore 2012-03-22
                // NotAfter 2023-06-21
                ASN1Encodable signingPeriod = signatureValidationPolicyDLS.getObjectAt(0);
                if (signingPeriod instanceof DLSequence) {
                    DLSequence signingPeriodDLS = (DLSequence) signingPeriod;
                    ASN1Encodable notBefore = signingPeriodDLS.getObjectAt(0);
                    if (notBefore instanceof ASN1GeneralizedTime) {
                        ASN1GeneralizedTime notBeforeAGT = (ASN1GeneralizedTime) notBefore;
                        ret.setNotBefore(notBeforeAGT.getDate());

                    }

                    ASN1Encodable notAfter = signingPeriodDLS.getObjectAt(1);
                    if (notAfter instanceof ASN1GeneralizedTime) {
                        ASN1GeneralizedTime notAfterAGT = (ASN1GeneralizedTime) notAfter;
                        ret.setNotAfter(notAfterAGT.getDate());
                    }

                }

                //
                // commonRules CommonRules,
                ASN1Encodable commonRules = getAt(signatureValidationPolicyDLS, 1);
                if (commonRules instanceof DLSequence) {
                    DLSequence commonRulesDLS = (DLSequence) commonRules;
                    // CommonRules ::= SEQUENCE {
                    // signerAndVeriferRules [0] SignerAndVerifierRules
                    // OPTIONAL,
                    // signingCertTrustCondition [1]
                    // SigningCertTrustCondition OPTIONAL,
                    // timeStampTrustCondition [2] TimestampTrustCondition
                    // OPTIONAL,
                    // attributeTrustCondition [3] AttributeTrustCondition
                    // OPTIONAL,
                    // algorithmConstraintSet [4] AlgorithmConstraintSet
                    // OPTIONAL,
                    // signPolExtensions [5] SignPolExtensions OPTIONAL
                    // }
                    ASN1Encodable signerAndVeriferRules = getAt(commonRulesDLS, 0);

                    // SignerAndVerifierRules ::= SEQUENCE {
                    // signerRules SignerRules,
                    // verifierRules VerifierRules }

                    if (signerAndVeriferRules instanceof DERTaggedObject) {
                        DERTaggedObject signerAndVeriferRulesDTO = (DERTaggedObject) signerAndVeriferRules;
                        ASN1Encodable signerAndVeriferRulesTmp = signerAndVeriferRulesDTO.getObject();
                        if (signerAndVeriferRulesTmp instanceof DERSequence) {
                            DERSequence signerAndVeriferRulesDERSeq = (DERSequence) signerAndVeriferRulesTmp;
                            ASN1Encodable signerRules = getAt(signerAndVeriferRulesDERSeq, 0);
                            if (signerRules instanceof DERSequence) {
                                DERSequence signerRulesDERSeq = (DERSequence) signerRules;
                                // SignerRules ::= SEQUENCE {
                                // externalSignedData BOOLEAN OPTIONAL,
                                // -- True if signed data is external to CMS
                                // structure
                                // -- False if signed data part of CMS
                                // structure
                                // -- not present if either allowed
                                // mandatedSignedAttr CMSAttrs,
                                // -- Mandated CMS signed attributes
                                // 1.2.840.113549.1.9.3
                                // 1.2.840.113549.1.9.4
                                // 1.2.840.113549.1.9.16.2.15
                                // 1.2.840.113549.1.9.16.2.47
                                // mandatedUnsignedAttr CMSAttrs,
                                // <empty sequence>
                                // -- Mandated CMS unsigned attributed
                                // mandatedCertificateRef [0] CertRefReq
                                // DEFAULT signerOnly,
                                // (1)
                                // -- Mandated Certificate Reference
                                // mandatedCertificateInfo [1] CertInfoReq
                                // DEFAULT none,
                                // -- Mandated Certificate Info
                                // signPolExtensions [2] SignPolExtensions
                                // OPTIONAL}

                                // CMSAttrs ::= SEQUENCE OF OBJECT
                                // IDENTIFIER
                                ASN1Encodable mandatedSignedAttr = getAt(signerRulesDERSeq, 0);
                                if (mandatedSignedAttr instanceof DERSequence) {
                                    DERSequence mandatedSignedAttrDERSeq = (DERSequence) mandatedSignedAttr;
                                    for (int i = 0; i < mandatedSignedAttrDERSeq.size(); i++) {
                                        ASN1Encodable at = getAt(mandatedSignedAttrDERSeq, i);
                                        ret.addMandatedSignedAttr(at.toString());
                                    }
                                }
                                ASN1Encodable mandatedUnsignedAttr = getAt(signerRulesDERSeq, 1);
                                if (mandatedUnsignedAttr instanceof DERSequence) {
                                    DERSequence mandatedUnsignedAttrDERSeq = (DERSequence) mandatedUnsignedAttr;
                                }
                                ASN1Encodable mandatedCertificateRef = getAt(signerRulesDERSeq, 2);
                                if (mandatedCertificateRef instanceof DERTaggedObject) {
                                    DERTaggedObject mandatedCertificateRefDERSeq = (DERTaggedObject) mandatedCertificateRef;
                                    // CertRefReq ::= ENUMERATED {
                                    // signerOnly (1),
                                    // -- Only reference to signer cert
                                    // mandated
                                    // fullpath (2)
                                    //
                                    // -- References for full cert path up
                                    // to a trust point required
                                    // }
                                    ASN1Encodable mandatedCertificateRefTmp = mandatedCertificateRefDERSeq
                                            .getObject();
                                    ASN1Enumerated mandatedCertificateRefEnum = (ASN1Enumerated) mandatedCertificateRefTmp;
                                    BigInteger valEnum = mandatedCertificateRefEnum.getValue();
                                    int mandatedCertificateRefInt = valEnum.intValue();
                                    ret.setMandatedCertificateRef(mandatedCertificateRefInt);
                                    int x = 0;
                                }
                            }

                            ASN1Encodable verifierRules = getAt(signerAndVeriferRulesDERSeq, 1);
                            if (verifierRules instanceof DERSequence) {
                                DERSequence verifierRulesDERSeq = (DERSequence) verifierRules;

                            }

                        }

                    }

                    ASN1Encodable signingCertTrustCondition = getAt(commonRulesDLS, 1);
                    if (signingCertTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject signingCertTrustConditionDTO = (DERTaggedObject) signingCertTrustCondition;
                        ASN1Encodable signingCertTrustConditionTmp = signingCertTrustConditionDTO.getObject();
                        if (signingCertTrustConditionTmp instanceof DERSequence) {
                            DERSequence signingCertTrustConditionDERSeq = (DERSequence) signingCertTrustConditionTmp;
                        }

                    }
                    ASN1Encodable timeStampTrustCondition = getAt(commonRulesDLS, 2);
                    if (timeStampTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject timeStampTrustConditionDTO = (DERTaggedObject) timeStampTrustCondition;
                        ASN1Encodable timeStampTrustConditionTmp = timeStampTrustConditionDTO.getObject();
                        if (timeStampTrustConditionTmp instanceof DERSequence) {
                            DERSequence timeStampTrustConditionDERSeq = (DERSequence) timeStampTrustConditionTmp;
                        }

                    }
                    ASN1Encodable attributeTrustCondition = getAt(commonRulesDLS, 3);
                    if (attributeTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject attributeTrustConditionDTO = (DERTaggedObject) attributeTrustCondition;
                        ASN1Encodable attributeTrustConditionTmp = attributeTrustConditionDTO.getObject();
                        if (attributeTrustConditionTmp instanceof DERSequence) {
                            DERSequence attributeTrustConditionDERSeq = (DERSequence) attributeTrustConditionTmp;
                        }

                    }

                    // *****************************
                    ASN1Encodable algorithmConstraintSet = getAt(commonRulesDLS, 4);
                    ASN1Encodable signPolExtensions = getAt(commonRulesDLS, 5);

                }
                // commitmentRules CommitmentRules,
                ASN1Encodable commitmentRules = getAt(signatureValidationPolicyDLS, 2);
                if (commitmentRules instanceof DLSequence) {

                }

                // signPolExtensions SignPolExtensions
                // OPTIONAL
                ASN1Encodable signPolExtensions = getAt(signatureValidationPolicyDLS, 3);
                if (signPolExtensions instanceof DLSequence) {

                }
                // }
            }
        }

    }

    // CertInfoReq ::= ENUMERATED {
    // none (0) ,
    // -- No mandatory requirements
    // signerOnly (1) ,
    // -- Only reference to signer cert mandated
    // fullpath (2)
    // -- References for full cert path up to a
    // -- trust point mandated
    // }

    is.close();
    return ret;

}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.RFC3280CertPathUtilitiesHelper.java

License:Open Source License

protected static void getCertStatus(Date validDate, X509CRL crl, Object cert, CertStatus certStatus)
        throws SimpleValidationErrorException {
    // use BC X509CRLObject so that indirect CRLs are supported
    X509CRLObject bcCRL = null;/*w  w w.  j  a  v a  2 s.c o m*/
    try {
        bcCRL = new X509CRLObject(
                new CertificateList((ASN1Sequence) ASN1Sequence.fromByteArray(crl.getEncoded())));
    } catch (Exception e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.unknownMsg, e);
    }
    // use BC X509CRLEntryObject, so that getCertificateIssuer() is
    // supported.
    X509CRLEntryObject crl_entry = (X509CRLEntryObject) bcCRL
            .getRevokedCertificate(CertPathValidatorUtilities.getSerialNumber(cert));
    if (crl_entry != null && (CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert)
            .equals(crl_entry.getCertificateIssuer())
            || CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert)
                    .equals(crl.getIssuerX500Principal()))) {
        ASN1Enumerated reasonCode = null;
        if (crl_entry.hasExtensions()) {
            try {
                reasonCode = ASN1Enumerated.getInstance(CertPathValidatorUtilities.getExtensionValue(crl_entry,
                        X509Extensions.ReasonCode.getId()));
            } catch (Exception e) {
                throw new SimpleValidationErrorException(ValidationErrorCode.crlReasonExtError, e);
            }
        }

        // for reason keyCompromise, caCompromise, aACompromise
        // or
        // unspecified
        if (!(validDate.getTime() < crl_entry.getRevocationDate().getTime()) || reasonCode == null
                || reasonCode.getValue().intValue() == 0 || reasonCode.getValue().intValue() == 1
                || reasonCode.getValue().intValue() == 2 || reasonCode.getValue().intValue() == 8) {

            // (i) or (j) (1)
            if (reasonCode != null) {
                certStatus.setCertStatus(reasonCode.getValue().intValue());
            }
            // (i) or (j) (2)
            else {
                certStatus.setCertStatus(CRLReason.unspecified);
            }
            certStatus.setRevocationDate(crl_entry.getRevocationDate());
        }
    }
}

From source file:jcifs.spnego.NegTokenTarg.java

License:Open Source License

@Override
protected void parse(byte[] token) throws IOException {
    try (ASN1InputStream der = new ASN1InputStream(token)) {
        ASN1TaggedObject tagged = (ASN1TaggedObject) der.readObject();
        ASN1Sequence sequence = ASN1Sequence.getInstance(tagged, true);
        Enumeration<?> fields = sequence.getObjects();
        while (fields.hasMoreElements()) {
            tagged = (ASN1TaggedObject) fields.nextElement();
            switch (tagged.getTagNo()) {
            case 0:
                ASN1Enumerated enumerated = ASN1Enumerated.getInstance(tagged, true);
                setResult(enumerated.getValue().intValue());
                break;
            case 1:
                ASN1ObjectIdentifier mech = ASN1ObjectIdentifier.getInstance(tagged, true);
                setMechanism(new Oid(mech.getId()));
                break;
            case 2:
                ASN1OctetString mechanismToken = ASN1OctetString.getInstance(tagged, true);
                setMechanismToken(mechanismToken.getOctets());
                break;
            case 3:
                ASN1OctetString mechanismListMIC = ASN1OctetString.getInstance(tagged, true);
                setMechanismListMIC(mechanismListMIC.getOctets());
                break;
            default:
                throw new IOException("Malformed token field.");
            }//w w w .j a v a 2  s .c o m
        }
    } catch (GSSException e) {
        throw new IOException("Failed to parse Oid", e);
    }
}

From source file:net.sf.keystore_explorer.utilities.asn1.Asn1Dump.java

License:Open Source License

private String dumpEnumerated(ASN1Enumerated asn1Enumerated) {
    StringBuilder sb = new StringBuilder();

    sb.append(indentSequence.toString(indentLevel));
    sb.append("ENUMERATED=");
    sb.append(asn1Enumerated.getValue());
    sb.append(NEWLINE);/*from   w w w.j  a v  a  2 s . c  o  m*/

    return sb.toString();
}

From source file:org.cesecore.certificates.util.cert.CrlExtensions.java

License:Open Source License

/** @return the revocation reason code as defined in RevokedCertInfo.REVOCATION_REASON_... */
public static int extractReasonCode(final X509CRLEntry crlEntry) {
    int reasonCode = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    if (crlEntry.hasExtensions()) {
        final byte[] extensionValue = crlEntry.getExtensionValue(Extension.reasonCode.getId());
        try {/*from   w  ww.j a  va2 s.  com*/
            final ASN1Enumerated reasonCodeExtension = ASN1Enumerated
                    .getInstance(X509ExtensionUtil.fromExtensionValue(extensionValue));
            if (reasonCodeExtension != null) {
                reasonCode = reasonCodeExtension.getValue().intValue();
            }
        } catch (IOException e) {
            log.debug("Failed to parse reason code of CRLEntry: " + e.getMessage());
        }
    }
    return reasonCode;
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.CertInfoReq.java

License:Open Source License

public static CertInfoReq parse(ASN1Primitive derObject) {
    ASN1Enumerated derEnumerated = ASN1Object.getDEREnumerated(derObject);
    int value = derEnumerated.getValue().intValue();
    for (CertInfoReq certInfoReq : CertInfoReq.values()) {
        if (certInfoReq.value == value) {
            return certInfoReq;
        }//w w  w. ja  v a 2s  .com
    }
    return null;
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.CertRefReq.java

License:Open Source License

public static CertRefReq parse(ASN1Primitive derObject) {
    ASN1Enumerated derEnumerated = ASN1Object.getDEREnumerated(derObject);
    int value = derEnumerated.getValue().intValue();
    for (CertRefReq certRefReq : CertRefReq.values()) {
        if (certRefReq.value == value) {
            return certRefReq;
        }//from  ww w . j a v  a  2  s  .  co m
    }
    return null;
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.EnuRevReq.java

License:Open Source License

public static EnuRevReq parse(ASN1Primitive derObject) {
    ASN1Enumerated derEnumerated = ASN1Object.getDEREnumerated(derObject);
    int value = derEnumerated.getValue().intValue();
    for (EnuRevReq enuRevReq : EnuRevReq.values()) {
        if (enuRevReq.value == value) {
            return enuRevReq;
        }//from   www .j a v  a  2s . c  o  m
    }
    return null;
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.HowCertAttribute.java

License:Open Source License

public static HowCertAttribute parse(ASN1Primitive derObject) {
    ASN1Enumerated derEnumerated = ASN1Object.getDEREnumerated(derObject);
    int value = derEnumerated.getValue().intValue();
    for (HowCertAttribute howCertAttribute : HowCertAttribute.values()) {
        if (howCertAttribute.value == value) {
            return howCertAttribute;
        }/*from  w w  w .  j a  v  a  2 s  . c  o  m*/
    }
    return null;
}

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

License:Open Source License

public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }//from  w ww .  j av  a  2s  .  c om

    CA ca = null;
    try {
        final String caDN = msg.getHeader().getRecipient().getName().toString();
        final int caId = CertTools.stringToBCDNString(caDN).hashCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId
                    + ", after CertTools.stringToBCDNString conversion.");
        }
        ca = caSession.getCA(admin, caId);
    } catch (CADoesntExistsException e) {
        final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString()
                + "' is unknown";
        LOG.info(errMsg);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                errMsg);
    } catch (AuthorizationDeniedException e) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e.getMessage());
    }

    ResponseMessage resp = null;
    // if version == 1 it is cmp1999 and we should not return a message back
    // Try to find a HMAC/SHA1 protection key
    final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID());
    ResponseStatus status = ResponseStatus.FAILURE;
    FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK;
    String failText = null;

    //Verify the authenticity of the message
    final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin,
            caSession, endEntityAccessSession, certificateStoreSession, authorizationSession,
            endEntityProfileSession, authenticationProviderSession, endEntityManagementSession,
            this.cmpConfiguration);
    ICMPAuthenticationModule authenticationModule = messageVerifyer
            .getUsedAuthenticationModule(msg.getMessage(), null, authenticated);
    if (authenticationModule == null) {
        LOG.info(messageVerifyer.getErrorMessage());
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage());
    }

    // If authentication was correct, we will now try to find the certificate to revoke
    final PKIMessage pkimsg = msg.getMessage();
    final PKIBody body = pkimsg.getBody();
    final RevReqContent rr = (RevReqContent) body.getContent();
    RevDetails rd;
    try {
        rd = rr.toRevDetailsArray()[0];
    } catch (Exception e) {
        LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message.");
        rd = CmpMessageHelper.getNovosecRevDetails(rr);
        LOG.debug("Succeeded in parsing the novosec generated request.");
    }
    final CertTemplate ct = rd.getCertDetails();
    final ASN1Integer serno = ct.getSerialNumber();
    final X500Name issuer = ct.getIssuer();
    // Get the revocation reason. 
    // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension
    // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2
    int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode)
            .getExtnValue();
    DERBitString reasonbits;
    try {
        reasonbits = new DERBitString(reasonoctets.getEncoded());
    } catch (IOException e1) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e1.getMessage());
    }
    if (reasonbits != null) {
        reason = CertTools.bitStringToRevokedCertInfo(reasonbits);
        if (LOG.isDebugEnabled()) {
            LOG.debug("CMPv1 revocation reason: " + reason);
        }
    }
    final Extensions crlExt = rd.getCrlEntryDetails();
    if (crlExt != null) {
        final Extension ext = crlExt.getExtension(Extension.reasonCode);
        if (ext != null) {
            try {
                final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets());
                final ASN1Primitive obj = ai.readObject();
                final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj);
                // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code
                reason = crlreason.getValue().intValue();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CRLReason extension: " + reason);
                }
                ai.close();
            } catch (IOException e) {
                LOG.info("Exception parsin CRL reason extension: ", e);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No CRL reason code extension present.");
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No CRL entry extensions present");
        }
    }

    if ((serno != null) && (issuer != null)) {
        final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(),
                serno.getValue().toString(16));
        LOG.info(iMsg);
        try {
            endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason);
            status = ResponseStatus.SUCCESS;
        } catch (AuthorizationDeniedException e) {
            failInfo = FailInfo.NOT_AUTHORIZED;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            LOG.info(failText);
        } catch (FinderException e) {
            failInfo = FailInfo.BAD_CERTIFICATE_ID;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        } catch (WaitingForApprovalException e) {
            status = ResponseStatus.GRANTED_WITH_MODS;
        } catch (ApprovalException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested");
            failText = errMsg;
            LOG.info(failText);
        } catch (AlreadyRevokedException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked");
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        }
    } else {
        failInfo = FailInfo.BAD_CERTIFICATE_ID;
        final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(),
                serno.getValue().toString(16));
        failText = errMsg;
        LOG.info(failText);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating a PKI revocation message response");
    }
    final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage();
    rresp.setRecipientNonce(msg.getSenderNonce());
    rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce())));
    rresp.setSender(msg.getRecipient());
    rresp.setRecipient(msg.getSender());
    rresp.setTransactionId(msg.getTransactionId());
    rresp.setFailInfo(failInfo);
    rresp.setFailText(failText);
    rresp.setStatus(status);

    if (StringUtils.equals(responseProtection, "pbe")) {
        final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule;
        final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid();
        final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid();
        final int iterationCount = 1024;
        final String cmpRaAuthSecret = hmacmodule.getAuthenticationString();

        if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) {
            // Set all protection parameters
            if (LOG.isDebugEnabled()) {
                LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", "
                        + cmpRaAuthSecret);
            }
            rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount);
        }
    } else if (StringUtils.equals(responseProtection, "signature")) {
        try {
            final CryptoToken cryptoToken = cryptoTokenSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            final String aliasCertSign = ca.getCAToken()
                    .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
            rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign),
                    cryptoToken.getSignProviderName());
            if (msg.getHeader().getProtectionAlg() != null) {
                rresp.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }
        } catch (CryptoTokenOfflineException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    resp = rresp;
    try {
        resp.create();
    } catch (InvalidKeyException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchProviderException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CertificateEncodingException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CRLException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    }

    return resp;
}