Example usage for org.bouncycastle.asn1 ASN1GeneralizedTime ASN1GeneralizedTime

List of usage examples for org.bouncycastle.asn1 ASN1GeneralizedTime ASN1GeneralizedTime

Introduction

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

Prototype

ASN1GeneralizedTime(byte[] bytes) 

Source Link

Usage

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineB.java

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)/*from  ww w .  j a  v  a  2s.  co  m*/
 * <p/>
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later. The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1 type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 * <p/>
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    /* this attribute is prohibited in PAdES B */
    if (!padesUsage) {

        final BLevelParameters bLevelParameters = parameters.bLevel();
        final String contentIdentifierPrefix = bLevelParameters.getContentIdentifierPrefix();
        if (DSSUtils.isNotBlank(contentIdentifierPrefix)) {

            final String contentIdentifierSuffix;
            if (DSSUtils.isBlank(bLevelParameters.getContentIdentifierSuffix())) {

                final Date now = new Date();
                final String asn1GeneralizedTimeString = new ASN1GeneralizedTime(now).getTimeString();
                final long randomNumber = new Random(now.getTime()).nextLong();
                contentIdentifierSuffix = asn1GeneralizedTimeString + randomNumber;
                bLevelParameters.setContentIdentifierSuffix(contentIdentifierSuffix);
            } else {
                contentIdentifierSuffix = bLevelParameters.getContentIdentifierSuffix();
            }
            final String contentIdentifierString = contentIdentifierPrefix + contentIdentifierSuffix;
            final ContentIdentifier contentIdentifier = new ContentIdentifier(
                    contentIdentifierString.getBytes());
            final DERSet attrValues = new DERSet(contentIdentifier);
            final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_contentIdentifier,
                    attrValues);
            signedAttributes.add(attribute);
        }
    }
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineB.java

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)/*from  w ww . j  a  v  a 2s  . c o  m*/
 *
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later.
 * The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1
 * type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 *
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final CAdESSignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    /* this attribute is prohibited in PAdES B */
    if (!padesUsage) {

        final BLevelParameters bLevelParameters = parameters.bLevel();
        final String contentIdentifierPrefix = parameters.getContentIdentifierPrefix();
        if (StringUtils.isNotBlank(contentIdentifierPrefix)) {

            final String contentIdentifierSuffix;
            if (StringUtils.isBlank(parameters.getContentIdentifierSuffix())) {

                final Date now = new Date();
                final String asn1GeneralizedTimeString = new ASN1GeneralizedTime(now).getTimeString();
                final long randomNumber = new Random(now.getTime()).nextLong();
                contentIdentifierSuffix = asn1GeneralizedTimeString + randomNumber;
                parameters.setContentIdentifierSuffix(contentIdentifierSuffix);
            } else {
                contentIdentifierSuffix = parameters.getContentIdentifierSuffix();
            }
            final String contentIdentifierString = contentIdentifierPrefix + contentIdentifierSuffix;
            final ContentIdentifier contentIdentifier = new ContentIdentifier(
                    contentIdentifierString.getBytes());
            final DERSet attrValues = new DERSet(contentIdentifier);
            final Attribute attribute = new Attribute(id_aa_contentIdentifier, attrValues);
            signedAttributes.add(attribute);
        }
    }
}

From source file:net.ripe.rpki.commons.crypto.cms.manifest.ManifestCmsBuilder.java

License:BSD License

/**
 * Note: in DER encoding a field with a value equal to its default should
 * NOT be encoded. So the version field should not be present.
 *///from ww  w  . j  a  va 2 s  .  c  o  m
