java.security.cert.X509Certificate Java Examples

The following examples show how to use java.security.cert.X509Certificate. 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: TPMAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 7 votes vote down vote up
private void validateX5c(TPMAttestationStatement attestationStatement, TPMSAttest certInfo, AuthenticatorData<RegistrationExtensionAuthenticatorOutput<?>> authenticatorData) {
    X509Certificate aikCert = attestationStatement.getX5c().getEndEntityAttestationCertificate().getCertificate();

    /// Verify the sig is a valid signature over certInfo using the attestation public key in aikCert with the algorithm specified in alg.
    String jcaName = getJcaName(attestationStatement.getAlg());
    Signature certInfoSignature = SignatureUtil.createSignature(jcaName);
    try {
        certInfoSignature.initVerify(aikCert.getPublicKey());
        certInfoSignature.update(certInfo.getBytes());
        if (!certInfoSignature.verify(attestationStatement.getSig())) {
            throw new BadAttestationStatementException("hash of certInfo doesn't match with sig.");
        }
    } catch (SignatureException | InvalidKeyException e) {
        throw new BadAttestationStatementException("Failed to validate the signature.", e);
    }

    /// Verify that aikCert meets the requirements in ยง8.3.1 TPM Attestation Statement Certificate Requirements.
    validateAikCert(aikCert);

    /// If aikCert contains an extension with OID 1 3 6 1 4 1 45724 1 1 4 (id-fido-gen-ce-aaguid) verify that the value of this extension matches the aaguid in authenticatorData.
    byte[] aaguidBytes = aikCert.getExtensionValue(ID_FIDO_GEN_CE_AAGUID);
    if (aaguidBytes != null && !Objects.equals(new AAGUID(aaguidBytes), authenticatorData.getAttestedCredentialData().getAaguid())) {
        throw new BadAttestationStatementException("AAGUID in aikCert doesn't match with that in authenticatorData");
    }
}
 
Example #2
Source File: TrustOnFirstUseManagerTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddFingerPrintFailedToWrite() throws CertificateException, IOException {

    Path notWritable = Paths.get(tmpDir.getRoot().getPath(), "notWritable");

    Files.createFile(notWritable);
    Files.setPosixFilePermissions(notWritable, PosixFilePermissions.fromString("r--------"));

    trustManager = new TrustOnFirstUseManager(notWritable);

    X509Certificate certificate = mock(X509Certificate.class);
    when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8));
    X500Principal cn = new X500Principal("CN=localhost");
    when(certificate.getSubjectX500Principal()).thenReturn(cn);

    try {
        trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "s");
        trustManager.checkClientTrusted(new X509Certificate[]{certificate}, "s");

        failBecauseExceptionWasNotThrown(CertificateException.class);
    } catch (Exception ex) {
        assertThat(ex).isInstanceOf(CertificateException.class);
    }
}
 
Example #3
Source File: KeyDepotManagerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private EncryptionToken getEtkBasedOnX509(X509Certificate cert) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(cert);
   IdentifierType identifierType = parser.getIdentifier();
   String identifierValue = parser.getId();
   String application = parser.getApplication();
   if (identifierType != null && !StringUtils.isEmpty(identifierValue) && StringUtils.isNumeric(identifierValue)) {
      try {
         return this.getEtk(identifierType, Long.parseLong(identifierValue), application);
      } catch (NumberFormatException var7) {
         LOG.error(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND.getMessage());
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND, var7, new Object[0]);
      }
   } else {
      LOG.error(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND, new Object[0]);
   }
}
 
Example #4
Source File: AbstractConsultationServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
protected D obtainCompleteness(X509Certificate certificate, PrivateKey privateKey, C consultRequest) throws TechnicalConnectorException {
   if (certificate != null && privateKey != null) {
      GenericRequest request = ServiceFactory.getTSConsultService(certificate, privateKey);
      request.setPayload(consultRequest);

      try {
         return be.ehealth.technicalconnector.ws.ServiceFactory.getGenericWsSender().send(request).asObject(this.clazzD);
      } catch (SOAPException var6) {
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, new Object[]{var6.getMessage(), var6});
      }
   } else {
      TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.SECURITY_NO_CERTIFICATE;
      LOG.debug("\t## " + errorValue.getMessage());
      throw new TechnicalConnectorException(errorValue, (Throwable)null, new Object[0]);
   }
}
 
