Example usage for java.security.cert X509Certificate getSerialNumber

List of usage examples for java.security.cert X509Certificate getSerialNumber

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSerialNumber.

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validatePem(CertificateBundle certificateBundle, String subjectName)
        throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException,
        InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();

    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);

    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);/*w ww  . j  ava  2s.c  o  m*/
    Assert.assertTrue(certificates.size() == 1);

    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * Return the user associated to a certiciate in LDAP server
 * @param x509Certificate//www  .j  a  v a 2s  . c o m
 * @return the user of the certificate or null if no associate exist
 */
public User getUserByCertificate(X509Certificate x509Certificate) {

    if (logger.isInfoEnabled()) {
        logger.info("Get user for serial number " + x509Certificate.getSerialNumber().toString(16));
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    AndFilter filterS = new AndFilter();
    filterS.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, USERS_CLASS));
    filterS.and(new LikeFilter("userCertificate", "*"));
    for (String rdn : rdnUsers) {
        List serialNumbers = ldapTemplate.search(rdn, filterS.encode(), new AbstractContextMapper() {
            public Object doMapFromContext(DirContextOperations ctx) {

                try {
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

                    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(
                            new ByteArrayInputStream((byte[]) ctx.getObjectAttribute(CERTIFICATE_ATTRIBUTE)));

                    if (ctx.getStringAttribute(MAIL_ATTRIBUTE) == null)
                        ctx.setAttributeValue(MAIL_ATTRIBUTE, "");
                    if (ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE) == null)
                        ctx.setAttributeValue(COMMON_NAME_ATTRIBUTE, "");

                    String uid = ctx.getStringAttribute(UID_ATTRIBUTE);

                    //get the date of last modify of this user
                    LdapTemplate tmp = new LdapTemplate();
                    tmp.setContextSource(ldapContextSource);
                    final String[] attrOp = { MODIFY_TIMESTAMP_ATTRIBUTE };
                    Object o = tmp.lookup(ctx.getDn(), attrOp, new ContextMapper() {
                        public Object mapFromContext(Object ctx) {
                            DirContextAdapter adapter = (DirContextAdapter) ctx;
                            return adapter.getStringAttribute(attrOp[0]);

                        }
                    }

                    );

                    Date lastPasswordChange; //the time of last change for the entry
                    if (o != null) {
                        String modifyTimestamp = o.toString();
                        lastPasswordChange = getDate(modifyTimestamp);
                    } else {
                        //if the modifyTimeStamp is null
                        lastPasswordChange = new Date();
                    }

                    LdapUser user = new LdapUser(uid, ctx.getNameInNamespace(),
                            ctx.getStringAttribute(MAIL_ATTRIBUTE),
                            ctx.getStringAttribute(COMMON_NAME_ATTRIBUTE), lastPasswordChange, getRealm());

                    Object[] tab = { x509Certificate.getSerialNumber(), user };

                    return tab;

                } catch (Exception e) {

                    logger.error(e);
                    return null;
                }
            }
        });

        if (serialNumbers != null) {
            for (Object o : serialNumbers) {

                Object[] tab = (Object[]) o;
                BigInteger serialNumber = (BigInteger) tab[0];
                LdapUser user = (LdapUser) tab[1];
                if (serialNumber.equals(x509Certificate.getSerialNumber()))
                    return user;
            }
        }
    }

    return null;

}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);/*  w  ww . j  av a  2 s.c o m*/
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private String buildKID(X509Certificate cert) {
    StringBuffer b = new StringBuffer();
    b.append(cert.getSubjectDN().getName()).append('-').append(cert.getIssuerDN().getName()).append('-')
            .append(cert.getSerialNumber().toString());
    return b.toString();
}

From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java

/**
 * @throws SSOAuthenticationException/*from   ww w . j av a  2  s. c  om*/
 */
