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:be.fedict.trust.ocsp.OnlineOcspRepository.java

private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate)
        throws OCSPException, IOException {
    LOG.debug("OCSP URI: " + ocspUri);
    OCSPReqGenerator ocspReqGenerator = new OCSPReqGenerator();
    CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate,
            certificate.getSerialNumber());
    ocspReqGenerator.addRequest(certId);
    OCSPReq ocspReq = ocspReqGenerator.generate();
    byte[] ocspReqData = ocspReq.getEncoded();

    PostMethod postMethod = new PostMethod(ocspUri.toString());
    RequestEntity requestEntity = new ByteArrayRequestEntity(ocspReqData, "application/ocsp-request");
    postMethod.addRequestHeader("User-Agent", "jTrust OCSP Client");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }//w  ww  .j av  a  2s. co  m
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }

    int responseCode;
    try {
        httpClient.executeMethod(postMethod);
        responseCode = postMethod.getStatusCode();
    } catch (ConnectException e) {
        LOG.debug("OCSP responder is down");
        return null;
    }

    if (HttpURLConnection.HTTP_OK != responseCode) {
        LOG.error("HTTP response code: " + responseCode);
        return null;
    }

    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        LOG.debug("no Content-Type response header");
        return null;
    }
    String resultContentType = responseContentTypeHeader.getValue();
    if (!"application/ocsp-response".equals(resultContentType)) {
        LOG.debug("result content type not application/ocsp-response");
        return null;
    }

    Header responseContentLengthHeader = postMethod.getResponseHeader("Content-Length");
    if (null != responseContentLengthHeader) {
        String resultContentLength = responseContentLengthHeader.getValue();
        if ("0".equals(resultContentLength)) {
            LOG.debug("no content returned");
            return null;
        }
    }

    OCSPResp ocspResp = new OCSPResp(postMethod.getResponseBodyAsStream());
    LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes");
    return ocspResp;
}

From source file:org.globus.gsi.stores.ResourceSigningPolicyStoreTest.java

