Example usage for java.security.cert X509Certificate getVersion

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

Introduction

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

Prototype

public abstract int getVersion();

Source Link

Document

Gets the version (version number) value from the certificate.

Usage

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

/**
 * Sets the KeyIdentifier Element as a X509 Subject-Key-Identifier (SKI). Takes a X509
 * certificate, gets it SKI data, converts into base 64 and inserts it into a
 * <code>wsse:KeyIdentifier</code> element, which is placed in the
 * <code>wsse:SecurityTokenReference</code> element.
 * /*from  w w  w . j  a  v  a2  s  . c o m*/
 * @param cert
 *            is the X509 certificate to get the SKI
 * @param crypto
 *            is the Crypto implementation. Used to read SKI info bytes from certificate
 */
public void setKeyIdentifierSKI(X509Certificate cert, Crypto crypto) throws WSSecurityException {
    //
    // As per the 1.1 specification, SKI can only be used for a V3 certificate
    //
    if (cert.getVersion() != 3) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "invalidCertForSKI",
                new Object[] { new Integer(cert.getVersion()) });
    }

    Document doc = this.element.getOwnerDocument();
    byte data[] = crypto.getSKIBytesFromCert(cert);

    org.w3c.dom.Text text = doc.createTextNode(Base64.encode(data));
    createKeyIdentifier(doc, SKI_URI, text, true);
}

From source file:org.apache.xml.security.keys.content.x509.XMLX509SKI.java

/**
 * Method getSKIBytesFromCert//from  ww  w.  j a v a2 s.  c  o m
 *
 * @param cert
 * @return ski bytes from the given certificate
 *
 * @throws XMLSecurityException
 * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
 */