Example #5
Source File: ForwardBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the builder with the input parameters.
 *
 * @param params the parameter set used to build a certification path
 */
ForwardBuilder(BuilderParams buildParams, boolean searchAllCertStores) {
    super(buildParams);

    // populate sets of trusted certificates and subject DNs
    trustAnchors = buildParams.trustAnchors();
    trustedCerts = new HashSet<X509Certificate>(trustAnchors.size());
    trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size());
    for (TrustAnchor anchor : trustAnchors) {
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert != null) {
            trustedCerts.add(trustedCert);
            trustedSubjectDNs.add(trustedCert.getSubjectX500Principal());
        } else {
            trustedSubjectDNs.add(anchor.getCA());
        }
    }
    this.searchAllCertStores = searchAllCertStores;
}
 
Example #6
Source File: ForwardBuilder.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the builder with the input parameters.
 *
 * @param params the parameter set used to build a certification path
 */
ForwardBuilder(BuilderParams buildParams, boolean searchAllCertStores) {
    super(buildParams);

    // populate sets of trusted certificates and subject DNs
    trustAnchors = buildParams.trustAnchors();
    trustedCerts = new HashSet<X509Certificate>(trustAnchors.size());
    trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size());
    for (TrustAnchor anchor : trustAnchors) {
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert != null) {
            trustedCerts.add(trustedCert);
            trustedSubjectDNs.add(trustedCert.getSubjectX500Principal());
        } else {
            trustedSubjectDNs.add(anchor.getCA());
        }
    }
    this.searchAllCertStores = searchAllCertStores;
}
 
Example #7
Source File: CertificateFactory.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public CertPath engineGenerateCertPath(
    List certificates)
    throws CertificateException
{
    Iterator iter = certificates.iterator();
    Object obj;
    while (iter.hasNext())
    {
        obj = iter.next();
        if (obj != null)
        {
            if (!(obj instanceof X509Certificate))
            {
                throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString());
            }
        }
    }
    return new PKIXCertPath(certificates);
}
 
Example #8
Source File: TrustOnFirstUseManagerTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testCertificateNotValidForRecognisedAddress() throws CertificateException, IOException {
    testAddThumbPrintToKnownHostsList();

    when(certificate.getEncoded()).thenReturn("ADifferentCertificate".getBytes(UTF_8));
    X500Principal cn = new X500Principal("CN=localhost");
    when(certificate.getSubjectX500Principal()).thenReturn(cn);

    try {
        trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "str");
        failBecauseExceptionWasNotThrown(IOException.class);
    } catch (Exception ex) {
        assertThat(ex)
            .isInstanceOf(CertificateException.class)
            .hasMessageContaining("This address has been associated with a different certificate");
    }

    verify(certificate, times(3)).getEncoded();
    verify(certificate, times(3)).getSubjectX500Principal();

}
 
Example #9
Source File: GenericWsSenderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendCertificateSecured(String url, String payload, X509Certificate certificate, PrivateKey privateKey, String soapAction) throws TechnicalConnectorException {
   GenericRequest request = new GenericRequest();
   request.setPayload(payload);
   request.setEndpoint(url);
   if (soapAction != null && soapAction.isEmpty()) {
      request.setSoapAction(soapAction);
   }

   request.setHandlerChain((new HandlerChain()).register(HandlerPosition.SECURITY, new CertificateCallback(certificate, privateKey)).register(HandlerPosition.SECURITY, new SoapActionHandler()));
   request.setDefaultHandlerChain();

   try {
      return this.send(request).asString();
   } catch (SOAPException var8) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var8, new Object[]{var8.getMessage()});
   }
}
 
Example #10
Source File: PKCS7.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param issuerName the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {
    if (certificates != null) {
        if (certIssuerNames == null)
            populateCertIssuerNames();
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            BigInteger thisSerial = cert.getSerialNumber();
            if (serial.equals(thisSerial)
                && issuerName.equals(certIssuerNames[i]))
            {
                return cert;
            }
        }
    }
    return null;
}
 
