Java Code Examples for java.security.cert.CertificateException

The following examples show how to use java.security.cert.CertificateException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ditto   Source File: TrustManagerFactoryFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private TrustManagerFactory createTrustManagerFactory(@Nullable final String trustedCertificates)
        throws NoSuchAlgorithmException, CertificateException, KeyStoreException,
        InvalidAlgorithmParameterException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(PKIX);
    if (trustedCertificates != null) {
        final KeyStore keystore = keyStoreFactory.newKeystore();
        final Collection<? extends Certificate> caCerts;
        final byte[] caCertsPem = trustedCertificates.getBytes(StandardCharsets.US_ASCII);
        caCerts = X509_CERTIFICATE_FACTORY.generateCertificates(new ByteArrayInputStream(caCertsPem));
        long cnt = 0;
        for (final Certificate caCert : caCerts) {
            keystore.setCertificateEntry("ca-" + cnt++, caCert);
        }
        trustManagerFactory.init(keystore);
    } else {
        // standard CAs; add revocation check
        final PKIXRevocationChecker revocationChecker =
                (PKIXRevocationChecker) CertPathBuilder.getInstance(PKIX).getRevocationChecker();
        final PKIXBuilderParameters parameters =
                new PKIXBuilderParameters(DEFAULT_CA_KEYSTORE, new X509CertSelector());
        parameters.addCertPathChecker(revocationChecker);
        trustManagerFactory.init(new CertPathTrustManagerParameters(parameters));
    }
    return trustManagerFactory;
}
 
Example 2
/**
 * {@inheritDoc}
 */
@Override
protected Map<AAGUID, Set<TrustAnchor>> loadTrustAnchors() {
    checkConfig();
    Path keystore = getKeyStore();
    try (InputStream inputStream = Files.newInputStream(keystore)) {
        KeyStore keyStoreObject = loadKeyStoreFromStream(inputStream, getPassword());
        List<String> aliases = Collections.list(keyStoreObject.aliases());
        Set<TrustAnchor> trustAnchors = new HashSet<>();
        for (String alias : aliases) {
            X509Certificate certificate = (X509Certificate) keyStoreObject.getCertificate(alias);
            trustAnchors.add(new TrustAnchor(certificate, null));
        }
        return Collections.singletonMap(AAGUID.NULL, trustAnchors);
    } catch (java.security.KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new KeyStoreException("Failed to load TrustAnchor from keystore", e);
    }
}
 
Example 3
public void checkServerTrusted(X509Certificate[] certificates, String type)
throws CertificateException {
    if (this.trustLevel.equals(TrustLevel.OPEN)) {
        return;
    }

    try {
        this.standardTrustManager.checkServerTrusted(certificates, type);
        if (this.trustLevel.equals(TrustLevel.STRICT)) {
            logger.severe(TrustLevel.STRICT + " not implemented.");
        }
    } catch (CertificateException e) {
        if (this.trustLevel.equals(TrustLevel.LOOSE) &&
            certificates != null && certificates.length == 1)
        {
                // If only one cert and its valid and it caused a
                // CertificateException, assume its selfsigned.
                X509Certificate certificate = certificates[0];
                certificate.checkValidity();
        } else {
            // If we got to here, then we're probably NORMAL. Rethrow.
            throw e;
        }
    }
}
 
Example 4
Source Project: cyberduck   Source File: S3SessionTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTrustChain() throws Exception {
    final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
        System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
    ));
    final AtomicBoolean verified = new AtomicBoolean();
    final S3Session session = new S3Session(host, new DefaultX509TrustManager() {
        @Override
        public void verify(final String hostname, final X509Certificate[] certs, final String cipher) throws CertificateException {
            verified.set(true);
            super.verify(hostname, certs, cipher);
        }
    },
        new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), host, new DisabledCertificateStore()));
    final LoginConnectionService c = new LoginConnectionService(
        new DisabledLoginCallback(),
        new DisabledHostKeyCallback(),
        new DisabledPasswordStore(),
        new DisabledProgressListener()
    );
    c.connect(session, PathCache.empty(), new DisabledCancelCallback());
    assertTrue(verified.get());
    session.close();
}
 