public boolean authenticate() throws SSOAuthenticationException {

    setAuthenticated(false);

    //String username = getUsername(_inputCredentials);
    X509Certificate x509Certificate = getX509Certificate(_inputCredentials);

    // Check if all credentials are present.
    if (x509Certificate == null) {

        if (logger.isDebugEnabled())
            logger.debug("X.509 Certificate not provided");

        // We don't support empty values !
        return false;
    }

    // validate certificate
    if (_validators != null) {
        for (X509CertificateValidator validator : _validators) {
            try {
                validator.validate(x509Certificate);
            } catch (X509CertificateValidationException e) {
                logger.error("Certificate is not valid!", e);
                return false;
            }
        }
    }

    // TODO STRONG-AUTH: Local certificate storage should be optional
    List<X509Certificate> knownX509Certificates = getX509Certificates(getKnownCredentials());

    StringBuffer buf = new StringBuffer("\n\tSupplied Credential: ");
    buf.append(x509Certificate.getSerialNumber().toString(16));
    buf.append("\n\t\t");
    buf.append(x509Certificate.getSubjectX500Principal().getName());
    buf.append("\n\n\tExisting Credentials: ");
    for (int i = 0; i < knownX509Certificates.size(); i++) {
        X509Certificate knownX509Certificate = knownX509Certificates.get(i);
        buf.append(i + 1);
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSerialNumber().toString(16));
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSubjectX500Principal().getName());
        buf.append("\n");
    }

    logger.debug(buf.toString());

    // Validate user identity ...
    boolean valid = false;
    X509Certificate validCertificate = null;
    for (X509Certificate knownX509Certificate : knownX509Certificates) {
        if (validateX509Certificate(x509Certificate, knownX509Certificate)) {
            validCertificate = knownX509Certificate;
            break;
        }
    }

    if (validCertificate == null) {
        return false;
    }

    // TODO STRONG-AUTH resolve User ID, take it from the certificate ..

    // Find UID
    // (We could just use getUID() to authenticate user
    // without previous validation against known certificates?)
    _uid = resolveUID(validCertificate);
    if (_uid == null) {
        return false;
    }

    if (logger.isDebugEnabled())
        logger.debug(
                "[authenticate()], Principal authenticated : " + x509Certificate.getSubjectX500Principal());

    // We have successfully authenticated this user.
    setAuthenticated(true);
    return true;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private RevocationDetail getRevocationDetail(List<X509CRL> crls, X509Certificate targetCertificate,
        X509Certificate issuerCertificate, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException {
    RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

    boolean validCRLFound = false;

    int reasonMask = 0;

    for (X509CRL crl : crls) {
        BigInteger serialNumber = targetCertificate.getSerialNumber();

        X509CRLEntry crlEntry = crl.getRevokedCertificate(serialNumber);

        Date revocationDate = null;

        if (crlEntry != null) {
            revocationDate = crlEntry.getRevocationDate();

            if (revocationDate == null || !now.before(revocationDate)) {
                /*// ww  w  .ja v  a 2 s.c o m
                 * X.509 7.3 NOTE 4  When an implementation processing a certificate revocation list does not 
                 * recognize a critical extension in the crlEntryExtensions field, it shall assume that, 
                 * at a minimum, the identified certificate has been revoked and is no longer valid and 
                 * perform additional actions concerning that revoked certificate as dictated by local policy.
                 *
                 * We do not need to check for unsupported critical extension because if we do not support them
                 * we should assume that the certificate is revoked.
                 */

                // TODO: add support for onHold/removeFromCRL

                Integer reasonCode = null;
                try {
                    reasonCode = X509CRLEntryInspector.getReasonCode(crlEntry);
                } catch (IOException e) {
                    logger.error("Error retrieving reasonCode.", e);
                }

                detail = (reasonCode != null ? new RevocationDetailImpl(RevocationStatus.REVOKED, reasonCode)
                        : new RevocationDetailImpl(RevocationStatus.REVOKED));

                /* there is no need to continue because certificate is revoked */
                break;
            } else {
                if (now.before(revocationDate)) {
                    logger.info("Certificate is revoked in the future.");
                }
            }
        }

        if (hasUnsupportedCriticalExtensions(crl)) {
            logger.debug("The CRL has unsupported critical extensions.");

            detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

            continue;
        }

        /*
         * check that the start time the CRL is valid is before the time the certificate is 
         * no longer valid. In other words, that the expiration date of the certificate is 
         * later than the date the CRL was issued. It is possible that the certificate was
         * at some point revoked but the CA removed it because the certificate is no longer 
         * valid
         */
        if (crl.getThisUpdate() != null && targetCertificate.getNotAfter().before(crl.getThisUpdate())) {
            logger.info("Certificate has expired before the CRL was valid.");

            continue;
        }

        try {
            if (X509CRLInspector.isDeltaCRL(crl)) {
                DeltaCRLStatus deltaStatus = getDeltaCRLStatus(targetCertificate, crl, issuerPublicKey, now);

                if (deltaStatus == DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION) {
                    detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

                    continue;
                } else if (deltaStatus == DeltaCRLStatus.UNKNOWN) {
                    continue;
                }
            } else {
                if (!acceptCRL_6_3_3_b(targetCertificate, crl)) {
                    logger.debug("CRL not valid according to acceptCRL_6_3_3_b.");
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("Error inspecting CRL.", e);

            continue;
        }

        if (crl.getNextUpdate() != null && now.after(crl.getNextUpdate())) {
            /*
             * an CRL cannot really expire but, when we want at least to log that the 
             * nextUpdate is overdue
             */
            logger.debug("The CRL next update is overdue.");

            /* we need to set the nextUpdate if this is a newer CRL */

            if (detail.getStatus() != RevocationStatus.EXPIRED || detail.getNextUpdate() == null) {
                detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
            } else {
                if (crl.getNextUpdate().after(detail.getNextUpdate())) {
                    /* the nextUpdate of the current CRL is later so it's longer valid */
                    detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
                }
            }

            continue;
        }

        try {
            reasonMask = reasonMask | getInterimReasonsMask(targetCertificate, crl);

            /* a valid crl was found. Continue search. */
            validCRLFound = true;
        } catch (IOException e) {
            logger.error("Error getting interim mask.", e);
        }
    }

    /*
     * if one the CRLs was good and the certificate was not revoked we will set the 
     * status to NOT_REVOKED
     */
    if (validCRLFound && detail.getStatus() != RevocationStatus.REVOKED) {
        /* check if all reasons are covered */
        if (reasonMask == allReasons) {
            detail = new RevocationDetailImpl(RevocationStatus.NOT_REVOKED);
        } else {
            logger.debug("Not all reasons were covered.");

            detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);
        }
    }

    return detail;
}

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

/**
 * This method takes byte array and translates it onto a OCSPReq class.
 * /*from   w  ww . ja v  a2s.  co  m*/
 * @param authenticationToken An authentication token needed to perform validation.
 * @param request the byte array in question.
 * @param remoteAddress The remote address of the HttpRequest associated with this array.
 * @param transactionLogger A transaction logger.
 * @return
 * @throws InvalidKeyException
 * @throws SignRequestException thrown if an unsigned request was processed when system configuration requires that all requests be signed.
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws SignRequestSignatureException
 */
private OCSPReq translateRequestFromByteArray(byte[] request, String remoteAddress,
        TransactionLogger transactionLogger) throws MalformedRequestException, SignRequestException,
        SignRequestSignatureException, CertificateException, NoSuchAlgorithmException {

    OCSPReq result = null;
    try {
        result = new OCSPReq(request);
    } catch (IOException e) {
        throw new MalformedRequestException("Could not form OCSP request", e);
    }

    if (result.getRequestorName() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is null");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Requestor name is: " + result.getRequestorName().toString());
        }
        transactionLogger.paramPut(TransactionLogger.REQ_NAME, result.getRequestorName().toString());
    }

    /**
     * check the signature if contained in request. if the request does not contain a signature and the servlet is configured in the way the a
     * signature is required we send back 'sigRequired' response.
     */
    if (log.isDebugEnabled()) {
        log.debug("Incoming OCSP request is signed : " + result.isSigned());
    }
    if (result.isSigned()) {
        X509Certificate signercert = checkRequestSignature(remoteAddress, result);
        String signercertIssuerName = CertTools.getIssuerDN(signercert);
        BigInteger signercertSerNo = CertTools.getSerialNumber(signercert);
        String signercertSubjectName = CertTools.getSubjectDN(signercert);

        transactionLogger.paramPut(TransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName);
        transactionLogger.paramPut(TransactionLogger.SIGN_SERIAL_NO,
                signercert.getSerialNumber().toByteArray());
        transactionLogger.paramPut(TransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName);
        transactionLogger.paramPut(PatternLogger.REPLY_TIME, TransactionLogger.REPLY_TIME);

        if (OcspConfiguration.getEnforceRequestSigning()) {
            // If it verifies OK, check if it is revoked
            final CertificateStatus status = certificateStoreSession
                    .getStatus(CertTools.getIssuerDN(signercert), CertTools.getSerialNumber(signercert));
            /*
             * If rci == null it means the certificate does not exist in database, we then treat it as ok, because it may be so that only revoked
             * certificates is in the (external) OCSP database.
             */
            if (status.equals(CertificateStatus.REVOKED)) {
                String serno = signercertSerNo.toString(16);
                String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.revoked", signercertSubjectName,
                        signercertIssuerName, serno);
                log.info(infoMsg);
                throw new SignRequestSignatureException(infoMsg);
            }

            if (OcspConfiguration.getRestrictSignatures()) {
                DirectoryCache.INSTANCE.loadTrustDir();
                switch (OcspConfiguration.getRestrictSignaturesByMethod()) {
                case OcspConfiguration.RESTRICTONSIGNER:
                    if (!checkCertInList(signercert, DirectoryCache.INSTANCE.getTrustedReqSigSigners())) {
                        String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed",
                                signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16));
                        log.info(infoMsg);
                        throw new SignRequestSignatureException(infoMsg);
                    }
                    break;
                case OcspConfiguration.RESTRICTONISSUER:
                    X509Certificate signerca = certificateStoreSession
                            .findLatestX509CertificateBySubject(signercertIssuerName);
                    if ((signerca == null) || (!checkCertInList(signerca,
                            DirectoryCache.INSTANCE.getTrustedReqSigIssuers()))) {
                        String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed",
                                signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16));
                        log.info(infoMsg);
                        throw new SignRequestSignatureException(infoMsg);
                    }
                    break;
                default:
                    // There must be an internal error. We do not want to send a response, just to be safe.
                    throw new OcspFailureException(
                            "m_reqRestrictMethod=" + OcspConfiguration.getRestrictSignaturesByMethod());

                }
            }
        }
    } else {
        if (OcspConfiguration.getEnforceRequestSigning()) {
            // Signature required
            throw new SignRequestException("Signature required");
        }
    }

    return result;
}

