Example usage for org.bouncycastle.asn1.x509 Extension deltaCRLIndicator

List of usage examples for org.bouncycastle.asn1.x509 Extension deltaCRLIndicator

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension deltaCRLIndicator.

Prototype

ASN1ObjectIdentifier deltaCRLIndicator

To view the source code for org.bouncycastle.asn1.x509 Extension deltaCRLIndicator.

Click Source Link

Document

Delta CRL indicator

Usage

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509CRL generateCrl(PrivateKey issuerPrivateKey, X509Certificate issuerCertificate,
        DateTime thisUpdate, DateTime nextUpdate, List<String> deltaCrlUris, boolean deltaCrl,
        List<RevokedCertificate> revokedCertificates, String signatureAlgorithm,
        long numberOfRevokedCertificates)
        throws InvalidKeyException, CRLException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException, IOException, OperatorCreationException {

    X500Name issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    X509v2CRLBuilder x509v2crlBuilder = new X509v2CRLBuilder(issuerName, thisUpdate.toDate());
    x509v2crlBuilder.setNextUpdate(nextUpdate.toDate());

    for (RevokedCertificate revokedCertificate : revokedCertificates) {
        x509v2crlBuilder.addCRLEntry(revokedCertificate.serialNumber,
                revokedCertificate.revocationDate.toDate(), CRLReason.privilegeWithdrawn);
    }/*  w  ww.java 2 s.  com*/
    if (-1 != numberOfRevokedCertificates) {
        SecureRandom secureRandom = new SecureRandom();
        while (numberOfRevokedCertificates-- > 0) {
            BigInteger serialNumber = new BigInteger(128, secureRandom);
            Date revocationDate = new Date();
            x509v2crlBuilder.addCRLEntry(serialNumber, revocationDate, CRLReason.privilegeWithdrawn);
        }
    }

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    x509v2crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
            extensionUtils.createAuthorityKeyIdentifier(issuerCertificate));
    x509v2crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.ONE));

    if (null != deltaCrlUris && !deltaCrlUris.isEmpty()) {
        DistributionPoint[] deltaCrlDps = new DistributionPoint[deltaCrlUris.size()];
        for (int i = 0; i < deltaCrlUris.size(); i++) {
            deltaCrlDps[i] = getDistributionPoint(deltaCrlUris.get(i));
        }
        CRLDistPoint crlDistPoint = new CRLDistPoint((DistributionPoint[]) deltaCrlDps);
        x509v2crlBuilder.addExtension(Extension.freshestCRL, false, crlDistPoint);
    }

    if (deltaCrl) {
        x509v2crlBuilder.addExtension(Extension.deltaCRLIndicator, true, new CRLNumber(BigInteger.ONE));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);

    X509CRLHolder x509crlHolder = x509v2crlBuilder.build(contentSigner);
    byte[] crlValue = x509crlHolder.getEncoded();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(new ByteArrayInputStream(crlValue));
    return crl;
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get extension value as a string./* w w w . j a  v a 2  s.c  o  m*/
 * 
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 * @throws ParseException If a date formatting problem occurs
 */
