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:ru.codeinside.gws.crypto.cryptopro.SunPkcs7.java

public static byte[] toPkcs7(final Signature signature) {
    final X509Certificate certificate = signature.certificate;
    final byte[] sign = signature.sign;
    X500Name issuer = X500Name.asX500Name(certificate.getIssuerX500Principal());
    final AlgorithmId digestAlgorithmId = new AlgorithmId(GOST3411);
    final AlgorithmId signAlgorithmId = new AlgorithmId(GOST3410);
    SignerInfo sInfo = new SignerInfo(issuer, certificate.getSerialNumber(), digestAlgorithmId, signAlgorithmId,
            sign);/* w  ww  .j ava2 s  .c o  m*/
    ContentInfo cInfo = new ContentInfo(ContentInfo.DATA_OID, null);
    PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { digestAlgorithmId }, cInfo,
            new X509Certificate[] { certificate }, new SignerInfo[] { sInfo });
    final ByteArrayOutputStream bOut = new DerOutputStream();
    try {
        pkcs7.encodeSignedData(bOut);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return bOut.toByteArray();
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

private static void addUserCertificate(String userName, X509Certificate x509Certificate)
        throws AuthenticationFailedException {

    if (log.isDebugEnabled()) {
        log.debug("X509 Certificate with serial num: " + x509Certificate.getSerialNumber()
                + " does not exit for user: " + userName);
    }//from   w  w w  . ja  v a  2  s. co m
    X509CertificateUtil.addCertificate(userName, x509Certificate);
    if (log.isDebugEnabled()) {
        log.debug("Adding the X509 certificate with serial num: " + x509Certificate.getSerialNumber()
                + " as a user claim.");
    }
}

From source file:be.fedict.eid.applet.service.JSONServlet.java

private static JSONObject createCertJSONObject(X509Certificate certificate, SimpleDateFormat simpleDateFormat)
        throws CertificateEncodingException, IOException {
    JSONObject certJSONObject = new JSONObject();
    certJSONObject.put("subject", certificate.getSubjectX500Principal().toString());
    certJSONObject.put("issuer", certificate.getIssuerX500Principal().toString());
    certJSONObject.put("serialNumber", certificate.getSerialNumber().toString());
    certJSONObject.put("notBefore", certificate.getNotBefore().toString());
    certJSONObject.put("notAfter", certificate.getNotAfter().toString());
    certJSONObject.put("signatureAlgo", certificate.getSigAlgName());
    certJSONObject.put("thumbprint", DigestUtils.shaHex(certificate.getEncoded()));
    certJSONObject.put("details", certificate.toString());
    certJSONObject.put("pem", toPem(certificate));

    return certJSONObject;
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Returns the serial number as a String (to get the BigInteger serial number use 
 * X509Certificate directly)/*from   w  ww.j  a v a  2  s  .com*/
 * @param certificate
 * @return
 */
public static String getSerialNumberHex(X509Certificate certificate) {
    return BigIntegerUtils.hexEncode(certificate.getSerialNumber());
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static SocketFactory createSocketFactory(InputStream keyStore, String password,
        String keystoreType, String algorithm, String protocol)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException, CertificateExpiredException {

    char[] pwdChars = password.toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(keyStore, pwdChars);/* w ww.j  ava 2s .c  o m*/

    // ??
    Enumeration<String> enums = ks.aliases();
    String alias = "";
    if (enums.hasMoreElements()) {
        alias = enums.nextElement();
    }
    if (StringUtils.isNotEmpty(alias)) {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        if (null != certificate) {
            String type = certificate.getType();
            int ver = certificate.getVersion();
            String name = certificate.getSubjectDN().getName();
            String serialNumber = certificate.getSerialNumber().toString(16);
            String issuerDN = certificate.getIssuerDN().getName();
            String sigAlgName = certificate.getSigAlgName();
            String publicAlgorithm = certificate.getPublicKey().getAlgorithm();
            Date before = certificate.getNotBefore();
            Date after = certificate.getNotAfter();

            String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss");
            String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss");

            // ??
            long expire = DateUtil.getNumberOfDaysBetween(new Date(), after);
            if (expire <= 0) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(
                            "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]",
                            name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                            afterStr, Math.abs(expire));
                }

                throw new CertificateExpiredException("??[" + Math.abs(expire) + "]");
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(
                        "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?",
                        name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                        afterStr, expire);
            }
        }
    }

    KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm);
    kf.init(ks, pwdChars);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init((KeyStore) null);
    SSLContext context = SSLContext.getInstance(protocol);
    context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

private static boolean isUserCertificateValid(String userName, X509Certificate x509Certificate)
        throws AuthenticationFailedException {

    X509Certificate certInUserClaim = getCertificate(userName);
    if (log.isDebugEnabled()) {
        log.debug("X509 certificate with serial num: " + x509Certificate.getSerialNumber()
                + " is getting matched with the user certificate with serial num : "
                + certInUserClaim.getSerialNumber() + " in the user claim of user: " + userName);
    }// w  ww  .  j a va2 s .c  o m
    return x509Certificate.equals(certInUserClaim);
}

From source file:fi.laverca.Pkcs7.java

/**
 * Read the certificates used to sign a PKCS7 SignedData.
 * //w  ww.j a  va 2s .  co m
 * @param sd PKCS7 SignedData
 * @return List of X509 certificates
 * @throws FiComException if no certificate or signer info is found from the data
 */
public static List<X509Certificate> getSignerCerts(final SignedData sd) throws FiComException {

    // 0. Setup. 
    // 1. Read PKCS7.Certificates to get all possible certs.
    // 2. Read PKCS7.SignerInfo to get all signers.
    // 3. Look up matching certificates.
    // 4. Return the list.

    // 0. Setup. 
    if (sd == null) {
        throw new IllegalArgumentException("null input");
    }
    List<X509Certificate> signerCerts = new ArrayList<X509Certificate>();

    // 1. Read PKCS7.Certificates to get all possible certs.
    log.debug("Read all certs");
    List<X509Certificate> certs = readCerts(sd);

    if (certs.isEmpty()) {
        throw new FiComException("PKCS7 SignedData certificates not found");
    }

    // 2. Read PKCS7.SignerInfo to get all signers.
    log.debug("Read SignerInfo");
    List<SignerInfo> signerInfos = readSignerInfos(sd);

    if (signerInfos.isEmpty()) {
        throw new FiComException("PKCS7 SignedData signerInfo not found");
    }

    // 3. Verify that signerInfo cert details match the cert on hand
    log.debug("Matching cert and SignerInfo details");
    for (SignerInfo si : signerInfos) {
        for (X509Certificate c : certs) {
            String siIssuer = readIssuer(si);
            String siSerial = readSerial(si);

            String cIssuer = c.getIssuerDN().toString();
            String cSerial = c.getSerialNumber().toString();

            if (dnsEqual(siIssuer, cIssuer) && siSerial.equals(cSerial)) {
                signerCerts.add(c);
                log.debug("Cert does match signerInfo");
                log.debug("SignerInfo   issuer:serial = " + siIssuer + ":" + siSerial);
                log.debug("Certificates issuer:serial = " + cIssuer + ":" + cSerial);
            } else {
                log.debug("Cert does not match signerInfo");
                log.debug("SignerInfo   issuer:serial = " + siIssuer + ":" + siSerial);
                log.debug("Certificates issuer:serial = " + cIssuer + ":" + cSerial);
            }
        }
    }

    // 4. Return the list.
    log.debug("Returning " + signerCerts.size() + " certs");
    return signerCerts;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

public static Hashtable getCertificatesFromDirectory(String certificateDir) throws IOException {
    // read all files from trustDir, expect that they are PEM formatted certificates
    CertTools.installBCProvider();//from w w  w . ja v a2  s  .  c  o m
    File dir = new File(certificateDir);
    Hashtable trustedCerts = new Hashtable();
    if (dir == null || dir.isDirectory() == false) {
        m_log.error(dir.getCanonicalPath() + " is not a directory.");
        throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory.");
    }
    File files[] = dir.listFiles();
    if (files == null || files.length == 0) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath());
        m_log.error(errMsg);
    }
    for (int i = 0; i < files.length; i++) {
        final String fileName = files[i].getCanonicalPath();
        // Read the file, don't stop completely if one file has errors in it
        try {
            byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(fileName),
                    CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE);
            X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes);
            String key = cert.getIssuerDN() + ";" + cert.getSerialNumber().toString(16);
            trustedCerts.put(key, cert);
        } catch (CertificateException e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                    e.getMessage());
            m_log.error(errMsg, e);
        } catch (IOException e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                    e.getMessage());
            m_log.error(errMsg, e);
        }
    }
    return trustedCerts;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

/**
 * Checks to see if a certificate is in a list of certificate.
 * Comparison is made on SerialNumber/*from w  w  w .j a  v  a  2 s. c o m*/
 * @param cert the certificate to look for
 * @param trustedCerts the list (Hashtable) to look in
 * @return true if cert is in trustedCerts, false otherwise
 */
public static boolean checkCertInList(X509Certificate cert, Hashtable trustedCerts) {
    //String key = CertTools.getIssuerDN(cert)+";"+cert.getSerialNumber().toString(16);
    String key = cert.getIssuerDN() + ";" + cert.getSerialNumber().toString(16);
    Object found = trustedCerts.get(key);
    if (found != null) {
        return true;
    }
    return false;
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

private static void deleteUserCertificate(String userName, X509Certificate x509Certificate)
        throws AuthenticationFailedException {

    if (isCertificateExist(userName) && isUserCertificateValid(userName, x509Certificate)) {
        if (log.isDebugEnabled()) {
            log.debug("Provided X509 client certificate with serial num: " + x509Certificate.getSerialNumber()
                    + " has been revoked. Removing the x509Certificate claim of the user: " + userName);
        }/*from ww  w .j a v a2 s. c  om*/
        deleteCertificate(userName);
    }
}