Example 5
Source Project: localization_nifi   Source File: PostHTTP.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 6
@Test
public void testParseAttestationRecord() throws CertificateException, IOException {
  X509Certificate x509Certificate = getAttestationRecord(CERT);
  ParsedAttestationRecord attestationRecord =
      ParsedAttestationRecord.createParsedAttestationRecord(x509Certificate);

  assertThat(attestationRecord.attestationVersion).isEqualTo(EXPECTED_ATTESTATION_VERSION);
  assertThat(attestationRecord.attestationSecurityLevel)
      .isEqualTo(EXPECTED_ATTESTATION_SECURITY_LEVEL);
  assertThat(attestationRecord.keymasterVersion).isEqualTo(EXPECTED_KEYMASTER_VERSION);
  assertThat(attestationRecord.keymasterSecurityLevel)
      .isEqualTo(EXPECTED_KEYMASTER_SECURITY_LEVEL);
  assertThat(attestationRecord.attestationChallenge).isEqualTo(EXPECTED_ATTESTATION_CHALLENGE);
  assertThat(attestationRecord.uniqueId).isEqualTo(EXPECTED_UNIQUE_ID);
  assertThat(attestationRecord.softwareEnforced).isNotNull();
  assertThat(attestationRecord.teeEnforced).isNotNull();
}
 
Example 7
/**
 * Set the attribute value.
 * @exception CertificateException on attribute handling errors.
 */
public void set(String name, Object obj)
throws CertificateException, IOException {
    if (!(obj instanceof Date)) {
        throw new CertificateException("Attribute must be of type Date.");
    }
    if (name.equalsIgnoreCase(NOT_BEFORE)) {
        notBefore = (Date)obj;
    } else if (name.equalsIgnoreCase(NOT_AFTER)) {
        notAfter = (Date)obj;
    } else {
      throw new CertificateException("Attribute name not recognized by"
                       + " CertAttrSet:PrivateKeyUsage.");
    }
    encodeThis();
}
 
Example 8
public static PublicKey pem2PublicKey(InputStream in) throws IOException {
    try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
        Object ohh = pem.readObject();
        if (ohh instanceof PEMKeyPair) {
            PEMKeyPair kp = (PEMKeyPair) ohh;
            return new JcaPEMKeyConverter().getKeyPair(kp).getPublic();
        } else if (ohh instanceof SubjectPublicKeyInfo) {
            return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) ohh);
        } else if (ohh instanceof X509CertificateHolder) {
            X509CertificateHolder certHolder = (X509CertificateHolder) ohh;
            try {
                return new JcaX509CertificateConverter().getCertificate(certHolder).getPublicKey();
            } catch (CertificateException ce) {
                throw new IllegalArgumentException("Can not read PEM: " + ce.getMessage());
            }
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example 9
/**
 * process the signature block file. Goes through the .SF file
 * and adds code signers for each section where the .SF section
 * hash was verified against the Manifest section.
 *
 *
 */
public void process(Hashtable<String, CodeSigner[]> signers,
        List<Object> manifestDigests)
    throws IOException, SignatureException, NoSuchAlgorithmException,
        JarException, CertificateException
{
    // calls Signature.getInstance() and MessageDigest.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        processImpl(signers, manifestDigests);
    } finally {
        Providers.stopJarVerification(obj);
    }

}
 
Example 10
Source Project: haven-platform   Source File: SSLUtil.java    License: Apache License 2.0 6 votes vote down vote up
private void checkTrusted(Func func) throws CertificateException {
    CertificateException ex = null;
    for (int i =0; i < list.size(); ++i) {
        X509TrustManager tm = list.get(i);
        try {
            func.apply(tm);
            // accepted
            return;
        } catch (CertificateException e) {
            if(ex == null || Throwables.has(e, CertPathValidatorException.class)) {
                ex = e;
            }
        }
    }
    if(ex != null) {
        throw ex;
    }
}
 