public String getStringValue() throws IOException, ParseException {
    // Get octet string from extension
    byte[] bOctets = ((ASN1OctetString) ASN1Primitive.fromByteArray(m_bValue)).getOctets();

    // Octet string processed differently depending on extension type
    if (m_Oid.equals(X509ObjectIdentifiers.commonName)) {
        return getCommonNameStringValue(bOctets);
    } else if (m_Oid.equals(Extension.subjectKeyIdentifier)) {
        return getSubjectKeyIdentifierStringValue(bOctets);
    } else if (m_Oid.equals(Extension.keyUsage)) {
        return getKeyUsageStringValue(bOctets);
    } else if (m_Oid.equals(Extension.privateKeyUsagePeriod)) {
        return getPrivateKeyUsagePeriod(bOctets);
    } else if (m_Oid.equals(Extension.issuerAlternativeName)
            || m_Oid.equals(Extension.subjectAlternativeName)) {
        return getAlternativeName(bOctets);
    } else if (m_Oid.equals(Extension.basicConstraints)) {
        return getBasicConstraintsStringValue(bOctets);
    } else if (m_Oid.equals(Extension.cRLNumber)) {
        return getCrlNumberStringValue(bOctets);
    } else if (m_Oid.equals(Extension.reasonCode)) {
        return getReasonCodeStringValue(bOctets);
    } else if (m_Oid.equals(Extension.instructionCode)) {
        return getHoldInstructionCodeStringValue(bOctets);
    } else if (m_Oid.equals(Extension.invalidityDate)) {
        return getInvalidityDateStringValue(bOctets);
    } else if (m_Oid.equals(Extension.deltaCRLIndicator)) {
        return getDeltaCrlIndicatorStringValue(bOctets);
    } else if (m_Oid.equals(Extension.certificateIssuer)) {
        return getCertificateIssuerStringValue(bOctets);
    } else if (m_Oid.equals(Extension.policyMappings)) {
        return getPolicyMappingsStringValue(bOctets);
    } else if (m_Oid.equals(Extension.authorityKeyIdentifier)) {
        return getAuthorityKeyIdentifierStringValue(bOctets);
    } else if (m_Oid.equals(Extension.policyConstraints)) {
        return getPolicyConstraintsStringValue(bOctets);
    } else if (m_Oid.equals(Extension.extendedKeyUsage)) {
        return getExtendedKeyUsageStringValue(bOctets);
    } else if (m_Oid.equals(Extension.inhibitAnyPolicy)) {
        return getInhibitAnyPolicyStringValue(bOctets);
    } else if (m_Oid.equals(MiscObjectIdentifiers.entrustVersionExtension)) {
        return getEntrustVersionExtensionStringValue(bOctets);
    } else if (m_Oid.equals(PKCSObjectIdentifiers.pkcs_9_at_smimeCapabilities)) {
        return getSmimeCapabilitiesStringValue(bOctets);
    } else if (m_Oid.equals(MicrosoftObjectIdentifiers.microsoftCaVersion)) {
        return getMicrosoftCAVersionStringValue(bOctets);
    } else if (m_Oid.equals(MicrosoftObjectIdentifiers.microsoftPrevCaCertHash)) {
        return getMicrosoftPreviousCACertificateHashStringValue(bOctets);
    } else if (m_Oid.equals(MicrosoftObjectIdentifiers.microsoftCertTemplateV2)) {
        return getMicrosoftCertificateTemplateV2StringValue(bOctets);
    } else if (m_Oid.equals(MicrosoftObjectIdentifiers.microsoftAppPolicies)) {
        return getUnknownOidStringValue(bOctets); // TODO
    }
    // TODO: https://github.com/bcgit/bc-java/pull/92
    else if (m_Oid.toString().equals("1.3.6.1.4.1.311.21.4")) {
        return getMicrosoftCrlNextPublish(bOctets);
    } else if (m_Oid.equals(Extension.authorityInfoAccess) || m_Oid.equals(Extension.subjectInfoAccess)) {
        return getInformationAccessStringValue(bOctets);
    } else if (m_Oid.equals(Extension.logoType)) {
        return getLogotypeStringValue(bOctets);
    } else if (m_Oid.equals(MiscObjectIdentifiers.novellSecurityAttribs)) {
        return getNovellSecurityAttributesStringValue(bOctets);
    } else if (m_Oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
        return getNetscapeCertificateTypeStringValue(bOctets);
    } else if (m_Oid.equals(MiscObjectIdentifiers.netscapeSSLServerName)
            || m_Oid.equals(MiscObjectIdentifiers.netscapeCertComment)
            || m_Oid.equals(MiscObjectIdentifiers.verisignDnbDunsNumber)
            || m_Oid.equals(MicrosoftObjectIdentifiers.microsoftCertTemplateV1)) {
        return getASN1ObjectString(bOctets);
    } else if (m_Oid.equals(MiscObjectIdentifiers.netscapeCApolicyURL)) {
        return getNetscapeExtensionURLValue(bOctets, LinkClass.BROWSER);
    } else if (m_Oid.equals(MiscObjectIdentifiers.netscapeBaseURL)
            || m_Oid.equals(MiscObjectIdentifiers.netscapeRenewalURL)
            || m_Oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)
            || m_Oid.equals(MiscObjectIdentifiers.netscapeCARevocationURL)) {
        return getNetscapeExtensionURLValue(bOctets, LinkClass.CRL);
    } else if (m_Oid.equals(Extension.cRLDistributionPoints)) {
        return getCrlDistributionPointsStringValue(bOctets);
    } else if (m_Oid.equals(Extension.certificatePolicies)) {
        return getCertificatePoliciesStringValue(bOctets);
    }

    // TODO:
    // - CERTIFICATE_POLICIES_OLD_OID
    // - AUTHORITY_KEY_IDENTIFIER_OLD_OID
    // - BASIC_CONSTRAINTS_OLD_0_OID

    // Don't know how to process the extension
    // and clear text
    else {
        return getUnknownOidStringValue(bOctets);
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Generate a CRL or a deltaCRL/*from  w ww .  ja va 2 s. c  o  m*/
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}

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