ASN1Encodable encodeManifest() {
    ASN1Encodable[] seq = { new ASN1Integer(number), new ASN1GeneralizedTime(thisUpdateTime.toDate()),
            new ASN1GeneralizedTime(nextUpdateTime.toDate()),
            new ASN1ObjectIdentifier(ManifestCms.FILE_HASH_ALGORITHM), encodeFileList() };
    return new DERSequence(seq);
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

License:Open Source License

@Override
public OcspResponseInformation getOcspResponse(final byte[] request,
        final X509Certificate[] requestCertificates, String remoteAddress, String remoteHost,
        StringBuffer requestUrl, final AuditLogger auditLogger, final TransactionLogger transactionLogger)
        throws MalformedRequestException, OCSPException {
    //Check parameters
    if (auditLogger == null) {
        throw new InvalidParameterException(
                "Illegal to pass a null audit logger to OcspResponseSession.getOcspResponse");
    }//from  w  w  w . j a  va  2 s .co m
    if (transactionLogger == null) {
        throw new InvalidParameterException(
                "Illegal to pass a null transaction logger to OcspResponseSession.getOcspResponse");
    }
    // Validate byte array.
    if (request.length > MAX_REQUEST_SIZE) {
        final String msg = intres.getLocalizedMessage("request.toolarge", MAX_REQUEST_SIZE, request.length);
        throw new MalformedRequestException(msg);
    }
    byte[] respBytes = null;
    final Date startTime = new Date();
    OCSPResp ocspResponse = null;
    // Start logging process time after we have received the request
    if (transactionLogger.isEnabled()) {
        transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
    }
    if (auditLogger.isEnabled()) {
        auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        auditLogger.paramPut(AuditLogger.OCSPREQUEST, new String(Hex.encode(request)));
    }
    OCSPReq req;
    long maxAge = OcspConfiguration.getMaxAge(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
    OCSPRespBuilder responseGenerator = new OCSPRespBuilder();
    try {
        req = translateRequestFromByteArray(request, remoteAddress, transactionLogger);
        // Get the certificate status requests that are inside this OCSP req
        Req[] ocspRequests = req.getRequestList();
        if (ocspRequests.length <= 0) {
            String infoMsg = intres.getLocalizedMessage("ocsp.errornoreqentities");
            log.info(infoMsg);
            throw new MalformedRequestException(infoMsg);
        }
        final int maxRequests = 100;
        if (ocspRequests.length > maxRequests) {
            String infoMsg = intres.getLocalizedMessage("ocsp.errortoomanyreqentities", maxRequests);
            log.info(infoMsg);
            throw new MalformedRequestException(infoMsg);
        }
        if (log.isDebugEnabled()) {
            log.debug("The OCSP request contains " + ocspRequests.length + " simpleRequests.");
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.NUM_CERT_ID, ocspRequests.length);
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
        }
        OcspSigningCacheEntry ocspSigningCacheEntry = null;
        long nextUpdate = OcspConfiguration
                .getUntilNextUpdate(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
        // Add standard response extensions
        Map<ASN1ObjectIdentifier, Extension> responseExtensions = getStandardResponseExtensions(req);
        // Look for extension OIDs
        final Collection<String> extensionOids = OcspConfiguration.getExtensionOids();
        // Look over the status requests
        List<OCSPResponseItem> responseList = new ArrayList<OCSPResponseItem>();
        boolean addExtendedRevokedExtension = false;
        Date producedAt = null;
        for (Req ocspRequest : ocspRequests) {
            CertificateID certId = ocspRequest.getCertID();
            ASN1ObjectIdentifier certIdhash = certId.getHashAlgOID();
            if (!OIWObjectIdentifiers.idSHA1.equals(certIdhash)
                    && !NISTObjectIdentifiers.id_sha256.equals(certIdhash)) {
                throw new InvalidAlgorithmException(
                        "CertID with SHA1 and SHA256 are supported, not: " + certIdhash.getId());
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.SERIAL_NOHEX,
                        certId.getSerialNumber().toByteArray());
                transactionLogger.paramPut(TransactionLogger.DIGEST_ALGOR, certId.getHashAlgOID().toString());
                transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash());
                transactionLogger.paramPut(TransactionLogger.ISSUER_KEY, certId.getIssuerKeyHash());
            }
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.ISSUER_KEY, certId.getIssuerKeyHash());
                auditLogger.paramPut(AuditLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray());
                auditLogger.paramPut(AuditLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash());
            }
            byte[] hashbytes = certId.getIssuerNameHash();
            String hash = null;
            if (hashbytes != null) {
                hash = new String(Hex.encode(hashbytes));
            }
            String infoMsg = intres.getLocalizedMessage("ocsp.inforeceivedrequest",
                    certId.getSerialNumber().toString(16), hash, remoteAddress);
            log.info(infoMsg);
            // Locate the CA which gave out the certificate
            ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(certId);
            if (ocspSigningCacheEntry == null) {
                //Could it be that we haven't updated the OCSP Signing Cache?
                ocspSigningCacheEntry = findAndAddMissingCacheEntry(certId);
            }
            if (ocspSigningCacheEntry != null) {
                if (transactionLogger.isEnabled()) {
                    // This will be the issuer DN of the signing certificate, whether an OCSP responder or an internal CA  
                    String issuerNameDn = CertTools
                            .getIssuerDN(ocspSigningCacheEntry.getFullCertificateChain().get(0));
                    transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_DN, issuerNameDn);
                }
            } else {
                /*
                 * if the certId was issued by an unknown CA 
                 * 
                 * The algorithm here: 
                 * We will sign the response with the CA that issued the last certificate(certId) in the request. If the issuing CA is not available on 
                 * this server, we sign the response with the default responderId (from params in web.xml). We have to look up the ca-certificate for 
                 * each certId in the request though, as we will check for revocation on the ca-cert as well when checking for revocation on the certId.
                 */
                // We could not find certificate for this request so get certificate for default responder
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry();
                if (ocspSigningCacheEntry != null) {
                    String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacertusedefault",
                            new String(Hex.encode(certId.getIssuerNameHash())));
                    log.info(errMsg);
                    // If we can not find the CA, answer UnknowStatus
                    responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate));
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                OCSPResponseItem.OCSP_UNKNOWN);
                        transactionLogger.writeln();
                    }
                    continue;
                } else {
                    GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession
                            .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
                    String defaultResponder = ocspConfiguration.getOcspDefaultResponderReference();
                    String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacert",
                            new String(Hex.encode(certId.getIssuerNameHash())), defaultResponder);
                    log.error(errMsg);
                    // If we are responding to multiple requests, the last found ocspSigningCacheEntry will be used in the end
                    // so even if there are not any one now, it might be later when it is time to sign the responses.
                    // Since we only will sign the entire response once if there is at least one valid ocspSigningCacheEntry
                    // we might as well include the unknown requests.
                    responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate));
                    continue;
                }
            }

            final org.bouncycastle.cert.ocsp.CertificateStatus certStatus;
            // Check if the cacert (or the default responderid) is revoked
            X509Certificate caCertificate = ocspSigningCacheEntry.getIssuerCaCertificate();
            final CertificateStatus signerIssuerCertStatus = ocspSigningCacheEntry
                    .getIssuerCaCertificateStatus();
            final String caCertificateSubjectDn = CertTools.getSubjectDN(caCertificate);
            CertificateStatusHolder certificateStatusHolder = null;
            if (signerIssuerCertStatus.equals(CertificateStatus.REVOKED)) {
                /*
                 * According to chapter 2.7 in RFC2560:
                 * 
                 * 2.7 CA Key Compromise If an OCSP responder knows that a particular CA's private key has been compromised, it MAY return the revoked
                 * state for all certificates issued by that CA.
                 */
                // If we've ended up here it's because the signer issuer certificate was revoked. 
                certStatus = new RevokedStatus(
                        new RevokedInfo(new ASN1GeneralizedTime(signerIssuerCertStatus.revocationDate),
                                CRLReason.lookup(signerIssuerCertStatus.revocationReason)));
                infoMsg = intres.getLocalizedMessage("ocsp.signcertissuerrevoked",
                        CertTools.getSerialNumberAsString(caCertificate),
                        CertTools.getSubjectDN(caCertificate));
                log.info(infoMsg);
                responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate));
                if (transactionLogger.isEnabled()) {
                    transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_REVOKED);
                    transactionLogger.writeln();
                }
            } else {
                /**
                 * Here is the actual check for the status of the sought certificate (easy to miss). Here we grab just the status if there aren't
                 * any OIDs defined (default case), but if there are we'll probably need the certificate as well. If that's the case, we'll grab
                 * the certificate in the same transaction.
                 */
                final CertificateStatus status;
                if (extensionOids.isEmpty()) {
                    status = certificateStoreSession.getStatus(caCertificateSubjectDn,
                            certId.getSerialNumber());
                } else {
                    certificateStatusHolder = certificateStoreSession
                            .getCertificateAndStatus(caCertificateSubjectDn, certId.getSerialNumber());
                    status = certificateStatusHolder.getCertificateStatus();
                }
                // If we have an OcspKeyBinding configured for this request, we override the default value
                if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                    nextUpdate = ocspSigningCacheEntry.getOcspKeyBinding().getUntilNextUpdate() * 1000L;
                }
                // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                        && OcspConfiguration.isUntilNextUpdateConfigured(status.certificateProfileId)) {
                    nextUpdate = OcspConfiguration.getUntilNextUpdate(status.certificateProfileId);
                }
                // If we have an OcspKeyBinding configured for this request, we override the default value
                if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                    maxAge = ocspSigningCacheEntry.getOcspKeyBinding().getMaxAge() * 1000L;
                }
                // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                        && OcspConfiguration.isMaxAgeConfigured(status.certificateProfileId)) {
                    maxAge = OcspConfiguration.getMaxAge(status.certificateProfileId);
                }

                final String sStatus;
                boolean addArchiveCutoff = false;
                if (status.equals(CertificateStatus.NOT_AVAILABLE)) {
                    // No revocation info available for this cert, handle it
                    if (log.isDebugEnabled()) {
                        log.debug("Unable to find revocation information for certificate with serial '"
                                + certId.getSerialNumber().toString(16) + "'" + " from issuer '"
                                + caCertificateSubjectDn + "'");
                    }
                    /* 
                     * If we do not treat non existing certificates as good or revoked
                     * OR
                     * we don't actually handle requests for the CA issuing the certificate asked about
                     * then we return unknown 
                     * */
                    if (OcspConfigurationCache.INSTANCE.isNonExistingGood(requestUrl,
                            ocspSigningCacheEntry.getOcspKeyBinding())
                            && OcspSigningCache.INSTANCE.getEntry(certId) != null) {
                        sStatus = "good";
                        certStatus = null; // null means "good" in OCSP
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_GOOD);
                        }
                    } else if (OcspConfigurationCache.INSTANCE.isNonExistingRevoked(requestUrl,
                            ocspSigningCacheEntry.getOcspKeyBinding())
                            && OcspSigningCache.INSTANCE.getEntry(certId) != null) {
                        sStatus = "revoked";
                        certStatus = new RevokedStatus(new RevokedInfo(new ASN1GeneralizedTime(new Date(0)),
                                CRLReason.lookup(CRLReason.certificateHold)));
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_REVOKED);
                        }
                        addExtendedRevokedExtension = true;
                    } else {
                        sStatus = "unknown";
                        certStatus = new UnknownStatus();
                        if (transactionLogger.isEnabled()) {
                            transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                    OCSPResponseItem.OCSP_UNKNOWN);
                        }
                    }
                } else if (status.equals(CertificateStatus.REVOKED)) {
                    // Revocation info available for this cert, handle it
                    sStatus = "revoked";
                    certStatus = new RevokedStatus(
                            new RevokedInfo(new ASN1GeneralizedTime(status.revocationDate),
                                    CRLReason.lookup(status.revocationReason)));
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS,
                                OCSPResponseItem.OCSP_REVOKED);
                    }
                    // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                    if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                            && OcspConfiguration
                                    .isRevokedUntilNextUpdateConfigured(status.certificateProfileId)) {
                        nextUpdate = OcspConfiguration.getRevokedUntilNextUpdate(status.certificateProfileId);
                    }
                    // If we have an explicit value configured for this certificate profile, we override the the current value with this value
                    if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE
                            && OcspConfiguration.isRevokedMaxAgeConfigured(status.certificateProfileId)) {
                        maxAge = OcspConfiguration.getRevokedMaxAge(status.certificateProfileId);
                    }
                } else {
                    sStatus = "good";
                    certStatus = null;
                    if (transactionLogger.isEnabled()) {
                        transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_GOOD);
                    }
                    addArchiveCutoff = checkAddArchiveCuttoff(caCertificateSubjectDn, certId);
                }

                if (log.isDebugEnabled()) {
                    log.debug("Set nextUpdate=" + nextUpdate + ", and maxAge=" + maxAge
                            + " for certificateProfileId=" + status.certificateProfileId);
                }

                infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", sStatus,
                        certId.getSerialNumber().toString(16), caCertificateSubjectDn);
                log.info(infoMsg);
                OCSPResponseItem respItem = new OCSPResponseItem(certId, certStatus, nextUpdate);
                if (addArchiveCutoff) {
                    addArchiveCutoff(respItem);
                    producedAt = new Date();
                }
                responseList.add(respItem);
                if (transactionLogger.isEnabled()) {
                    transactionLogger.writeln();
                }
            }
            for (String oidstr : extensionOids) {
                boolean useAlways = false;
                if (oidstr.startsWith("*")) {
                    oidstr = oidstr.substring(1, oidstr.length());
                    useAlways = true;
                }
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(oidstr);
                Extension extension = null;
                if (!useAlways) {
                    // Only check if extension exists if we are not already bound to use it
                    if (req.hasExtensions()) {
                        extension = req.getExtension(oid);
                    }
                }
                //If found, or if it should be used anyway
                if (useAlways || extension != null) {
                    // We found an extension, call the extension class
                    if (log.isDebugEnabled()) {
                        log.debug("Found OCSP extension oid: " + oidstr);
                    }
                    OCSPExtension extObj = OcspExtensionsCache.INSTANCE.getExtensions().get(oidstr);
                    if (extObj != null) {
                        // Find the certificate from the certId
                        if (certificateStatusHolder != null
                                && certificateStatusHolder.getCertificate() != null) {
                            X509Certificate cert = (X509Certificate) certificateStatusHolder.getCertificate();
                            // Call the OCSP extension
                            Map<ASN1ObjectIdentifier, Extension> retext = extObj.process(requestCertificates,
                                    remoteAddress, remoteHost, cert, certStatus);
                            if (retext != null) {
                                // Add the returned X509Extensions to the responseExtension we will add to the basic OCSP response
                                responseExtensions.putAll(retext);
                            } else {
                                String errMsg = intres.getLocalizedMessage("ocsp.errorprocessextension",
                                        extObj.getClass().getName(),
                                        Integer.valueOf(extObj.getLastErrorCode()));
                                log.error(errMsg);
                            }
                        }
                    }
                }
            }
        }
        if (addExtendedRevokedExtension) {
            // id-pkix-ocsp-extended-revoke OBJECT IDENTIFIER ::= {id-pkix-ocsp 9}
            final ASN1ObjectIdentifier extendedRevokedOID = new ASN1ObjectIdentifier(
                    OCSPObjectIdentifiers.id_pkix_ocsp + ".9");
            try {
                responseExtensions.put(extendedRevokedOID,
                        new Extension(extendedRevokedOID, false, DERNull.INSTANCE.getEncoded()));
            } catch (IOException e) {
                throw new IllegalStateException("Could not get encodig from DERNull.", e);
            }
        }
        if (ocspSigningCacheEntry != null) {
            // Add responseExtensions
            Extensions exts = new Extensions(responseExtensions.values().toArray(new Extension[0]));
            // generate the signed response object
            BasicOCSPResp basicresp = signOcspResponse(req, responseList, exts, ocspSigningCacheEntry,
                    producedAt);
            ocspResponse = responseGenerator.build(OCSPRespBuilder.SUCCESSFUL, basicresp);
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL);
            }
        } else {
            // Only unknown CAs in requests and no default responder's cert, return an unsigned response
            if (log.isDebugEnabled()) {
                log.debug(intres.getLocalizedMessage("ocsp.errornocacreateresp"));
            }
            ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null);
            if (auditLogger.isEnabled()) {
                auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            }
            if (transactionLogger.isEnabled()) {
                transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            }
        }
    } catch (SignRequestException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.SIG_REQUIRED, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED);
        }
    } catch (SignRequestSignatureException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED);
        }
    } catch (InvalidAlgorithmException e) {
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME);
        }
        String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage());
        log.info(errMsg); // No need to log the full exception here
        // RFC 2560: responseBytes are not set on error.
        ocspResponse = responseGenerator.build(OCSPRespBuilder.MALFORMED_REQUEST, null);
        if (transactionLogger.isEnabled()) {
            transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST);
            transactionLogger.writeln();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST);
        }
    } catch (NoSuchAlgorithmException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    } catch (CertificateException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    } catch (CryptoTokenOfflineException e) {
        ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e);
    }
    try {
        respBytes = ocspResponse.getEncoded();
        if (auditLogger.isEnabled()) {
            auditLogger.paramPut(AuditLogger.OCSPRESPONSE, new String(Hex.encode(respBytes)));
            auditLogger.writeln();
            auditLogger.flush();
        }
        if (transactionLogger.isEnabled()) {
            transactionLogger.flush();
        }
        if (OcspConfiguration.getLogSafer()) {
            // See if the Errorhandler has found any problems
            if (hasErrorHandlerFailedSince(startTime)) {
                log.info("ProbableErrorhandler reported error, cannot answer request");
                // RFC 2560: responseBytes are not set on error.
                ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null);

            }
            // See if the Appender has reported any problems
            if (!CanLogCache.INSTANCE.canLog()) {
                log.info("SaferDailyRollingFileAppender reported error, cannot answer request");
                // RFC 2560: responseBytes are not set on error.
                ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null);
            }
        }
    } catch (IOException e) {
        log.error("Unexpected IOException caught.", e);
        if (transactionLogger.isEnabled()) {
            transactionLogger.flush();
        }
        if (auditLogger.isEnabled()) {
            auditLogger.flush();
        }
    }
    return new OcspResponseInformation(ocspResponse, maxAge);
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