public static byte[] getSKIBytesFromCert(X509Certificate cert) throws XMLSecurityException {

    if (cert.getVersion() < 3) {
        Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
        throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
    }

    /*
     * Gets the DER-encoded OCTET string for the extension value 
     * (extnValue) identified by the passed-in oid String. The oid 
     * string is represented by a set of positive whole numbers 
     * separated by periods.
     */
    byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
    if (extensionValue == null) {
        throw new XMLSecurityException("certificate.noSki.null");
    }

    /**
     * Strip away first four bytes from the extensionValue 
     * The first two bytes are the tag and length of the extensionValue
     * OCTET STRING, and the next two bytes are the tag and length of
     * the ski OCTET STRING.
     */
    byte skidValue[] = new byte[extensionValue.length - 4];

    System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);

    if (log.isDebugEnabled()) {
        log.debug("Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}

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 w  w w .j a  v a2  s  .  c  o m*/
    userCertData.setLink(new Link("self", uri));

    return userCertData;
}

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

/**
 * Adds a certificate to a user//from   w w  w.  jav  a 2s  . co  m
 * <P>
 *
 * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
 * ui/admin-protocol-definition.html#user-admin
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
 * users/groups)
 * </ul>
 */
@Override
public Response addUserCert(String userID, UserCertData userCertData) {

    if (userCertData == null)
        throw new BadRequestException("Certificate data is null.");

    // ensure that any low-level exceptions are reported
    // to the signed audit log and stored as failures
    try {
        if (userID == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
            throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
        }

        IUser user = userGroupManager.createUser(userID);

        String encoded = userCertData.getEncoded();

        // no cert is a success
        if (encoded == null) {
            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);
            return createOKResponse();
        }

        // only one cert added per operation
        X509Certificate cert = null;

        // Base64 decode cert
        byte binaryCert[] = Cert.parseCertificate(encoded);

        try {
            cert = new X509CertImpl(binaryCert);

        } catch (CertificateException e) {
            CMS.debug("UserService: Submitted data is not an X.509 certificate: " + e);
            // ignore
        }

        if (cert == null) {
            // TODO: Remove this code. Importing PKCS #7 is not supported.

            // cert chain direction
            boolean assending = true;

            // could it be a pkcs7 blob?
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_IS_PK_BLOB"));

            try {
                CryptoManager manager = CryptoManager.getInstance();

                PKCS7 pkcs7 = new PKCS7(binaryCert);

                X509Certificate p7certs[] = pkcs7.getCertificates();

                if (p7certs.length == 0) {
                    CMS.debug("UserService: PKCS #7 data contains no certificates");
                    throw new BadRequestException("PKCS #7 data contains no certificates");
                }

                // fix for 370099 - cert ordering can not be assumed
                // find out the ordering ...

                // self-signed and alone? take it. otherwise test
                // the ordering
                if (p7certs[0].getSubjectDN().toString().equals(p7certs[0].getIssuerDN().toString())
                        && (p7certs.length == 1)) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT"));

                } else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_ACEND_ORD"));

                } else if (p7certs[1].getIssuerDN().toString().equals(p7certs[0].getSubjectDN().toString())) {
                    assending = false;
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_DESC_ORD"));
                    cert = p7certs[p7certs.length - 1];

                } else {
                    // not a chain, or in random order
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_BAD_CHAIN"));
                    throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
                }

                CMS.debug("UserService: "
                        + CMS.getLogMessage("ADMIN_SRVLT_CHAIN_STORED_DB", String.valueOf(p7certs.length)));

                int j = 0;
                int jBegin = 0;
                int jEnd = 0;

                if (assending == true) {
                    jBegin = 1;
                    jEnd = p7certs.length;
                } else {
                    jBegin = 0;
                    jEnd = p7certs.length - 1;
                }

                // store the chain into cert db, except for the user cert
                for (j = jBegin; j < jEnd; j++) {
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN",
                            String.valueOf(j), String.valueOf(p7certs[j].getSubjectDN())));
                    org.mozilla.jss.crypto.X509Certificate leafCert = manager
                            .importCACertPackage(p7certs[j].getEncoded());

                    if (leafCert == null) {
                        CMS.debug("UserService: missing leaf certificate");
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NULL"));
                    } else {
                        CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NON_NULL"));
                    }

                    if (leafCert instanceof InternalCertificate) {
                        ((InternalCertificate) leafCert).setSSLTrust(InternalCertificate.VALID_CA
                                | InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA);
                    } else {
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT",
                                String.valueOf(p7certs[j].getSubjectDN())));
                    }
                }

                /*
                } catch (CryptoManager.UserCertConflictException e) {
                // got a "user cert" in the chain, most likely the CA
                // cert of this instance, which has a private key.  Ignore
                log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", e.toString()));
                */
            } catch (PKIException e) {
                CMS.debug("UserService: Unable to import user certificate from PKCS #7 data: " + e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw e;

            } catch (Exception e) {
                CMS.debug(e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw new PKIException("Unable to import user certificate from PKCS #7 data: " + e.getMessage(),
                        e);
            }
        }

        try {
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_BEFORE_VALIDITY"));
            cert.checkValidity(); // throw exception if fails

            user.setX509Certificates(new X509Certificate[] { cert });
            userGroupManager.addUserCert(user);

            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);

            // read the data back

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

            userCertData = getUserCertData(userID, URLEncoder.encode(certID, "UTF-8"));

            return createCreatedResponse(userCertData, userCertData.getLink().getHref());

        } catch (CertificateExpiredException e) {
            CMS.debug("UserService: Certificate expired: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate expired: " + e.getMessage(), e);

        } catch (CertificateNotYetValidException e) {
            CMS.debug("UserService: Certificate not yet valid: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate not yet valid: " + e.getMessage(), e);
        }

    } catch (PKIException e) {
        CMS.debug("UserService: Unable to import user certificate: " + e);
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw e;

    } catch (Exception e) {
        CMS.debug(e);
        log(ILogger.LL_FAILURE, e.toString());
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw new PKIException("Unable to import user certificate: " + e.getMessage(), e);
    }
}

From source file:org.ejbca.ui.web.CertificateView.java