License:Open Source License

/** Returns the delta crl indicator number if it exists as a CRL extension
 * //from w w w.  ja  v a2s  .  c o  m
 * @return the BaseCRLNumber, or -1 if no delta crl indicator extension was found or an error reading it occurred. Never return null.
 */
public static BigInteger getDeltaCRLIndicator(X509CRL crl) {
    BigInteger ret = BigInteger.valueOf(-1);
    try {
        ASN1Primitive obj = CrlExtensions.getExtensionValue(crl, Extension.deltaCRLIndicator.getId());
        if (obj != null) {
            CRLNumber crlnum = CRLNumber.getInstance(obj);
            if (crlnum != null) {
                ret = crlnum.getCRLNumber();
            }
        }
    } catch (IOException e) {
        log.error("Error reading CRL number extension: ", e);
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java

License:Open Source License

/**
 * Writes the CRL to a temporary file and executes an external command with
 * the temporary file as argument. By default, a PublisherException is
 * thrown if the external command returns with an errorlevel or outputs to
 * stderr./*from w  ww. j  a v a  2s .  c  o m*/
 * 
 * @see org.ejbca.core.model.ca.publisher.ICustomPublisher#storeCRL(org.ejbca.core.model.log.Admin,
 *      byte[], java.lang.String, int)
 */
public boolean storeCRL(AuthenticationToken admin, byte[] incrl, String cafp, int number, String userDN)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCRL, Storing CRL");
    }
    // Verify initialization
    if (crlExternalCommandFileName == null) {
        String msg = intres.getLocalizedMessage("publisher.errormissingproperty",
                crlExternalCommandPropertyName);
        log.error(msg);
        throw new PublisherException(msg);
    }

    List<String> additionalArguments = new ArrayList<String>();

    if (calclulateDeltaCrlLocally) {
        X509CRL crl;
        try {
            crl = CertTools.getCRLfromByteArray(incrl);
            additionalArguments
                    .add(Boolean.toString(crl.getExtensionValue(Extension.deltaCRLIndicator.getId()) != null));
        } catch (CRLException e) {
            log.error("Byte array does not contain a correct CRL.", e);
        }

    }

    // Run internal method to create tempfile and run the command
    runWithTempFile(crlExternalCommandFileName, incrl, crlFailOnErrorCode, crlFailOnStandardError,
            additionalArguments);
    if (log.isTraceEnabled()) {
        log.trace("<storeCRL");
    }
    return true;
}

From source file:org.ejbca.core.model.ca.publisher.LdapPublisher.java

License:Open Source License

/**
 * @see org.ejbca.core.model.ca.publisher.BasePublisher#storeCRL
 *//*  ww w.j a v a  2 s  . co m*/