License:Open Source License

private void addArchiveCutoff(OCSPResponseItem respItem) {
    long archPeriod = OcspConfiguration.getExpiredArchiveCutoff();
    if (archPeriod == -1) {
        return;/*  w  w  w  .  ja v  a 2 s  .  c o  m*/
    }
    long res = System.currentTimeMillis() - archPeriod;
    ExtensionsGenerator gen = new ExtensionsGenerator();
    try {
        gen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff, false,
                new ASN1GeneralizedTime(new Date(res)));
    } catch (IOException e) {
        throw new IllegalStateException("IOException was caught when decoding static value.", e);
    }
    Extensions exts = gen.generate();
    respItem.setExtentions(exts);
}

From source file:org.cesecore.util.PrintableStringNameStyle.java

License:Open Source License

@Override
public ASN1Encodable stringToValue(ASN1ObjectIdentifier oid, String value) {
    if (value.length() != 0 && value.charAt(0) == '#') {
        try {/*ww w  . j  a v a  2 s . co m*/
            return IETFUtils.valueFromHexString(value, 1);
        } catch (IOException e) {
            throw new RuntimeException("can't recode value for oid " + oid.getId());
        }
    } else if (value.length() != 0 && value.charAt(0) == '\\') {
        value = value.substring(1);
    } else if (oid.equals(CeSecoreNameStyle.EmailAddress) || oid.equals(CeSecoreNameStyle.DC)) {
        return new DERIA5String(value);
    } else if (oid.equals(DATE_OF_BIRTH)) // accept time string as well as # (for compatibility)
    {
        return new ASN1GeneralizedTime(value);
    } else if (canBePrintable(value)) {
        return new DERPrintableString(value);
    }

    return new DERUTF8String(value);
}

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