Example 11
Source Project: jdk8u-dev-jdk   Source File: OIDMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a name to lookup table.
 *
 * @param name the name of the attr
 * @param oid the string representation of the object identifier for
 *         the class.
 * @param clazz the Class object associated with this attribute
 * @exception CertificateException on errors.
 */
public static void addAttribute(String name, String oid, Class<?> clazz)
        throws CertificateException {
    ObjectIdentifier objId;
    try {
        objId = new ObjectIdentifier(oid);
    } catch (IOException ioe) {
        throw new CertificateException
                            ("Invalid Object identifier: " + oid);
    }
    OIDInfo info = new OIDInfo(name, objId, clazz);
    if (oidMap.put(objId, info) != null) {
        throw new CertificateException
                            ("Object identifier already exists: " + oid);
    }
    if (nameMap.put(name, info) != null) {
        throw new CertificateException("Name already exists: " + name);
    }
}
 
Example 12
Source Project: reader   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
  int length = reader.readInt();
  if (length == -1) {
    return null;
  }
  try {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Certificate[] result = new Certificate[length];
    for (int i = 0; i < result.length; i++) {
      String line = reader.readLine();
      byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
      result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
    }
    return result;
  } catch (CertificateException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example 13
Source Project: nifi   Source File: StandardKnoxConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
public RSAPublicKey getKnoxPublicKey() {
    // get the path to the public key
    final Path knoxPublicKeyPath = properties.getKnoxPublicKeyPath();

    // ensure the file exists
    if (Files.isRegularFile(knoxPublicKeyPath) && Files.exists(knoxPublicKeyPath)) {
        try (final InputStream publicKeyStream = Files.newInputStream(knoxPublicKeyPath)) {
            final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(publicKeyStream);
            return (RSAPublicKey) certificate.getPublicKey();
        } catch (final IOException | CertificateException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } else {
        throw new RuntimeException(String.format("The specified Knox public key path does not exist '%s'", knoxPublicKeyPath.toString()));
    }
}
 
Example 14
Source Project: ofdrw   Source File: SESealTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void verify() throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {
        Path path = Paths.get("target", "UserV1.esl");
//        Path path = Paths.get("target", "2_980_1587284330714.es");

        SESeal seal = SESeal.getInstance(Files.readAllBytes(path));
        SES_SignInfo signInfo = seal.getSignInfo();

        ASN1OctetString cert = signInfo.getCert();
        CertificateFactory factory = new CertificateFactory();
        X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(cert.getOctetStream());

        ASN1EncodableVector v = new ASN1EncodableVector(3);
        v.add(seal.getEsealInfo());
        v.add(cert);
        v.add(signInfo.getSignatureAlgorithm());

        Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
        sg.initVerify(certificate);
        sg.update(new DERSequence(v).getEncoded("DER"));
        byte[] sigVal = signInfo.getSignData().getBytes();
        System.out.println(sg.verify(sigVal));
    }
 
Example 15
/**
 * Create a certificate using key pair and signing certificate with CA certificate, common name and a list of subjective alternate name
 *
 * @return signed sever identity certificate
 * */
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
    List<ASN1Encodable> sans)
    throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
           NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  X500Name issuer = new X509CertificateHolder(_issuerCertificate.getEncoded()).getSubject();
  BigInteger serial = getSerial();
  X500Name subject = getSubject(commonName);

  X509v3CertificateBuilder x509v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
  buildExtensions(x509v3CertificateBuilder, publicKey);

  fillSans(sans, x509v3CertificateBuilder);

  X509Certificate signedCertificate = createCertificate(_issuerPrivateKey, x509v3CertificateBuilder);

  signedCertificate.checkValidity();
  signedCertificate.verify(_issuerCertificate.getPublicKey());

  return signedCertificate;
}
 
Example 16
Source Project: openjdk-jdk9   Source File: OIDMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a name to lookup table.
 *
 * @param name the name of the attr
 * @param oid the string representation of the object identifier for
 *         the class.
 * @param clazz the Class object associated with this attribute
 * @exception CertificateException on errors.
 */