Example #11
Source File: TimestampedSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates a PKCS #7 signed data message that includes a signature
 * timestamp.
 * This method is used when a signature has already been generated.
 * The signature, a signature timestamp, the signer's certificate chain,
 * and optionally the content that was signed, are packaged into a PKCS #7
 * signed data message.
 *
 * @param params The non-null input parameters.
 * @param omitContent true if the content should be omitted from the
 *        signed data message. Otherwise the content is included.
 * @param applyTimestamp true if the signature should be timestamped.
 *        Otherwise timestamping is not performed.
 * @return A PKCS #7 signed data message including a signature timestamp.
 * @throws NoSuchAlgorithmException The exception is thrown if the signature
 *         algorithm is unrecognised.
 * @throws CertificateException The exception is thrown if an error occurs
 *         while processing the signer's certificate or the TSA's
 *         certificate.
 * @throws IOException The exception is thrown if an error occurs while
 *         generating the signature timestamp or while generating the signed
 *         data message.
 * @throws NullPointerException The exception is thrown if parameters is
 *         null.
 */
public byte[] generateSignedData(ContentSignerParameters params,
    boolean omitContent, boolean applyTimestamp)
        throws NoSuchAlgorithmException, CertificateException, IOException {

    if (params == null) {
        throw new NullPointerException();
    }

    // Parse the signature algorithm to extract the digest
    // algorithm. The expected format is:
    //     "<digest>with<encryption>"
    // or  "<digest>with<encryption>and<mgf>"
    String signatureAlgorithm = params.getSignatureAlgorithm();

    X509Certificate[] signerChain = params.getSignerCertificateChain();
    byte[] signature = params.getSignature();

    // Include or exclude content
    byte[] content = (omitContent == true) ? null : params.getContent();

    URI tsaURI = null;
    if (applyTimestamp) {
        tsaURI = params.getTimestampingAuthority();
        if (tsaURI == null) {
            // Examine TSA cert
            tsaURI = getTimestampingURI(
                params.getTimestampingAuthorityCertificate());
            if (tsaURI == null) {
                throw new CertificateException(
                    "Subject Information Access extension not found");
            }
        }
    }
    return PKCS7.generateSignedData(signature, signerChain, content,
                                    params.getSignatureAlgorithm(), tsaURI,
                                    params.getTSAPolicyID(),
                                    params.getTSADigestAlg());
}
 
Example #12
Source File: TimestampedSigner.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Examine the certificate for a Subject Information Access extension
 * (<a href="http://tools.ietf.org/html/rfc5280">RFC 5280</a>).
 * The extension's {@code accessMethod} field should contain the object
 * identifier defined for timestamping: 1.3.6.1.5.5.7.48.3 and its
 * {@code accessLocation} field should contain an HTTP or HTTPS URL.
 *
 * @param tsaCertificate An X.509 certificate for the TSA.
 * @return An HTTP or HTTPS URI or null if none was found.
 */
public static URI getTimestampingURI(X509Certificate tsaCertificate) {

    if (tsaCertificate == null) {
        return null;
    }
    // Parse the extensions
    try {
        byte[] extensionValue =
            tsaCertificate.getExtensionValue(SUBJECT_INFO_ACCESS_OID);
        if (extensionValue == null) {
            return null;
        }
        DerInputStream der = new DerInputStream(extensionValue);
        der = new DerInputStream(der.getOctetString());
        DerValue[] derValue = der.getSequence(5);
        AccessDescription description;
        GeneralName location;
        URIName uri;
        for (int i = 0; i < derValue.length; i++) {
            description = new AccessDescription(derValue[i]);
            if (description.getAccessMethod()
                    .equals((Object)AD_TIMESTAMPING_Id)) {
                location = description.getAccessLocation();
                if (location.getType() == GeneralNameInterface.NAME_URI) {
                    uri = (URIName) location.getName();
                    if (uri.getScheme().equalsIgnoreCase("http") ||
                            uri.getScheme().equalsIgnoreCase("https")) {
                        return uri.getURI();
                    }
                }
            }
        }
    } catch (IOException ioe) {
        // ignore
    }
    return null;
}
 
Example #13
Source File: X509CertPath.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an <code>X509CertPath</code> from a <code>List</code> of
 * <code>X509Certificate</code>s.
 * <p>
 * The certificates are copied out of the supplied <code>List</code>
 * object.
 *
 * @param certs a <code>List</code> of <code>X509Certificate</code>s
 * @exception CertificateException if <code>certs</code> contains an element
 *                      that is not an <code>X509Certificate</code>
 */