public boolean storeCRL(AuthenticationToken admin, byte[] incrl, String cafp, int number, String userDN)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCRL");
    }
    int ldapVersion = LDAPConnection.LDAP_V3;

    final String dn;
    final String crldn;
    final boolean isDeltaCRL;
    try {
        // Extract the users DN from the crl. Use the least number of encodings...
        final X509CRL crl = CertTools.getCRLfromByteArray(incrl);
        crldn = CertTools.stringToBCDNString(crl.getIssuerDN().toString());
        // Is it a delta CRL?
        if (crl.getExtensionValue(Extension.deltaCRLIndicator.getId()) != null) {
            isDeltaCRL = true;
        } else {
            isDeltaCRL = false;
        }
        // Construct the DN used for the LDAP object entry
        dn = constructLDAPDN(crldn, userDN);
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("publisher.errorldapdecode", "CRL");
        log.error(msg, e);
        throw new PublisherException(msg);
    }

    LDAPConnection lc = createLdapConnection();

    // Check if the entry is already present, we will update it with the new CRL.
    LDAPEntry oldEntry = searchOldEntity(null, ldapVersion, lc, crldn, userDN, null);

    LDAPEntry newEntry = null;
    ArrayList<LDAPModification> modSet = new ArrayList<LDAPModification>();
    LDAPAttributeSet attributeSet = null;

    if (oldEntry != null) {
        modSet = getModificationSet(oldEntry, crldn, null, false, false, null, null);
    } else {
        attributeSet = getAttributeSet(null, this.getCAObjectClass(), crldn, null, true, false, null, null);
    }

    if (isDeltaCRL) {
        // It's a delta CRL.
        LDAPAttribute attr = new LDAPAttribute(getDeltaCRLAttribute(), incrl);
        if (oldEntry != null) {
            modSet.add(new LDAPModification(LDAPModification.REPLACE, attr));
        } else {
            attributeSet.add(attr);
        }
    } else {
        // It's a CRL
        LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), incrl);
        LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), incrl);
        if (oldEntry != null) {
            modSet.add(new LDAPModification(LDAPModification.REPLACE, crlAttr));
            modSet.add(new LDAPModification(LDAPModification.REPLACE, arlAttr));
        } else {
            attributeSet.add(crlAttr);
            attributeSet.add(arlAttr);
        }
    }
    if (oldEntry == null) {
        newEntry = new LDAPEntry(dn, attributeSet);
    }
    // Try all the listed servers
    Iterator<String> servers = getHostnameList().iterator();
    boolean connectionFailed;
    do {
        connectionFailed = false;
        String currentServer = servers.next();
        try {
            TCPTool.probeConnectionLDAP(currentServer, Integer.parseInt(getPort()), getConnectionTimeOut()); // Avoid waiting for halfdead-servers
            // connect to the server
            lc.connect(currentServer, Integer.parseInt(getPort()));
            // Execute a STARTTLS handshake if it was requested.
            if (getConnectionSecurity() == ConnectionSecurity.STARTTLS) {
                if (log.isDebugEnabled()) {
                    log.debug("STARTTLS to LDAP server " + currentServer);
                }
                lc.startTLS();
            }
            // authenticate to the server
            lc.bind(ldapVersion, getLoginDN(), getLoginPassword().getBytes("UTF8"), ldapBindConstraints);
            // Add or modify the entry
            if (oldEntry != null) {
                LDAPModification[] mods = new LDAPModification[modSet.size()];
                mods = (LDAPModification[]) modSet.toArray(mods);
                lc.modify(dn, mods, ldapStoreConstraints);
                String msg = intres.getLocalizedMessage("publisher.ldapmodify", "CRL", dn);
                log.info(msg);
            } else {
                lc.add(newEntry, ldapStoreConstraints);
                String msg = intres.getLocalizedMessage("publisher.ldapadd", "CRL", dn);
                log.info(msg);
            }
        } catch (LDAPException e) {
            connectionFailed = true;
            if (servers.hasNext()) {
                log.warn("Failed to publish to " + currentServer + ". Trying next in list.");
            } else {
                String msg = intres.getLocalizedMessage("publisher.errorldapstore", "CRL", getCRLAttribute(),
                        getCAObjectClass(), dn, e.getMessage());
                log.error(msg, e);
                throw new PublisherException(msg);
            }
        } catch (UnsupportedEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorpassword", getLoginPassword());
            log.error(msg, e);
            throw new PublisherException(msg);
        } finally {
            // disconnect with the server
            try {
                lc.disconnect(ldapDisconnectConstraints);
            } catch (LDAPException e) {
                String msg = intres.getLocalizedMessage("publisher.errordisconnect");
                log.error(msg, e);
            }
        }
    } while (connectionFailed && servers.hasNext());
    if (log.isTraceEnabled()) {
        log.trace("<storeCRL");
    }
    return true;
}

From source file:org.xipki.ca.client.shell.GetCRLCommand.java

License:Open Source License