public static void addAttribute(String name, String oid, Class<?> clazz)
        throws CertificateException {
    ObjectIdentifier objId;
    try {
        objId = new ObjectIdentifier(oid);
    } catch (IOException ioe) {
        throw new CertificateException
                            ("Invalid Object identifier: " + oid);
    }
    OIDInfo info = new OIDInfo(name, objId, clazz);
    if (oidMap.put(objId, info) != null) {
        throw new CertificateException
                            ("Object identifier already exists: " + oid);
    }
    if (nameMap.put(name, info) != null) {
        throw new CertificateException("Name already exists: " + name);
    }
}
 
Example 17
/**
 * Validate the cluster CA certificate(s) passed in the given Secret
 * and return the PemTrustOptions for trusting them.
 */
protected PemTrustOptions trustOptions(Secret clusterCaCertificateSecret) {
    Base64.Decoder decoder = Base64.getDecoder();
    CertificateFactory x509 = x509Factory();
    PemTrustOptions pto = new PemTrustOptions();
    for (Map.Entry<String, String> entry : clusterCaCertificateSecret.getData().entrySet()) {
        String entryName = entry.getKey();
        if (entryName.endsWith(".crt")) {
            log.info("Trusting certificate {} from Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
            byte[] certBytes = decoder.decode(entry.getValue());
            try {
                x509.generateCertificate(new ByteArrayInputStream(certBytes));
            } catch (CertificateException e) {
                throw corruptCertificate(clusterCaCertificateSecret, entryName, e);
            }
            pto.addCertValue(Buffer.buffer(certBytes));
        } else {
            log.warn("Ignoring non-certificate {} in Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
        }
    }
    return pto;
}
 
Example 18
Source Project: java-client-api   Source File: ConnectedRESTQA.java    License: Apache License 2.0 6 votes vote down vote up
public static DatabaseClient getDatabaseClient(String user, String password, ConnectionType connType)
		throws KeyManagementException, NoSuchAlgorithmException, IOException {
	DatabaseClient client = null;
	
	SSLContext sslcontext = null;
	SecurityContext secContext = new DatabaseClientFactory.DigestAuthContext(user,password);
	if (IsSecurityEnabled()) {
		try {
			sslcontext = getSslContext();
		} catch (UnrecoverableKeyException | KeyStoreException | CertificateException e) {
			e.printStackTrace();
		}
		secContext = secContext.withSSLContext(sslcontext).withSSLHostnameVerifier(SSLHostnameVerifier.ANY);
	}
		client = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(),
				secContext, connType);				
	return client;
}
 
Example 19
Source Project: buck   Source File: AppBuilderBase.java    License: Apache License 2.0 6 votes vote down vote up
protected PrivateKeyAndCertificate createKeystoreProperties()
    throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
  KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
  KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
  char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
  try {
    keystore.load(filesystem.getInputStreamForRelativePath(pathToKeystore), keystorePassword);
  } catch (NoSuchAlgorithmException | CertificateException e) {
    throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
  }

  String alias = keystoreProperties.getAlias();
  char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
  Key key = keystore.getKey(alias, keyPassword);
  // key can be null if alias/password is incorrect.
  if (key == null) {
    throw new HumanReadableException(
        "The keystore [%s] key.alias [%s] does not exist or does not identify a key-related "
            + "entry",
        pathToKeystore, alias);
  }

  Certificate certificate = keystore.getCertificate(alias);

  return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
 
Example 20
Source Project: okhttp-OkGo   Source File: GApp.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    try {
        for (X509Certificate certificate : chain) {
            certificate.checkValidity(); //检查证书是否过期,签名是否通过等
        }
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
 
Example 21
public static CipherTestUtils getInstance() throws IOException,
        FileNotFoundException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeySpecException {
    if (instance == null) {
        synchronized (CipherTestUtils.class) {
            if (instance == null) {
                instance = new CipherTestUtils();
            }
        }
    }
    return instance;
}
 
Example 22
public List<X509Certificate> readCertificates(String certificatesFilename) {
    try (InputStream certificatesInputStream = getClass().getResourceAsStream(certificatesFilename)) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE_X_509);
        return (List<X509Certificate>) certificateFactory.generateCertificates(certificatesInputStream);
    } catch (CertificateException | IOException e) {
        throw new SLException(e, e.getMessage());
    }
}
 
