Java Code Examples for java.security.cert.X509Certificate#getVersion()

The following examples show how to use java.security.cert.X509Certificate#getVersion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExprUrlSSLVersion.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected Number[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        return new Number[]{sc.getVersion()};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 2
Source File: XMLX509SKI.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @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.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 3
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert.with.weak"));
    PublicKey pkey = cert.getPublicKey();
    String sigName = cert.getSigAlgName();
    // No need to warn about sigalg of a trust anchor
    if (!isTrustedCert(cert)) {
        sigName = withWeak(sigName);
    }
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("SHA-1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    sigName,
                    withWeak(pkey),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 4
Source File: XMLX509SKI.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @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.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 5
Source File: XMLX509SKI.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @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.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 6
Source File: XMLX509SKI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @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.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 7
Source File: XMLX509SKI.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @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.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example 8
Source File: X509CertificateTrustManager.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks the server certificate.  If it isn't trusted by the trust manager
 * passed to the constructor, then the user will be prompted to accept the
 * certificate.
 */
public void checkServerTrusted(X509Certificate[] chain, String type)
		throws CertificateException {
  try {
  	for (int i=0; i<trustManagers.length; i++) {
  		if (trustManagers[i] instanceof X509TrustManager)
  			((X509TrustManager)trustManagers[i]).checkServerTrusted(chain,type);
  	}
    return;
  } catch (CertificateException ce) {
     X509Certificate cert = chain[0];
     String certInfo = "Version: " + cert.getVersion() + "\n";
     certInfo = certInfo.concat("Serial Number: " + cert.getSerialNumber()+"\n");
     certInfo = certInfo.concat("Signature Algorithm: " + cert.getSigAlgName()+"\n");
     certInfo = certInfo.concat("Issuer: " + cert.getIssuerDN().getName()+"\n");
     certInfo = certInfo.concat("Valid From: " + cert.getNotBefore()+"\n");
     certInfo = certInfo.concat("Valid To: " + cert.getNotAfter()+"\n");
     certInfo = certInfo.concat("Subject DN: " + cert.getSubjectDN().getName()+"\n");
     certInfo = certInfo.concat("Public Key: " + cert.getPublicKey().getFormat()+"\n");

     int accept = JOptionPane.showConfirmDialog(null,certInfo,
                 "Accept Certificate",javax.swing.JOptionPane.YES_NO_OPTION);
     if (accept != JOptionPane.YES_OPTION) {
       throw new java.security.cert.CertificateException("Certificate Not Accepted");
     }
  	}
}
 
Example 9
Source File: PackedAttestation.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject ctapMakeCredResp, AuthenticatorData authDataStruct) throws AttestationException {
  try {
    byte[] clientDataHash = hash(clientDataJSON);

    byte[] signatureBase = Buffer.buffer()
      .appendBytes(authDataStruct.getRaw())
      .appendBytes(clientDataHash)
      .getBytes();

    JsonObject attStmt = ctapMakeCredResp.getJsonObject("attStmt");
    byte[] signature = b64dec.decode(attStmt.getString("sig"));

    boolean signatureValid;

    if (attStmt.containsKey("x5c")) {
      /* ----- Verify FULL attestation ----- */
      JsonArray x5c = attStmt.getJsonArray("x5c");

      final X509Certificate x509Certificate = (X509Certificate) x509.generateCertificate(new ByteArrayInputStream(b64dec.decode(x5c.getString(0))));
      // check the certificate
      x509Certificate.checkValidity();
      // certificate valid lets verify the principal
      String[] values = x509Certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).split(",");
      int count = 0;

      for (String value : values) {
        if (value.startsWith("OU=")) {
          if (!value.equals("OU=Authenticator Attestation")) {
            throw new AttestationException("Batch certificate OU MUST be set strictly to 'Authenticator Attestation'!");
          }
          count++;
          continue;
        }
        if (value.startsWith("CN=")) {
          if (value.equals("CN=")) {
            throw new AttestationException("Batch certificate CN MUST no be empty!");
          }
          count++;
          continue;
        }
        if (value.startsWith("O=")) {
          if (value.equals("O=")) {
            throw new AttestationException("Batch certificate O MUST no be empty!");
          }
          count++;
          continue;
        }
        if (value.startsWith("C=")) {
          if (value.length() != 4) {
            throw new AttestationException("Batch certificate C MUST be set to two character ISO 3166 code!");
          }
          count++;
          continue;
        }
      }

      if (count != 4) {
        throw new AttestationException("Batch certificate does not contain the required subject info!");
      }


      if (x509Certificate.getBasicConstraints() != -1) {
        throw new AttestationException("Batch certificate basic constraints CA MUST be false!");
      }

      if (x509Certificate.getVersion() != 3) {
        throw new AttestationException("Batch certificate version MUST be 3(ASN1 2)!");
      }

      signatureValid = verifySignature(signature, signatureBase, x509Certificate);
      /* ----- Verify FULL attestation ENDS ----- */
    } else if (attStmt.containsKey("ecdaaKeyId")) {
      throw new AttestationException("ECDAA IS NOT SUPPORTED YET!");
    } else {
      /* ----- Verify SURROGATE attestation ----- */
      JWK key = authDataStruct.getCredentialJWK();
      signatureValid = key.verify(signature, signatureBase);
      /* ----- Verify SURROGATE attestation ENDS ----- */
    }

    if (!signatureValid) {
      throw new AttestationException("Failed to verify the signature!");
    }
  } catch (CertificateException | InvalidKeyException | SignatureException e) {
    throw new AttestationException(e);
  }
}
 