@SuppressWarnings("unchecked")
public X509CertPath(List<? extends Certificate> certs) throws CertificateException {
    super("X.509");

    // Ensure that the List contains only X509Certificates
    //
    // Note; The certs parameter is not necessarily to be of Certificate
    // for some old code. For compatibility, to make sure the exception
    // is CertificateException, rather than ClassCastException, please
    // don't use
    //     for (Certificate obj : certs)
    for (Object obj : certs) {
        if (obj instanceof X509Certificate == false) {
            throw new CertificateException
                ("List is not all X509Certificates: "
                + obj.getClass().getName());
        }
    }

    // Assumes that the resulting List is thread-safe. This is true
    // because we ensure that it cannot be modified after construction
    // and the methods in the Sun JDK 1.4 implementation of ArrayList that
    // allow read-only access are thread-safe.
    this.certs = Collections.unmodifiableList(
            new ArrayList<X509Certificate>((List<X509Certificate>)certs));
}
 
Example #14
Source File: P11KeyStore.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void storeChain(String alias, X509Certificate[] chain)
            throws PKCS11Exception, CertificateException {

    // add new chain
    //
    // end cert has CKA_LABEL and CKA_ID set to alias.
    // other certs in chain have neither set.

    storeCert(alias, chain[0]);
    storeCaCerts(chain, 1);
}
 
Example #15
Source File: InsecureExtendedTrustManager.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
    try {
        DEFAULT_EXTENDED_TRUST_MANAGER.checkClientTrusted(x509Certificates, s, socket);
    } catch (CertificateException e) {
        log.debug("Accepting an untrusted client certificate: {}", x509Certificates[0].getSubjectDN(), e);
    }
}
 
Example #16
Source File: b.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public void checkServerTrusted(X509Certificate ax509certificate[], String s)
{
    if (a == null)
    {
        a = ax509certificate;
        Log.v("openauth", "init at checkServerTrusted");
    }
}
 
Example #17
Source File: SecureKeysAndSignerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCertificateAuthority() throws Exception {
    KeyPair caKey = SecureKeys.newKeyPair();
    X509Certificate caCert = new FluentKeySigner("the-root", caKey).ca(0).selfsign().getAuthorityCertificate();

    FluentKeySigner signer = new FluentKeySigner(caCert, caKey);
    Assert.assertEquals("the-root", signer.getCommonName());
    
    KeyPair aKey = SecureKeys.newKeyPair();
    X509Certificate aCert = signer.newCertificateFor("A", aKey);
    
    Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(aCert, caCert, false));
}
 
Example #18
Source File: CompleteCertRefsVerifier.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public QualifyingProperty verify(
        CompleteCertificateRefsData propData,
        QualifyingPropertyVerificationContext ctx) throws InvalidPropertyException
{
    List<X509Certificate> caCerts = ctx.getCertChainData().getCertificateChain();
    caCerts = caCerts.subList(1, caCerts.size());
    Collection<CertRef> caCertRefs = propData.getCertRefs();

    // "Check that there are no references to certificates out of those that
    // are part of the certification path."

    for (X509Certificate caCert : caCerts)
    {
        CertRef caRef = CertRefUtils.findCertRef(caCert, caCertRefs, this.dnComparer);
        if (null == caRef)
            throw new CompleteCertRefsCertNotFoundException(caCert);
        try
        {
            CertRefUtils.checkCertRef(caRef, caCert, messageDigestProvider);
        } catch (CertRefUtils.InvalidCertRefException ex)
        {
            throw new CompleteCertRefsReferenceException(caCert, caRef, ex.getMessage());
        }
    }

    return new CompleteCertificateRefsProperty(Collections.unmodifiableList(caCerts));
}
 
Example #19
Source File: XMLX509Certificate.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor XMLX509Certificate
 *
 * @param doc
 * @param x509certificate
 * @throws XMLSecurityException
 */
public XMLX509Certificate(Document doc, X509Certificate x509certificate)
    throws XMLSecurityException {
    super(doc);

    try {
        this.addBase64Text(x509certificate.getEncoded());
    } catch (java.security.cert.CertificateEncodingException ex) {
        throw new XMLSecurityException("empty", ex);
    }
}
 
Example #20
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static X509Certificate generateX509FromInputStream(InputStream instr) {
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BCFIPS");
        return (X509Certificate) certFactory.generateCertificate(instr);
    } catch (CertificateException | NoSuchProviderException ex) {
        logp(Level.SEVERE, classname, "generateX509FromBytes", "CRYPTO-MSG-1000", printStackTrace(ex));
    }
    return null;
}
 