From source file:org.apache.rampart.PolicyBasedResultsValidator.java

/**
 * Evaluate whether a given certificate should be trusted. Hook to allow subclasses to implement
 * custom validation methods however they see fit.
 * <p/>/*  w  w w .java  2  s .  co  m*/
 * Policy used in this implementation: 1. Search the keystore for the transmitted certificate 2.
 * Search the keystore for a connection to the transmitted certificate (that is, search for
 * certificate(s) of the issuer of the transmitted certificate 3. Verify the trust path for
 * those certificates found because the search for the issuer might be fooled by a phony DN
 * (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions
 *         during CertPathValidation)
 * @throws WSSecurityException
 */
protected boolean verifyTrust(X509Certificate cert, RampartMessageData rmd) throws RampartException {

    // If no certificate was transmitted, do not trust the signature
    if (cert == null) {
        return false;
    }

    String[] aliases = null;
    String alias = null;
    X509Certificate[] certs;

    String subjectString = cert.getSubjectDN().getName();
    String issuerString = cert.getIssuerDN().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    boolean doDebug = log.isDebugEnabled();

    if (doDebug) {
        log.debug("WSHandler: Transmitted certificate has subject " + subjectString);
        log.debug("WSHandler: Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial
                + ")");
    }

    // FIRST step
    // Search the keystore for the transmitted certificate

    // Search the keystore for the alias of the transmitted certificate
    try {
        alias = RampartUtil
                .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                .getAliasForX509Cert(issuerString, issuerSerial);
    } catch (WSSecurityException ex) {
        throw new RampartException("cannotFindAliasForCert", new String[] { subjectString }, ex);
    }

    if (alias != null) {
        // Retrieve the certificate for the alias from the keystore
        try {
            certs = RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new RampartException("noCertForAlias", new String[] { alias }, ex);
        }

        // If certificates have been found, the certificates must be compared
        // to ensure against phony DNs (compare encoded form including signature)
        if (certs != null && certs.length > 0 && cert.equals(certs[0])) {
            if (doDebug) {
                log.debug("Direct trust for certificate with " + subjectString);
            }
            // Set the alias of the cert used for the msg. sig. as a msg. cxt. property
            rmd.getMsgContext().setProperty(RampartMessageData.SIGNATURE_CERT_ALIAS, alias);
            return true;
        }
    } else {
        if (doDebug) {
            log.debug("No alias found for subject from issuer with " + issuerString + " (serial " + issuerSerial
                    + ")");
        }
    }

    // SECOND step
    // Search for the issuer of the transmitted certificate in the keystore

    // Search the keystore for the alias of the transmitted certificates issuer
    try {
        aliases = RampartUtil
                .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                .getAliasesForDN(issuerString);
    } catch (WSSecurityException ex) {
        throw new RampartException("cannotFindAliasForCert", new String[] { issuerString }, ex);
    }

    // If the alias has not been found, the issuer is not in the keystore
    // As a direct result, do not trust the transmitted certificate
    if (aliases == null || aliases.length < 1) {
        if (doDebug) {
            log.debug("No aliases found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    // THIRD step
    // Check the certificate trust path for every alias of the issuer found in the keystore
    for (int i = 0; i < aliases.length; i++) {
        alias = aliases[i];

        if (doDebug) {
            log.debug("Preparing to validate certificate path with alias " + alias + " for issuer "
                    + issuerString);
        }

        // Retrieve the certificate(s) for the alias from the keystore
        try {
            certs = RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .getCertificates(alias);
        } catch (WSSecurityException ex) {
            throw new RampartException("noCertForAlias", new String[] { alias }, ex);
        }

        // If no certificates have been found, there has to be an error:
        // The keystore can find an alias but no certificate(s)
        if (certs == null || certs.length < 1) {
            throw new RampartException("noCertForAlias", new String[] { alias });
        }

        // Form a certificate chain from the transmitted certificate
        // and the certificate(s) of the issuer from the keystore
        // First, create new array
        X509Certificate[] x509certs = new X509Certificate[certs.length + 1];
        // Then add the first certificate ...
        x509certs[0] = cert;
        // ... and the other certificates
        for (int j = 0; j < certs.length; j++) {
            cert = certs[j];
            x509certs[j + 1] = cert;
        }
        certs = x509certs;

        // Use the validation method from the crypto to check whether the subjects certificate
        // was really signed by the issuer stated in the certificate
        try {
            if (RampartUtil
                    .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader())
                    .validateCertPath(certs)) {
                if (doDebug) {
                    log.debug("WSHandler: Certificate path has been verified for certificate with subject "
                            + subjectString);
                }
                return true;
            }
        } catch (WSSecurityException ex) {
            throw new RampartException("certPathVerificationFailed", new String[] { subjectString }, ex);
        }
    }

    if (doDebug) {
        log.debug("WSHandler: Certificate path could not be verified for certificate with subject "
                + subjectString);
    }
    return false;
}

From source file:org.ejbca.ui.web.admin.keybind.InternalKeyBindingMBean.java

/** @return list of gui representations for all the InternalKeyBindings of the current type*/
public ListDataModel getInternalKeyBindingGuiList() {
    if (internalKeyBindingGuiList == null) {
        // Get the current type of tokens we operate on
        final String internalKeyBindingType = getSelectedInternalKeyBindingType();
        List<GuiInfo> internalKeyBindingList = new LinkedList<GuiInfo>();
        for (InternalKeyBindingInfo current : internalKeyBindingSession
                .getInternalKeyBindingInfos(authenticationToken, internalKeyBindingType)) {
            final int cryptoTokenId = current.getCryptoTokenId();
            final CryptoTokenInfo cryptoTokenInfo = cryptoTokenManagementSession
                    .getCryptoTokenInfo(cryptoTokenId);
            final String cryptoTokenName;
            boolean cryptoTokenAvailable = false;
            boolean cryptoTokenActive = false;
            if (cryptoTokenInfo == null) {
                cryptoTokenName = "unknown";
            } else {
                cryptoTokenAvailable = accessControlSession.isAuthorizedNoLogging(authenticationToken,
                        CryptoTokenRules.GENERATE_KEYS.resource() + "/" + cryptoTokenId);
                cryptoTokenActive = cryptoTokenInfo.isActive();
                cryptoTokenName = cryptoTokenInfo.getName();
            }//from w  ww .j a va  2s  .c  o m
            final String certificateId = current.getCertificateId();
            final Certificate certificate = certificateId == null ? null
                    : certificateStoreSession.findCertificateByFingerprint(certificateId);
            String certificateIssuerDn = "";
            String certificateSubjectDn = "";
            String certificateSerialNumber = "";
            String caCertificateIssuerDn = "";
            String caCertificateSerialNumber = "";
            String certificateInternalCaName = null;
            int certificateInternalCaId = 0;
            String status = current.getStatus().name();
            if (certificate != null) {
                certificateSubjectDn = CertTools.getSubjectDN(certificate);
                certificateIssuerDn = CertTools.getIssuerDN(certificate);
                certificateSerialNumber = CertTools.getSerialNumberAsString(certificate);
                try {
                    // Note that we can do lookups using the .hashCode, but we will use the objects id
                    final CA ca = caSession.getCANoLog(authenticationToken, certificateIssuerDn.hashCode());
                    certificateInternalCaName = ca.getName();
                    certificateInternalCaId = ca.getCAId();
                    caCertificateIssuerDn = CertTools.getIssuerDN(ca.getCACertificate());
                    caCertificateSerialNumber = CertTools.getSerialNumberAsString(ca.getCACertificate());
                } catch (Exception e) {
                    // CADoesntExistsException or AuthorizationDeniedException
                    // The CA is for the purpose of "internal" renewal not available to this administrator.
                    // Try to find the issuer (CA) certificate by other means, trying to get it through CA certificate link from the bound certificate 
                    CertificateInfo info = certificateStoreSession.getCertificateInfo(certificateId);
                    final Certificate cacertificate = info.getCAFingerprint() == null ? null
                            : certificateStoreSession.findCertificateByFingerprint(info.getCAFingerprint());
                    if (cacertificate != null) {
                        caCertificateIssuerDn = CertTools.getIssuerDN(cacertificate);
                        caCertificateSerialNumber = CertTools.getSerialNumberAsString(cacertificate);
                    }
                }
                // Check for additional informative UI states
                if (InternalKeyBindingStatus.ACTIVE.equals(current.getStatus())) {
                    // Check if certificate is expired
                    if (certificate instanceof X509Certificate) {
                        final X509Certificate x509Certificate = (X509Certificate) certificate;
                        try {
                            x509Certificate.checkValidity();
                            // Check if certificate is revoked
                            if (certificateStoreSession.isRevoked(certificateIssuerDn,
                                    x509Certificate.getSerialNumber())) {
                                status = "REVOKED";
                            }
                        } catch (CertificateExpiredException e) {
                            status = "EXPIRED";
                        } catch (CertificateNotYetValidException e) {
                            status = "NOTYETVALID";
                        }
                    }
                }
            }
            internalKeyBindingList.add(new GuiInfo(current.getId(), current.getName(), cryptoTokenId,
                    cryptoTokenName, cryptoTokenAvailable, cryptoTokenActive, current.getKeyPairAlias(),
                    current.getNextKeyPairAlias(), status, current.getCertificateId(), certificateIssuerDn,
                    certificateSubjectDn, certificateInternalCaName, certificateInternalCaId,
                    certificateSerialNumber, caCertificateIssuerDn, caCertificateSerialNumber));
            Collections.sort(internalKeyBindingList, new Comparator<GuiInfo>() {
                @Override
                public int compare(final GuiInfo guiInfo1, final GuiInfo guiInfo2) {
                    return guiInfo1.getName().compareToIgnoreCase(guiInfo2.getName());
                }
            });
        }
        internalKeyBindingGuiList = new ListDataModel(internalKeyBindingList);
    }
    // View the list will purge the view cache
    flushSingleViewCache();
    return internalKeyBindingGuiList;
}

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

public void test01CrmfHttpOkUser() throws Exception {

    log.debug(">test01CrmfHttpOkUser()");

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notAfter = cal.getTime();

    // In this we also test validity override using notBefore and notAfter
    // from above
    // In this test userDN contains special, escaped characters to verify
    // that that works with CMP RA as well
    PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, notBefore, notAfter,
            null);/*from  w w w. ja v  a 2  s  .  com*/
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);
    assertNotNull(req);

    int reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD);
    X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId);
    // Check that validity override works
    assertTrue(cert.getNotBefore().equals(notBefore));
    assertTrue(cert.getNotAfter().equals(notAfter));
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, cacert, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD);
    checkCmpPKIConfirmMessage(userDN, cacert, resp);

    // Now revoke the bastard using the CMPv1 reason code!
    PKIMessage rev = genRevReq(issuerDN, userDN, cert.getSerialNumber(), cacert, nonce, transid, false);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD);
    checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), cacert, resp, true);
    int reason = checkRevokeStatus(issuerDN, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);

    // Create a revocation request for a non existing cert, should fail!
    rev = genRevReq(issuerDN, userDN, new BigInteger("1"), cacert, nonce, transid, true);
    revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200);
    checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD);
    checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), cacert, resp, false);

    log.debug("<test01CrmfHttpOkUser()");
}