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:org.apache.nifi.processors.email.smtp.SmtpConsumer.java

private Map<String, String> extractMessageAttributes() {
    final Map<String, String> attributes = new HashMap<>();
    final Certificate[] tlsPeerCertificates = context.getTlsPeerCertificates();
    if (tlsPeerCertificates != null) {
        for (int i = 0; i < tlsPeerCertificates.length; i++) {
            if (tlsPeerCertificates[i] instanceof X509Certificate) {
                X509Certificate x509Cert = (X509Certificate) tlsPeerCertificates[i];
                attributes.put("smtp.certificate." + i + ".serial", x509Cert.getSerialNumber().toString());
                attributes.put("smtp.certificate." + i + ".subjectName", x509Cert.getSubjectDN().getName());
            }//  w  w w. j a v  a  2  s  . c o m
        }
    }

    SocketAddress address = context.getRemoteAddress();
    if (address != null) {
        // will extract and format source address if available
        String strAddress = address instanceof InetSocketAddress
                ? ((InetSocketAddress) address).getHostString() + ":" + ((InetSocketAddress) address).getPort()
                : context.getRemoteAddress().toString();
        attributes.put("smtp.src", strAddress);
    }

    attributes.put("smtp.helo", context.getHelo());
    attributes.put("smtp.from", from);
    for (int i = 0; i < recipientList.size(); i++) {
        attributes.put("smtp.recipient." + i, recipientList.get(i));
    }
    attributes.put(CoreAttributes.MIME_TYPE.key(), "message/rfc822");
    return attributes;
}

From source file:com.github.technosf.posterer.models.impl.KeyStoreBeanTest.java

private void test509Cert(String alias, int serial) {
    Certificate cert = classUnderTest.getCertificate(alias);
    assertNotNull(cert);//from  ww  w.  ja  v  a 2  s. c  o  m
    assertEquals(cert.getType(), "X.509");
    X509Certificate x509 = (X509Certificate) cert;
    assertEquals(x509.getSerialNumber().intValue(), serial);

}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*  w w  w  .  j  a v  a  2  s.  c om*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:org.openhealthtools.openatna.net.MailConnection.java

public MimeBodyPart decryptMessage(Message message) throws MessagingException {

    try {/* ww  w.j ava 2 s. com*/
        /* Add BC */
        Security.addProvider(new BouncyCastleProvider());
        // Open the key store
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray());

        // find the certificate for the private key and generate a
        // suitable recipient identifier.
        X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias());
        RecipientId recId = new RecipientId();

        recId.setSerialNumber(cert.getSerialNumber());
        recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

        SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);
        RecipientInformationStore recipients = m.getRecipientInfos();
        // TODO figure out why this doesn't work...
        //RecipientInformation        recipient = recipients.get(recId);
        RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();

        Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray());
        byte[] byteContent = recipient.getContent(key, "BC");
        MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent);
        return res;

    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 *
 * @param cert//from   w w w  . ja  v a 2  s  .  c  om
 * @return
 */
public String getSerialNumber(X509Certificate cert) {
    String toReturn = "0" + cert.getSerialNumber().toString(16);
    return fixFingerprintHex(toReturn);
}

From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

public BigInteger getSerialNumber() {
    X509Certificate cert = getCertificateList().get(0);
    return cert.getSerialNumber();
}

From source file:org.signserver.admin.cli.defaultimpl.AbstractWSClientsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {/*ww w . ja v a2s. c  o  m*/
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    } catch (IllegalCommandArgumentsException e) {
        throw e;
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, getClientsProperty());
        final Set<ClientEntry> entries;

        if (admins != null) {
            entries = ClientEntry.clientEntriesFromProperty(admins);
        } else {
            entries = new HashSet<ClientEntry>();
        }

        if (LIST.equals(operation)) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized auditors:");
            buff.append("\n");
            for (ClientEntry entry : entries) {
                buff.append(
                        String.format("%-20s %s", entry.getSerialNumber().toString(16), entry.getIssuerDN()));
                buff.append("\n");
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            final boolean added;

            if (cert == null) {
                // serial number and issuer DN was entered manually
                added = entries.add(new ClientEntry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);

                added = entries.add(new ClientEntry(certificate.getSerialNumber(),
                        SignServerUtil.getTokenizedIssuerDNFromCert(certificate)));
            }

            if (added) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        getClientsProperty(), ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Auditor added");
            } else {
                getOutputStream().println("Auditor already exists");
            }
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new ClientEntry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        getClientsProperty(), ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Auditor removed");
            } else {
                getErrorStream().println("No such auditor");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil.java

/**
 * @param cert//from   www. j  a  v  a2 s .  c  o  m
 * @param formatter
 * @return
 * @throws CertificateEncodingException
 */
private static CertData fillCertData(X509Certificate cert, Format formatter)
        throws CertificateEncodingException {

    CertData certData = new CertData();
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));
    return certData;
}

From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

public String getSerialNumberString() {
    X509Certificate cert = getCertificateList().get(0);
    BigInteger sn = cert.getSerialNumber();
    return byteArrayToColonSeparatedHexString(sn.toByteArray(), ":");
}

From source file:be.fedict.trust.ocsp.OfflineOcspRepository.java

/**
 * {@inheritDoc}/*from ww w.ja  va  2 s  . co  m*/
 */
public OCSPResp findOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate) {

    LOG.debug("find OCSP response");

    try {
        for (OCSPResp ocspResp : this.ocspResponses) {

            CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate,
                    certificate.getSerialNumber());
            BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
            for (SingleResp singleResp : basicOCSPResp.getResponses()) {
                if (singleResp.getCertID().equals(certId)) {
                    LOG.debug("OCSP response found");
                    return ocspResp;
                }
            }
        }
    } catch (OCSPException e) {
        LOG.error("OCSPException: " + e.getMessage(), e);
        return null;
    }

    LOG.debug("OCSP response not found");
    return null;
}