private X509Certificate readCertificate(String certPath) {
    try {/*  w  ww . j  a  v a2s  .  c om*/
        FileInputStream fr = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate crt = (X509Certificate) cf.generateCertificate(fr);
        logger.info("Read certificate:");
        logger.info("\tCertificate for: " + crt.getSubjectDN());
        logger.info("\tCertificate issued by: " + crt.getIssuerDN());
        logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter());
        logger.info("\tCertificate SN# " + crt.getSerialNumber());
        logger.info("\tGenerated with " + crt.getSigAlgName());

        return crt;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * Generate standard key.//from   w w  w  . jav a 2  s.c  o  m
 * 
 * @param cert
 * @return
 */
public Key generateKey(X509Certificate cert) {
    return KeyFactory.createKey(KIND, cert.getIssuerDN() + ":" + cert.getSerialNumber().toString(16));
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * Verify that cached results are consistent. It's a strong indication that
 * someone has been screwing with the database if the values are
 * inconsistent. This is computationally expensive but the cost of a
 * corrupted database is far worse./*from   ww  w.j  ava  2s  .  co m*/
 * 
 * @param entity
 * @param cert
 */
public void validate(Entity entity, X509Certificate cert) throws CertificateException {
    if (!cert.getSerialNumber().equals(entity.getProperty(SERIAL_NUMBER))) {
        throw new CertificateException("serial number did not match");
    }
    if (!cert.getIssuerDN().equals(entity.getProperty(ISSUER_DN))) {
        throw new CertificateException("issuer dn did not match");
    }
    if (!cert.getSubjectDN().equals(entity.getProperty(SUBJECT_DN))) {
        throw new CertificateException("subject dn did not match");
    }
    if (!cert.getNotBefore().equals(entity.getProperty(NOT_BEFORE))) {
        throw new CertificateException("notBefore did not match");
    }
    if (!cert.getNotAfter().equals(entity.getProperty(NOT_AFTER))) {
        throw new CertificateException("notAfter did not match");
    }
    if (!x509CertUtil.getName(cert).equals(entity.getProperty(COMMON_NAME))) {
        throw new CertificateException("common name did not match");
    }
    if (!x509CertUtil.getFingerprint(cert).equals(entity.getProperty(FINGERPRINT))) {
        throw new CertificateException("cached fingerprints did not match");
    }
    if (!x509CertUtil.getCertificateHash(cert).equals(entity.getProperty(CERT_HASH))) {
        throw new CertificateException("cached certificate hash did not match");
    }
    if (!x509CertUtil.getIHash(cert).equals(entity.getProperty(ISSUER_HASH))) {
        throw new CertificateException("cached issuer hash did not match");
    }
    if (!x509CertUtil.getSHash(cert).equals(entity.getProperty(SUBJECT_HASH))) {
        throw new CertificateException("cached subject hash did not match");
    }
    if (!x509CertUtil.getAkidHash(cert).equals(entity.getProperty(AKID_HASH))) {
        throw new CertificateException("cached AKID hash did not match");
    }
    if (!x509CertUtil.getSkidHash(cert).equals(entity.getProperty(SKID_HASH))) {
        throw new CertificateException("cached SKID hash did not match");
    }
}

From source file:net.sf.dsig.verify.OCSPHelper.java

/**
 * Check with OCSP protocol whether a certificate is valid
 * /*from   w  w  w  . j ava  2  s  .c  om*/
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

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

@Test
public void testGenerateCACRLNoNextUpdate() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);//  ww w .j a va 2  s .co  m

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), thisDate, CRLReason.privilegeWithdrawn);

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(caPrivateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(null, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/test-generate-ca-no-next-update.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

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

@Test
public void testGenerateCACRL() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);/*from  w  ww .  j  a va2  s  .  c o  m*/

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), thisDate, CRLReason.privilegeWithdrawn);

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(caPrivateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/test-generate-ca.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

From source file:io.cloudslang.content.mail.sslconfig.AuthSSLX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], String authType)
 *///from   w  ww  . j  a v  a 2s  . co m
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (LOG.isInfoEnabled() && certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            LOG.info(" Server certificate " + (c + 1) + ":");
            LOG.info("  Subject DN: " + cert.getSubjectDN());
            LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.info("  Valid from: " + cert.getNotBefore());
            LOG.info("  Valid until: " + cert.getNotAfter());
            LOG.info("  Issuer: " + cert.getIssuerDN());
            LOG.info("  SN: " + cert.getSerialNumber().toString(16));
        }
    }
    defaultTrustManager.checkServerTrusted(certificates, authType);
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** check that client's cert is listed in the user certs file */
private boolean checkUser(String userID, X509Certificate cert) {
    Set<BigInteger> numSet = certsMap.get(userID);
    if (numSet == null) {
        LOG.info("User " + userID + " is not configured in the user certs file");
        return false;
    }/*from  www .  java2 s  . c o m*/
    if (!numSet.contains(cert.getSerialNumber())) {
        LOG.info("Cert with serial number " + cert.getSerialNumber() + " is not listed for user " + userID);
        return false;
    }
    return true;
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

/**
 * Prints Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
 * /*www .j  a v a2s . c  o m*/
 * @throws CertificateException
 */
private void printAllX509Certificates() throws CertificateException {

    // Find all available certificates with getMatches(null)
    Iterator<?> certIt = cmsSignedData.getCertificates().getMatches(null).iterator();
    int i = 0;

    while (certIt.hasNext()) {
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        System.out.println("X509 Certificate #" + ++i);
        System.out.println("X509 Issuer: " + cert.getIssuerDN());
        System.out.println("X509 Subject DN: " + cert.getSubjectDN());
        System.out.println("X509 SerialNumber: " + cert.getSerialNumber());
        System.out.println("SignerCert: " + (cert.getBasicConstraints() == -1 ? "Yes" : "No"));
        System.out.println();
    }
}