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.eid.dss.spi.utils.XAdESUtils.java

public static void checkSigningCertificate(X509Certificate signingCertificate,
        SignedSignaturePropertiesType signedSignatureProperties)
        throws XAdESValidationException, CertificateEncodingException {
    CertIDListType signingCertificateCertIDList = signedSignatureProperties.getSigningCertificate();
    List<CertIDType> signingCertificateCertIDs = signingCertificateCertIDList.getCert();
    CertIDType signingCertificateCertID = signingCertificateCertIDs.get(0);
    DigestAlgAndValueType signingCertificateDigestAlgAndValue = signingCertificateCertID.getCertDigest();
    String certXmlDigestAlgo = signingCertificateDigestAlgAndValue.getDigestMethod().getAlgorithm();
    String certDigestAlgo = XAdESUtils.getDigestAlgo(certXmlDigestAlgo);
    byte[] certDigestValue = signingCertificateDigestAlgAndValue.getDigestValue();
    MessageDigest messageDigest;/*ww w. ja v a  2 s .c  o m*/
    try {
        messageDigest = MessageDigest.getInstance(certDigestAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e);
    }
    byte[] actualCertDigestValue = messageDigest.digest(signingCertificate.getEncoded());
    if (!Arrays.equals(actualCertDigestValue, certDigestValue)) {
        throw new XAdESValidationException(
                "XAdES signing certificate not corresponding with actual signing certificate");
    }

    X509IssuerSerialType issuerSerial = signingCertificateCertID.getIssuerSerial();
    BigInteger serialNumber = issuerSerial.getX509SerialNumber();
    if (false == signingCertificate.getSerialNumber().equals(serialNumber)) {
        throw new XAdESValidationException("xades:SigningCertificate serial number mismatch");
    }
    X509Name issuerName;
    try {
        /*issuerName = new X509Name(
              (ASN1Sequence) new ASN1InputStream(signingCertificate
             .getIssuerX500Principal().getEncoded())
             .readObject());*/
        X509Principal sprin = new X509Principal(signingCertificate.getIssuerX500Principal().getEncoded());

        //issuerName = new X509Name( signingCertificate.getIssuerX500Principal().getName(X500Principal.RFC1779) );
        issuerName = new X509Name(sprin.getName());

    } catch (IOException e) {
        throw new XAdESValidationException("error parsing xades:SigningCertificate ds:X509IssuerName: " + e);
    }
    X509Name xadesIssuerName = new X509Name(issuerSerial.getX509IssuerName());
    if (false == issuerName.equals(xadesIssuerName)) {
        throw new XAdESValidationException("xades:SigningCertificate issuer name mismatch");
    }
    LOG.debug("XAdES SigningCertificate OK");
}

From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

private void populateCertificateTree() {
    certificateTree.removeAll();//from w  w  w .ja v  a 2 s  .  c o m
    valueText.setText(StringUtils.EMPTY);

    IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection();

    if (selection.size() != 1) {
        return;
    }

    CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement();
    X509Certificate certificate = certificateItem.certificate;

    TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE);
    Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal());
    rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$

    TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$
            String.valueOf(certificate.getVersion()));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$
            certificate.getSerialNumber().toString(16));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$
            certificate.getIssuerX500Principal().getName());

    TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$
            certificate.getNotBefore().toString());
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$
            certificate.getNotAfter().toString());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$
            certificate.getSubjectX500Principal().getName());

    TreeItem pkiItem = createTreeItem(certItem,
            Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$
    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$
            certificate.getPublicKey().getAlgorithm());

    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getPublicKey().getEncoded())));

    TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$
            StringUtils.EMPTY);
    populateExtensions(extItem, certificate, true);
    populateExtensions(extItem, certificate, false);

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getSignature())));

    rootItem.setExpanded(true);
    certItem.setExpanded(true);
    validityItem.setExpanded(true);
    pkiItem.setExpanded(true);
    extItem.setExpanded(true);
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

/**
 * Gives back the JAXB CertID data structure.
 * //from w  w  w.  j a  v a  2s .  c o  m
 * @param certificate
 * @param xadesObjectFactory
 * @param xmldsigObjectFactory
 * @param digestAlgorithm
 * @return
 */