/** Method that returns the version number of the X509 certificate. */
public String getVersion() {
    if (certificate instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) certificate;
        return Integer.toString(x509cert.getVersion());
    } else {// ww  w.j  av  a2  s  .co  m
        return String.valueOf(CVCertificateBody.CVC_VERSION);
    }
}

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;//  www  .  ja v  a2  s.  c  o  m
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:org.signserver.admin.gui.ViewCertificateFrame.java

private void viewCertificate(final X509Certificate certificate) {
    this.certificate = certificate;
    if (certificate == null) {
        fields = null;/*from w w w .  j  a v a  2 s  . c om*/

    } else {
        fields = new ArrayList<Field>();

        fields.add(new Field("Version", String.valueOf(certificate.getVersion())));
        fields.add(new Field("Serial Number", certificate.getSerialNumber().toString(16)));
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(new Field("Issuer", String.valueOf(certificate.getIssuerDN())));
        fields.add(new Field("Validity Not Before", String.valueOf(certificate.getNotBefore())));
        fields.add(new Field("Validity Not After", String.valueOf(certificate.getNotAfter())));
        fields.add(new Field("Subject", String.valueOf(certificate.getSubjectDN())));
        fields.add(new Field("Subject Public Key Algorithm",
                String.valueOf(certificate.getPublicKey().getAlgorithm())));
        fields.add(new Field("Subject's Public Key",
                new String(Hex.encode(certificate.getPublicKey().getEncoded()))));
        if (certificate.getCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getCriticalExtensionOIDs()) {
                fields.add(new Field("Critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        if (certificate.getNonCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getNonCriticalExtensionOIDs()) {
                fields.add(new Field("Non critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(
                new Field("Certificate Signature Value", new String(Hex.encode(certificate.getSignature()))));

        fieldsList.setModel(new AbstractListModel() {

            @Override
            public int getSize() {
                return fields.size();
            }

            @Override
            public Object getElementAt(int index) {
                return fields.get(index);
            }
        });
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the certificate meta data information such as version expiry data
 *
 * @param certificate Relevant certificate to get certificate meta data information.
 * @return Certificate meta data information.
 *//*w w w. ja v  a  2s .co  m*/
private CertificateInformationDTO getCertificateMetaData(X509Certificate certificate) {
    CertificateInformationDTO certificateInformation = new CertificateInformationDTO();
    certificateInformation
            .setStatus(certificate.getNotAfter().getTime() > System.currentTimeMillis() ? "Active" : "Expired");
    certificateInformation.setFrom(certificate.getNotBefore().toString());
    certificateInformation.setTo(certificate.getNotAfter().toString());
    certificateInformation.setSubject(certificate.getSubjectDN().toString());
    certificateInformation.setVersion(String.valueOf(certificate.getVersion()));
    return certificateInformation;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse)
        throws CertificateManagementDAOException {
    try {/*from   w  w w  .ja v  a2 s  . co  m*/
        if (certificateBytes != null) {
            java.security.cert.Certificate x509Certificate = (java.security.cert.Certificate) Serializer
                    .deserialize(certificateBytes);
            if (x509Certificate instanceof X509Certificate) {
                X509Certificate certificate = (X509Certificate) x509Certificate;
                certificateResponse.setNotAfter(certificate.getNotAfter().getTime());
                certificateResponse.setNotBefore(certificate.getNotBefore().getTime());
                certificateResponse.setCertificateserial(certificate.getSerialNumber());
                certificateResponse.setIssuer(certificate.getIssuerDN().getName());
                certificateResponse.setSubject(certificate.getSubjectDN().getName());
                certificateResponse.setCertificateVersion(certificate.getVersion());
            }
        }
    } catch (ClassNotFoundException | IOException e) {
        String errorMsg = "Error while during deserialization of the certificate.";
        throw new CertificateManagementDAOException(errorMsg, e);
    }

}

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

/**
 * @param cert//  w  w  w  .j  ava  2 s .com
 * @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;
}