@Override
protected Object _doExecute() throws Exception {
    Set<String> caNames = caClient.getCaNames();
    if (isEmpty(caNames)) {
        throw new IllegalCmdParamException("no CA is configured");
    }/*from  w  w w .  ja v a 2  s.  c o m*/

    if (caName != null && !caNames.contains(caName)) {
        throw new IllegalCmdParamException("CA " + caName + " is not within the configured CAs " + caNames);
    }

    if (caName == null) {
        if (caNames.size() == 1) {
            caName = caNames.iterator().next();
        } else {
            throw new IllegalCmdParamException("no caname is specified, one of " + caNames + " is required");
        }
    }

    X509CRL crl = null;
    try {
        crl = retrieveCRL(caName);
    } catch (PKIErrorException e) {
        throw new CmdFailure("received no CRL from server: " + e.getMessage());
    }

    if (crl == null) {
        throw new CmdFailure("received no CRL from server");
    }

    saveVerbose("saved CRL to file", new File(outFile), crl.getEncoded());

    if (withBaseCRL.booleanValue()) {
        byte[] octetString = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
        if (octetString != null) {
            if (baseCRLOut == null) {
                baseCRLOut = outFile + "-baseCRL";
            }

            byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
            BigInteger baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();

            RequestResponseDebug debug = getRequestResponseDebug();
            try {
                crl = caClient.downloadCRL(caName, baseCrlNumber, debug);
            } catch (PKIErrorException e) {
                throw new CmdFailure("received no baseCRL from server: " + e.getMessage());
            } finally {
                saveRequestResponse(debug);
            }

            if (crl == null) {
                throw new CmdFailure("received no baseCRL from server");
            } else {
                saveVerbose("saved baseCRL to file", new File(baseCRLOut), crl.getEncoded());
            }
        }
    }

    return null;
}

From source file:org.xipki.ca.server.impl.store.CertStoreQueryExecutor.java

License:Open Source License

void addCRL(final X509CertWithDBCertId caCert, final X509CRL crl)
        throws DataAccessException, CRLException, OperationException {
    byte[] encodedExtnValue = crl.getExtensionValue(Extension.cRLNumber.getId());
    Long crlNumber = null;//from  w w  w  . ja v  a 2 s .  c o m
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }

    encodedExtnValue = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
    Long baseCrlNumber = null;
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }

    final String sql = "INSERT INTO CRL (ID, CA_ID, CRL_NO, THISUPDATE, NEXTUPDATE, DELTACRL, BASECRL_NO, CRL)"
            + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    int currentMaxCrlId = (int) dataSource.getMax(null, "CRL", "ID");
    int crlId = currentMaxCrlId + 1;

    PreparedStatement ps = null;

    try {
        int caId = getCaId(caCert);
        ps = borrowPreparedStatement(sql);

        int idx = 1;
        ps.setInt(idx++, crlId);
        ps.setInt(idx++, caId);
        if (crlNumber != null) {
            ps.setInt(idx++, crlNumber.intValue());
        } else {
            ps.setNull(idx++, Types.INTEGER);
        }
        Date d = crl.getThisUpdate();
        ps.setLong(idx++, d.getTime() / 1000);
        d = crl.getNextUpdate();
        if (d != null) {
            ps.setLong(idx++, d.getTime() / 1000);
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }

        ps.setInt(idx++, baseCrlNumber != null ? 1 : 0);

        if (baseCrlNumber != null) {
            ps.setLong(idx++, baseCrlNumber);
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }

        byte[] encodedCrl = crl.getEncoded();
        String b64Crl = Base64.toBase64String(encodedCrl);
        ps.setString(idx++, b64Crl);

        ps.executeUpdate();
    } catch (SQLException e) {
        throw dataSource.translate(sql, e);
    } finally {
        releaseDbResources(ps, null);
    }
}

From source file:org.xipki.commons.console.karaf.completer.ExtensionNameCompleter.java

License:Open Source License

public ExtensionNameCompleter() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);
    oids.add(ObjectIdentifiers.id_pe_tlsfeature);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();/*from www .j av a  2  s .co m*/
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}

From source file:org.xipki.console.karaf.impl.completer.ExtensionNameCompleterImpl.java

License:Open Source License

public ExtensionNameCompleterImpl() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//from  www . j  ava 2 s  .  c  om
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}