License:Open Source License

@Test
public void testLegacyEncodedRequestOverride() throws Exception {
    reconfigureCA(false, false, false);/*from  w  w  w  .jav  a  2  s  . co  m*/
    // Setup "Allow subject DN override" and "Allow certificate serial number override" in used cert profile
    reconfigureCertificateProfile(true, true);
    final String issuerDn = CertTools.getSubjectDN(getTestCACert(TESTCA_NAME));
    final X500Name issuerX500Name = new X500Name(issuerDn);
    final org.bouncycastle.asn1.crmf.CertTemplateBuilder certTemplate = new org.bouncycastle.asn1.crmf.CertTemplateBuilder();
    certTemplate.setIssuer(issuerX500Name);
    final KeyPair keyPair = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final String serialNumber = "88883311121333FF33012345";
    final byte[] transactionId = new byte[16];
    final byte[] senderNonce = new byte[16];
    final Random random = new Random();
    random.nextBytes(transactionId);
    random.nextBytes(senderNonce);
    final String subjectDn = "C=SE,O=PrimeKey,OU=Labs,CN=Sec_" + serialNumber;
    final X500Name subjectX500Name = CertTools.stringToBcX500Name(subjectDn, new TeletexNamingStyle(), false);
    certTemplate.setSubject(subjectX500Name);
    final byte[] bytes = keyPair.getPublic().getEncoded();
    final ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    final org.bouncycastle.asn1.ASN1InputStream asn1InputStream = new org.bouncycastle.asn1.ASN1InputStream(
            bIn);
    final org.bouncycastle.asn1.x509.SubjectPublicKeyInfo keyInfo = new org.bouncycastle.asn1.x509.SubjectPublicKeyInfo(
            (org.bouncycastle.asn1.ASN1Sequence) asn1InputStream.readObject());
    asn1InputStream.close();
    certTemplate.setPublicKey(keyInfo);
    // Request a custom certificate serial number
    certTemplate.setSerialNumber(new ASN1Integer(new BigInteger(serialNumber, 16)));
    final org.bouncycastle.asn1.crmf.ProofOfPossession myProofOfPossession = new org.bouncycastle.asn1.crmf.ProofOfPossession();
    final CertRequest certRequest = new CertRequest(4, certTemplate.build(), null);
    final AttributeTypeAndValue[] avs = { new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(PBE_SECRET)) };
    final CertReqMsg certReqMsg = new CertReqMsg(certRequest, myProofOfPossession, avs);
    final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg);
    PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder(2, new GeneralName(subjectX500Name),
            new GeneralName(new X500Name(issuerDn)));
    pkiHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    pkiHeader.setSenderNonce(new DEROctetString(senderNonce));
    pkiHeader.setTransactionID(new DEROctetString(transactionId));
    pkiHeader.setProtectionAlg(null);
    final DEROctetString senderKID = null;
    pkiHeader.setSenderKID(senderKID);
    final PKIBody pkiBody = new PKIBody(0, certReqMessages);
    final PKIMessage pkiMessage = new PKIMessage(pkiHeader.build(), pkiBody);
    final PKIMessage req = protectPKIMessage(pkiMessage, false, PBE_SECRET, "unusedKeyId", 567);
    assertNotNull("Request was not created properly.", req);
    final CertReqMessages initializationRequest = (CertReqMessages) req.getBody().getContent();
    final int requestId = initializationRequest.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue()
            .intValue();
    final byte[] reqBytes = req.getEncoded();
    final byte[] cmpResponse = sendCmpHttp(reqBytes, 200, configAlias);
    final X509Certificate cert = checkCmpCertRepMessage(subjectX500Name, this.caCertificate, cmpResponse,
            requestId);
    LOG.debug("Request:\n" + new String(CertTools.getPEMFromCertificateRequest(certRequest.getEncoded())));
    LOG.debug("Result:\n" + new String(
            CertTools.getPemFromCertificateChain(new ArrayList<Certificate>(Arrays.asList(cert)))));
    final byte[] requestSubjectyX500Principal = cert.getSubjectX500Principal().getEncoded();
    final byte[] responeSubjectyX500Principal = subjectX500Name.getEncoded();
    assertTrue("Requested X500Name was not returned the same way as requested.",
            Arrays.equals(requestSubjectyX500Principal, responeSubjectyX500Principal));
    // We cannot assume that the unique serial number index is enabled, and hence we cant be sure that our serial number override was allowed, but at least we can print it
    LOG.info("Requested serial number: " + serialNumber);
    LOG.info("Response serial number:  " + CertTools.getSerialNumberAsString(cert));
}

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