Example #21
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 #22
Source File: SFTrustManagerIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Read certificates from a file.
 *
 * @param filename file name under resources directory
 * @return an array of X509Certificate
 * @throws Throwable raise if any error occurs
 */
private List<X509Certificate> getX509CertificatesFromFile(String filename) throws Throwable
{
  CertificateFactory fact = CertificateFactory.getInstance("X.509");
  List<X509Certificate> certList = new ArrayList<>();
  for (Certificate cert : fact.generateCertificates(getFile(filename)))
  {
    certList.add((X509Certificate) cert);
  }
  return certList;
}
 
Example #23
Source File: CertUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of certs from files and create a CertPath from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @throws Exception on error
 */
public static CertPath buildPath(String relPath, String [] fileNames)
    throws Exception {
    List<X509Certificate> list = new ArrayList<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        list.add(0, getCertFromFile(relPath + fileNames[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    return(cf.generateCertPath(list));
}
 
Example #24
Source File: X509SubjectNameResolver.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method engineResolvePublicKey
 *
 * @param element
 * @param BaseURI
 * @param storage
 * @return null if no {@link PublicKey} could be obtained
 * @throws KeyResolverException
 */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
 
Example #25
Source File: CertReplace.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param args {cacerts keystore, cert chain}
 */
public static void main(String[] args) throws Exception {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(args[0]), "changeit".toCharArray());
    Validator v = Validator.getInstance
        (Validator.TYPE_PKIX, Validator.VAR_GENERIC, ks);
    X509Certificate[] chain = createPath(args[1]);
    System.out.println("Chain: ");
    for (X509Certificate c: v.validate(chain)) {
        System.out.println("   " + c.getSubjectX500Principal() +
                " issued by " + c.getIssuerX500Principal());
    }
}
 
Example #26
Source File: DefaultTlsSocketPlugin.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void verify(String host, SSLSession session, Options options, long serverThreadId)
    throws SSLException {
  HostnameVerifierImpl hostnameVerifier = new HostnameVerifierImpl();
  if (!hostnameVerifier.verify(host, session, serverThreadId)) {

    // Use proprietary verify method in order to have an exception with a better description
    // of error.
    Certificate[] certs = session.getPeerCertificates();
    X509Certificate cert = (X509Certificate) certs[0];
    hostnameVerifier.verify(host, cert, serverThreadId);
  }
}
 
Example #27
Source File: ResourceCertificateSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate findBySubjectAndPublicKey(X509Certificate cert) {
    ensureInitialized();
    java.security.cert.TrustAnchor anchor = mIndex.findBySubjectAndPublicKey(cert);
    if (anchor == null) {
        return null;
    }
    return anchor.getTrustedCert();
}
 
Example #28
Source File: BuildEEBasicConstraints.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example #29
Source File: ConnectionTcp.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns any client certificates.
 * @throws CertificateException
 */
@Override
public X509Certificate []clientCertificates()
  throws CertificateException
{
  return _socket.getClientCertificates();
}
 
Example #30
Source File: PKITest.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private VaultResponseData generateKeyPair(Date startDate, long valid) throws Exception {
    CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA");
    certGen.generate(2048);

    X500Name x500Name = new X500Name("CN=Test");
    X509Certificate cert = certGen.getSelfCertificate(x500Name, startDate, valid);


    byte[] encodedPrivateKey = certGen.getPrivateKey().getEncoded();
    byte[] encodedPublicKey = cert.getEncoded();

    String privateKeySb = "-----BEGIN PRIVATE KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPrivateKey) +
            "\n-----END PRIVATE KEY-----";
    String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPublicKey) +
            "\n-----END PUBLIC KEY-----";

    privateKeySb = privateKeySb.replaceAll("\\n", "\\\\n");
    privateKeySb = privateKeySb.replaceAll("\\r", "");

    publicKey = publicKey.replaceAll("\\n", "\\\\n");
    publicKey = publicKey.replaceAll("\\r", "");

    VaultResponseData vaultResponseData = new VaultResponseData();
    vaultResponseData.setPrivate_key(privateKeySb);
    vaultResponseData.setCertificate(publicKey);
    return vaultResponseData;
}