Example 23
Source Project: localization_nifi   Source File: TestListenTCP.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTLSClienAuthNoneAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException,
        UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.NONE.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createTrustSslContext(
            "src/test/resources/localhost-ts.jks",
            "localtest".toCharArray(),
            "jks",
            "TLS");

    runTCP(messages, messages.size(), clientSslContext);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
    for (int i=0; i < mockFlowFiles.size(); i++) {
        mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
    }
}
 
Example 24
Source Project: nifi   Source File: LivySessionController.java    License: Apache License 2.0 5 votes vote down vote up
private HttpClient openConnection() throws IOException {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (sslContextService != null) {
        try {
            SSLContext sslContext = getSslSocketFactory(sslContextService);
            httpClientBuilder.setSSLContext(sslContext);
        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
            throw new IOException(e);
        }
    }

    if (credentialsService != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(null, -1, null),
            new KerberosKeytabCredentials(credentialsService.getPrincipal(), credentialsService.getKeytab()));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO, new KerberosKeytabSPNegoAuthSchemeProvider()).build();
        httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(connectTimeout);
    requestConfigBuilder.setConnectionRequestTimeout(connectTimeout);
    requestConfigBuilder.setSocketTimeout(connectTimeout);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    return httpClientBuilder.build();
}
 
Example 25
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    try {
        trustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException e) {
        defaultTrustManager.checkServerTrusted(chain, authType);
    }
}
 
Example 26
Source Project: Tomcat7.0.67   Source File: JSSESocketFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load the collection of CRLs.
 *
 */
protected Collection<? extends CRL> getCRLs(String crlf)
    throws IOException, CRLException, CertificateException {

    Collection<? extends CRL> crls = null;
    InputStream is = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        is = ConfigFileLoader.getInputStream(crlf);
        crls = cf.generateCRLs(is);
    } catch(IOException iex) {
        throw iex;
    } catch(CRLException crle) {
        throw crle;
    } catch(CertificateException ce) {
        throw ce;
    } finally {
        if(is != null) {
            try{
                is.close();
            } catch(Exception ex) {
                // Ignore
            }
        }
    }
    return crls;
}
 
Example 27
/**
 * Read the trust store off the classpath.
 *
 * @return handle to inputStream containing the trust store
 * @throws CertificateException
 */
private InputStream getTrustStoreInputStream() throws CertificateException
{
    InputStream result = ResourceUtil.getInputStream(trustStoreFile);
    if (null == result)
    {
        throw new CertificateException("LdapClientTrustStoreManager.getTrustStoreInputStream file does not exist on fortress classpath" );
    }
    return result;
}
 
Example 28
Source Project: openjdk-8-source   Source File: Main.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes an X.509 certificate in base64 or binary encoding to an output
 * stream.
 */
private void dumpCert(Certificate cert, PrintStream out)
    throws IOException, CertificateException
{
    if (rfc) {
        out.println(X509Factory.BEGIN_CERT);
        out.println(Base64.getMimeEncoder().encodeToString(cert.getEncoded()));
        out.println(X509Factory.END_CERT);
    } else {
        out.write(cert.getEncoded()); // binary
    }
}
 
Example 29
Source Project: SAMLRaider   Source File: XMLHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Sign assertions in SAML message
 *
 * @param document
 *            Document in assertions should be signed
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signAssertion(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Assertion']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example 30
Source Project: openjdk-jdk8u-backup   Source File: BadPem.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example 31
Source Project: ranger   Source File: TestRangerKeyStore.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected=IOException.class)
public void testInvalidKey3() throws NoSuchAlgorithmException,
                CertificateException, IOException, KeyStoreException {

        DaoManager daoManager = Mockito.mock(DaoManager.class);
        RangerKeyStore rangerKeyStore = new RangerKeyStore(daoManager);
        String keyValue = "1 enckey";
        InputStream inputStream = generateKeyStoreFile(keyValue);
        rangerKeyStore.engineLoadKeyStoreFile(inputStream, storePass, keyPass, masterKey, fileFormat);
        inputStream.close();
}
 