License:Open Source License

protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys,
        Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions,
        Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException,
        InvalidKeyException, SignatureException {
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    if (notBefore != null) {
        nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    }/*from   w ww .j a va2 s  .  com*/
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    if (notAfter != null) {
        na = new org.bouncycastle.asn1.x509.Time(notAfter);
    }
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(issuerDN));
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    Extensions exts = extensions;
    if (exts == null) {

        // SubjectAltName
        // Some altNames
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dOut = new ASN1OutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        if (altNames != null) {
            GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
            dOut.writeObject(san);
            byte[] value = bOut.toByteArray();
            extgen.addExtension(Extension.subjectAlternativeName, false, value);
        }

        // KeyUsage
        int bcku = 0;
        bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
        KeyUsage ku = new KeyUsage(bcku);
        extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(
            new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName())));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
                                                           // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

protected static PKIMessage genRevReq(String issuerDN, X500Name userDN, BigInteger serNo, Certificate cacert,
        byte[] nonce, byte[] transid, boolean crlEntryExtension, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws IOException {
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(userDN);//  w w w  .ja v  a2  s . c o m
    myCertTemplate.setSerialNumber(new ASN1Integer(serNo));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    CRLReason crlReason;
    if (crlEntryExtension) {
        crlReason = CRLReason.lookup(CRLReason.cessationOfOperation);
    } else {
        crlReason = CRLReason.lookup(CRLReason.keyCompromise);
    }
    extgen.addExtension(Extension.reasonCode, false, crlReason);

    Extensions exts = extgen.generate();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(myCertTemplate.build());
    v.add(exts);
    ASN1Sequence seq = new DERSequence(v);

    RevDetails myRevDetails = RevDetails.getInstance(seq); //new RevDetails(myCertTemplate.build(), exts);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new X500Name(((X509Certificate) cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

protected static PKIMessage genCertConfirm(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        String hash, int certReqId) {

    String issuerDN = "CN=foobarNoCA";
    if (cacert != null) {
        issuerDN = ((X509Certificate) cacert).getSubjectDN().getName();
    }//from ww  w .ja  v  a 2 s.c o  m
    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new X500Name(issuerDN)));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    CertStatus cs = new CertStatus(hash.getBytes(), new BigInteger(Integer.toString(certReqId)));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(cs);
    CertConfirmContent cc = CertConfirmContent.getInstance(new DERSequence(v));

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_CERT_CONFIRM, cc); // Cert Confirm
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}