Example 10
Source File: ConstraintsChecker.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 11
Source File: Main.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 12
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert.with.weak"));
    PublicKey pkey = cert.getPublicKey();
    String sigName = cert.getSigAlgName();
    // No need to warn about sigalg of a trust anchor
    if (!isTrustedCert(cert)) {
        sigName = withWeak(sigName);
    }
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    sigName,
                    withWeak(pkey),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 13
Source File: ConstraintsChecker.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 14
Source File: SSLImplementation.java    From tn5250j with GNU General Public License v2.0 4 votes vote down vote up
public void checkServerTrusted(X509Certificate[] chain, String type)
		throws CertificateException {
	try {
		for (int i = 0; i < userTrustManagers.length; i++) {
			if (userTrustManagers[i] instanceof X509TrustManager) {
				X509TrustManager trustManager = (X509TrustManager) userTrustManagers[i];
				X509Certificate[] calist = trustManager
						.getAcceptedIssuers();
				if (calist.length > 0) {
					trustManager.checkServerTrusted(chain, type);
				} else {
					throw new CertificateException(
							"Empty list of accepted issuers (a.k.a. root CA list).");
				}
			}
		}
		return;
	} catch (CertificateException ce) {
		X509Certificate cert = chain[0];
		String certInfo = "Version: " + cert.getVersion() + "\n";
		certInfo = certInfo.concat("Serial Number: "
				+ cert.getSerialNumber() + "\n");
		certInfo = certInfo.concat("Signature Algorithm: "
				+ cert.getSigAlgName() + "\n");
		certInfo = certInfo.concat("Issuer: "
				+ cert.getIssuerDN().getName() + "\n");
		certInfo = certInfo.concat("Valid From: " + cert.getNotBefore()
				+ "\n");
		certInfo = certInfo
				.concat("Valid To: " + cert.getNotAfter() + "\n");
		certInfo = certInfo.concat("Subject DN: "
				+ cert.getSubjectDN().getName() + "\n");
		certInfo = certInfo.concat("Public Key: "
				+ cert.getPublicKey().getFormat() + "\n");

		int accept = JOptionPane
				.showConfirmDialog(null, certInfo, "Unknown Certificate - Do you accept it?",
						javax.swing.JOptionPane.YES_NO_OPTION);
		if (accept != JOptionPane.YES_OPTION) {
			throw new java.security.cert.CertificateException(
					"Certificate Rejected");
		}

		int save = JOptionPane.showConfirmDialog(null,
				"Remember this certificate?", "Save Certificate",
				javax.swing.JOptionPane.YES_NO_OPTION);

		if (save == JOptionPane.YES_OPTION) {
			try {
				userks.setCertificateEntry(cert.getSubjectDN().getName(),
						cert);
				userks.store(new FileOutputStream(userKsPath),
						userksPassword);
			} catch (Exception e) {
				logger.error("Error saving certificate [" + e.getMessage()
						+ "]");
				e.printStackTrace();
			}
		}
	}

}
 