Example 32
public boolean isCertificateRevoked(File certFile, DateTime validOn) throws TechnicalConnectorException {
   try {
      CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
      X509Certificate cert = (X509Certificate)certFactory.generateCertificate(new FileInputStream(certFile));
      return this.isCertificateRevoked(cert, validOn);
   } catch (FileNotFoundException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   } catch (CertificateException var6) {
      throw new CertificateVerificationException(var6.getMessage(), var6);
   }
}
 
Example 33
Source Project: j2objc   Source File: CertificateFactory1Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>generateCertPath(List certificates)</code> method
 * Assertion: returns empty CertPath if certificates is empty
 */
public void testCertificateFactory15() throws CertificateException {
    if (!X509Support) {
        fail(NotSupportMsg);
        return;
    }
    CertificateFactory[] certFs = initCertFs();
    assertNotNull("CertificateFactory objects were not created", certFs);
    List<Certificate> list = new Vector<Certificate>();
    for (int i = 0; i < certFs.length; i++) {
        CertPath cp = certFs[i].generateCertPath(list);
        List<? extends Certificate> list1 = cp.getCertificates();
        assertTrue("List should be empty", list1.isEmpty());
    }
}
 
Example 34
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType, Socket socket)
        throws CertificateException {
    List<X509Certificate> trustedChain =
            mDelegate.getTrustedChainForServer(certs, authType, socket);
    checkPins(trustedChain);
}
 
Example 35
Source Project: vertx-auth   Source File: PackedAttestation.java    License: Apache License 2.0 5 votes vote down vote up
public PackedAttestation() {
  try {
    sha256 = MessageDigest.getInstance("SHA-256");
    x509 = CertificateFactory.getInstance("X.509");
    sig = Signature.getInstance("SHA256withECDSA");
  } catch (NoSuchAlgorithmException | CertificateException e) {
    throw new AttestationException(e);
  }
}
 
Example 36
Source Project: hottub   Source File: BadPem.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example 37
Source Project: carbon-identity   Source File: ServerCrypto.java    License: Apache License 2.0 5 votes vote down vote up
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

        try {

            // Generate cert path
            java.util.List certList = java.util.Arrays.asList(certs);
            CertPath path = this.getCertificateFactory().generateCertPath(certList);

            // Use the certificates in the keystore as TrustAnchors
            PKIXParameters param = new PKIXParameters(ks);

            // Do not check a revocation list
            param.setRevocationEnabled(false);

            // Verify the trust path using the above settings
            String provider = properties
                    .getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
            CertPathValidator certPathValidator;
            if (provider == null || provider.length() == 0) {
                certPathValidator = CertPathValidator.getInstance("PKIX");
            } else {
                certPathValidator = CertPathValidator.getInstance("PKIX", provider);
            }
            certPathValidator.validate(path, param);
        } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException |
                InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "certpath",
                    new Object[]{ex.getMessage()}, ex);
        }
        return true;
    }
 
Example 38
/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
 */
@Override
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if ((certificates != null) && (certificates.length == 1)) {
        certificates[0].checkValidity();
    } else {
        standardTrustManager.checkServerTrusted(certificates, authType);
    }
}
 
Example 39
Source Project: AndroidHttpCapture   Source File: InsecureExtendedTrustManager.java    License: MIT License 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
    try {
        DEFAULT_EXTENDED_TRUST_MANAGER.checkServerTrusted(x509Certificates, s, socket);
    } catch (CertificateException e) {
        log.debug("Accepting an untrusted server certificate: {}", x509Certificates[0].getSubjectDN(), e);
    }
}
 
Example 40
Source Project: Smack   Source File: XmppHostnameVerifier.java    License: Apache License 2.0 5 votes vote down vote up
private static void match(String name, X509Certificate cert) throws CertificateException {
    if (InetAddressUtil.isIpAddress(name)) {
        matchIp(name, cert);
    }
    else {
        matchDns(name, cert);
    }
}