private CertIDType getCertID(X509Certificate certificate) {

    CertIDType certId = xades13ObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = getDsObjectFactory().createX509IssuerSerialType();
    certId.setIssuerSerial(issuerSerial);
    String issuerName = certificate.getIssuerX500Principal().toString();
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());

    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, DigestAlgorithm.SHA1);
    certId.setCertDigest(certDigest);

    return certId;
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore/*from   w ww .j  a v a2  s  .  co  m*/
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(Object issuerRDN, BigInteger serialNumber, KeyStore store)
        throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                if (x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                    Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName());
                    if (certName.equals(issuerRDN)) {
                        return certs;
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

private String getAliasForX509Cert(String issuer, BigInteger serialNumber, boolean useSerialNumber, KeyStore ks)
        throws WSSecurityException {
    Vector issuerRDN = splitAndTrim(issuer);
    X509Certificate x509cert;
    Vector certRDN;//from  w  w w. j av a  2 s .com
    Certificate cert;
    try {
        for (Enumeration e = ks.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = this.getCertificates(alias);

            if (certs == null || certs.length == 0) {
                return null;
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            x509cert = (X509Certificate) cert;
            if (useSerialNumber && x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                certRDN = splitAndTrim(x509cert.getIssuerDN().getName());
                if (certRDN.equals(issuerRDN)) {
                    return alias;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }
    return null;
}

From source file:controller.CCInstance.java

private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert)
        throws GeneralSecurityException, OCSPException, IOException, OperatorException {
    if (checkCert == null || rootCert == null) {
        return null;
    }// w w w.j a v  a 2  s .  c  o  m
    String url = CertificateUtil.getOCSPURL(checkCert);

    if (url == null) {
        return null;
    }
    try {
        OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
        byte[] array = request.getEncoded();
        URL urlt = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlt.openConnection();
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        con.setDoOutput(true);

        OutputStream out = con.getOutputStream();
        try (DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out))) {
            dataOut.write(array);
            dataOut.flush();
        }

        if (con.getResponseCode() / 100 != 2) {
            throw new IOException(
                    MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
        }
        //Get Response
        InputStream in = (InputStream) con.getContent();
        return new OCSPResp(in);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers,
        Date validationDate) {//from w w  w .ja va 2 s .  c  om
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.CRL,
            CertificateValidity.UNKNOWN);

    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();

        String crlURL = getCrlUri(certificate);
        if (crlURL == null) {
            log.error("CRL's URL for '" + subjectX500Principal + "' is empty");
            return status;
        }

        log.debug("CRL's URL for '" + subjectX500Principal + "' is '" + crlURL + "'");

        X509CRL x509crl = getCrl(crlURL);
        if (!validateCRL(x509crl, certificate, issuer, validationDate)) {
            log.error("The CRL is not valid!");
            status.setValidity(CertificateValidity.INVALID);
            return status;
        }

        X509CRLEntry crlEntry = x509crl.getRevokedCertificate(certificate.getSerialNumber());
        if (crlEntry == null) {
            log.debug("CRL status is valid for '" + subjectX500Principal + "'");
            status.setValidity(CertificateValidity.VALID);
        } else if (crlEntry.getRevocationDate().after(validationDate)) {
            log.warn("CRL revocation time after the validation date, the certificate '" + subjectX500Principal
                    + "' was valid at " + validationDate);
            status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
            status.setValidity(CertificateValidity.VALID);
        } else {
            log.info("CRL for certificate '" + subjectX500Principal + "' is revoked since "
                    + crlEntry.getRevocationDate());
            status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
            status.setRevocationDate(crlEntry.getRevocationDate());
            status.setValidity(CertificateValidity.REVOKED);
        }
    } catch (Exception ex) {
        log.error("CRL exception: ", ex);
    }

    return status;
}

From source file:org.bitrepository.protocol.security.PermissionStore.java

/**
 * Load permissions and certificates into the store based.
 * @param permissions the PermissionSet from RepositorySettings.
 * @param componentID the ID of the component using the PermissionStore. 
 * @throws CertificateException in case a bad certificate data in PermissionSet.   
 *//*w  w w  .j  a va2  s .  c o  m*/
public void loadPermissions(PermissionSet permissions, String componentID) throws CertificateException {
    if (permissions != null) {
        Set<Operation> allowedOperations;
        Set<String> allowedUsers;
        for (Permission permission : permissions.getPermission()) {
            if (permission.getCertificate().getAllowedCertificateUsers() != null) {
                allowedUsers = new HashSet<String>();
                allowedUsers.addAll(permission.getCertificate().getAllowedCertificateUsers().getIDs());
            } else {
                allowedUsers = null;
            }

            allowedOperations = new HashSet<Operation>();
            X509Certificate certificate = null;
            if (permission.getOperationPermission() != null) {
                for (OperationPermission perm : permission.getOperationPermission()) {
                    if (perm.getAllowedComponents() == null
                            || perm.getAllowedComponents().getIDs().contains(componentID)) {
                        allowedOperations.add(perm.getOperation());
                    }
                }
                if (!allowedOperations.isEmpty()) {
                    certificate = makeCertificate(permission.getCertificate().getCertificateData());
                }
            }
            if (permission.getInfrastructurePermission().contains(InfrastructurePermission.MESSAGE_SIGNER)) {
                if (certificate == null) {
                    certificate = makeCertificate(permission.getCertificate().getCertificateData());
                }
            }

            if (certificate != null) {
                CertificateID certID = new CertificateID(certificate.getIssuerX500Principal(),
                        certificate.getSerialNumber());
                CertificatePermission certificatePermission = new CertificatePermission(certificate,
                        allowedOperations, allowedUsers);
                permissionMap.put(certID, certificatePermission);
            }
        }
    } else {
        log.info("The provided PermissionSet was null");
    }
}

From source file:org.dogtagpki.server.rest.UserService.java

public UserCertData createUserCertData(String userID, X509Certificate cert) throws Exception {

    UserCertData userCertData = new UserCertData();

    userCertData.setVersion(cert.getVersion());
    userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
    userCertData.setIssuerDN(cert.getIssuerDN().toString());
    userCertData.setSubjectDN(cert.getSubjectDN().toString());

    userID = URLEncoder.encode(userID, "UTF-8");
    String certID = URLEncoder.encode(userCertData.getID(), "UTF-8");
    URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}/certs/{certID}").build(userID,
            certID);/*from  www.  ja  v  a 2 s.c o  m*/
    userCertData.setLink(new Link("self", uri));

    return userCertData;
}

From source file:org.josso.auth.scheme.X509CertificateAuthScheme.java

/**
 * @throws SSOAuthenticationException/*ww w . ja v  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;
            }
        }
    }

    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;
    }

    // Find UID
    // (We could just use getUID() to authenticate user
    // without previous validation against known certificates?)
    _uid = getUID();
    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;
}