Example 15
Source File: ConstraintsChecker.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 16
Source File: Main.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 17
Source File: ConstraintsChecker.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i +
                    ", maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 18
Source File: ConstraintsChecker.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Internal method to check that a given cert meets basic constraints.
 */
private void checkBasicConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "basic constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
        debug.println("i = " + i);
        debug.println("maxPathLength = " + maxPathLength);
    }

    /* check if intermediate cert */
    if (i < certPathLength) {
        // RFC5280: If certificate i is a version 3 certificate, verify
        // that the basicConstraints extension is present and that cA is
        // set to TRUE.  (If certificate i is a version 1 or version 2
        // certificate, then the application MUST either verify that
        // certificate i is a CA certificate through out-of-band means
        // or reject the certificate.  Conforming implementations may
        // choose to reject all version 1 and version 2 intermediate
        // certificates.)
        //
        // We choose to reject all version 1 and version 2 intermediate
        // certificates except that it is self issued by the trust
        // anchor in order to support key rollover or changes in
        // certificate policies.
        int pathLenConstraint = -1;
        if (currCert.getVersion() < 3) {    // version 1 or version 2
            if (i == 1) {                   // issued by a trust anchor
                if (X509CertImpl.isSelfIssued(currCert)) {
                    pathLenConstraint = Integer.MAX_VALUE;
                }
            }
        } else {
            pathLenConstraint = currCert.getBasicConstraints();
        }

        if (pathLenConstraint == -1) {
            throw new CertPathValidatorException
                (msg + " check failed: this is not a CA certificate",
                 null, null, -1, PKIXReason.NOT_CA_CERT);
        }

        if (!X509CertImpl.isSelfIssued(currCert)) {
            if (maxPathLength <= 0) {
               throw new CertPathValidatorException
                    (msg + " check failed: pathLenConstraint violated - "
                     + "this cert must be the last cert in the "
                     + "certification path", null, null, -1,
                     PKIXReason.PATH_TOO_LONG);
            }
            maxPathLength--;
        }
        if (pathLenConstraint < maxPathLength)
            maxPathLength = pathLenConstraint;
    }

    if (debug != null) {
        debug.println("after processing, maxPathLength = " + maxPathLength);
        debug.println(msg + " verified.");
    }
}
 
Example 19
Source File: Main.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert.with.weak"));
    PublicKey pkey = cert.getPublicKey();
    String sigName = cert.getSigAlgName();
    // No need to warn about sigalg of a trust anchor
    if (!isTrustedCert(cert)) {
        sigName = withWeak(sigName);
    }
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    sigName,
                    withWeak(pkey),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}
 
Example 20
Source File: Main.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints a certificate in a human readable format.
 */
private void printX509Cert(X509Certificate cert, PrintStream out)
    throws Exception
{
    /*
    out.println("Owner: "
                + cert.getSubjectDN().toString()
                + "\n"
                + "Issuer: "
                + cert.getIssuerDN().toString()
                + "\n"
                + "Serial number: " + cert.getSerialNumber().toString(16)
                + "\n"
                + "Valid from: " + cert.getNotBefore().toString()
                + " until: " + cert.getNotAfter().toString()
                + "\n"
                + "Certificate fingerprints:\n"
                + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                + "\n"
                + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
    */

    MessageFormat form = new MessageFormat
            (rb.getString(".PATTERN.printX509Cert"));
    Object[] source = {cert.getSubjectDN().toString(),
                    cert.getIssuerDN().toString(),
                    cert.getSerialNumber().toString(16),
                    cert.getNotBefore().toString(),
                    cert.getNotAfter().toString(),
                    getCertFingerPrint("MD5", cert),
                    getCertFingerPrint("SHA1", cert),
                    getCertFingerPrint("SHA-256", cert),
                    cert.getSigAlgName(),
                    cert.getVersion()
                    };
    out.println(form.format(source));

    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl)cert;
        X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                       + "." +
                                                       X509CertImpl.INFO);
        CertificateExtensions exts = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);
        if (exts != null) {
            printExtensions(rb.getString("Extensions."), exts, out);
        }
    }
}