Search in sources :

Example 41 with Certificate

use of java.security.cert.Certificate in project Openfire by igniterealtime.

the class ExternalClientSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    if (isComplete()) {
        throw new IllegalStateException("Authentication exchange already completed.");
    }
    // There will be no further steps. Either authentication succeeds or fails, but in any case, we're done.
    complete = true;
    final Connection connection = session.getConnection();
    Certificate[] peerCertificates = connection.getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length < 1) {
        throw new SaslException("No peer certificates.");
    }
    final KeyStore keyStore = connection.getConfiguration().getIdentityStore().getStore();
    final KeyStore trustStore = connection.getConfiguration().getTrustStore().getStore();
    final X509Certificate trusted = CertificateManager.getEndEntityCertificate(peerCertificates, keyStore, trustStore);
    if (trusted == null) {
        throw new SaslException("Certificate chain of peer is not trusted.");
    }
    // Process client identities / principals.
    final ArrayList<String> principals = new ArrayList<>();
    principals.addAll(CertificateManager.getClientIdentities(trusted));
    String principal;
    switch(principals.size()) {
        case 0:
            principal = "";
            break;
        default:
            Log.debug("More than one principal found, using the first one.");
        // intended fall-through;
        case 1:
            principal = principals.get(0);
            break;
    }
    // Process requested user name.
    String username;
    if (response != null && response.length > 0) {
        username = new String(response, StandardCharsets.UTF_8);
    } else {
        username = null;
    }
    if (username == null || username.length() == 0) {
        // cause an authorization failure.
        for (String princ : principals) {
            final String mappedUsername = AuthorizationManager.map(princ);
            if (!mappedUsername.equals(princ)) {
                username = mappedUsername;
                principal = princ;
                break;
            }
        }
        if (username == null || username.length() == 0) {
            // Still no username.  Punt.
            username = principal;
        }
        Log.debug("No username requested, using: {}", username);
    }
    // Its possible that either/both username and principal are null here. The providers should not allow a null authorization
    if (AuthorizationManager.authorize(username, principal)) {
        Log.debug("Principal {} authorized to username {}", principal, username);
        authorizationID = username;
        // Success!
        return null;
    }
    throw new SaslException();
}
Also used : Connection(org.jivesoftware.openfire.Connection) ArrayList(java.util.ArrayList) SaslException(javax.security.sasl.SaslException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 42 with Certificate

use of java.security.cert.Certificate in project okhttp-OkGo by jeasonlzy.

the class HttpsUtils method prepareTrustManager.

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        // 创建一个默认类型的KeyStore,存储我们信任的证书
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certStream : certificates) {
            String certificateAlias = Integer.toString(index++);
            // 证书工厂根据证书文件的流生成证书 cert
            Certificate cert = certificateFactory.generateCertificate(certStream);
            // 将 cert 作为可信证书放入到keyStore中
            keyStore.setCertificateEntry(certificateAlias, cert);
            try {
                if (certStream != null)
                    certStream.close();
            } catch (IOException e) {
                OkLogger.e(e);
            }
        }
        //我们创建一个默认类型的TrustManagerFactory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书
        tmf.init(keyStore);
        //通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书
        return tmf.getTrustManagers();
    } catch (Exception e) {
        OkLogger.e(e);
    }
    return null;
}
Also used : InputStream(java.io.InputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 43 with Certificate

use of java.security.cert.Certificate in project neo4j by neo4j.

the class Certificates method loadCertificates.

public Certificate[] loadCertificates(File certFile) throws CertificateException, IOException {
    CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
    Collection<Certificate> certificates = new LinkedList<>();
    try (PemReader r = new PemReader(new FileReader(certFile))) {
        for (PemObject pemObject = r.readPemObject(); pemObject != null; pemObject = r.readPemObject()) {
            byte[] encodedCert = pemObject.getContent();
            certificates.addAll(certFactory.generateCertificates(new ByteArrayInputStream(encodedCert)));
        }
    }
    if (certificates.size() == 0) {
        // Ok, failed to read as PEM file, try and read it as raw binary certificate
        try (FileInputStream in = new FileInputStream(certFile)) {
            certificates = (Collection<Certificate>) certFactory.generateCertificates(in);
        }
    }
    return certificates.toArray(new Certificate[certificates.size()]);
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) ByteArrayInputStream(java.io.ByteArrayInputStream) FileReader(java.io.FileReader) CertificateFactory(java.security.cert.CertificateFactory) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 44 with Certificate

use of java.security.cert.Certificate in project neo4j by neo4j.

the class KeyStoreFactoryTest method shouldImportSingleCertificateWhenNotInAChain.

@Test
public void shouldImportSingleCertificateWhenNotInAChain() throws Exception {
    // given
    File certificatePath = new File(dir.getRoot(), "cert");
    File privateKeyPath = new File(dir.getRoot(), "key");
    new Certificates().createSelfSignedCertificate(certificatePath, privateKeyPath, "some-hostname");
    KeyStoreInformation keyStoreInformation = new KeyStoreFactory().createKeyStore(privateKeyPath, certificatePath);
    KeyStore keyStore = keyStoreInformation.getKeyStore();
    // when
    Certificate[] chain = keyStore.getCertificateChain("key");
    // then
    assertEquals("Single certificate expected not a chain of [" + chain.length + "]", 1, chain.length);
}
Also used : File(java.io.File) KeyStore(java.security.KeyStore) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 45 with Certificate

use of java.security.cert.Certificate in project neo4j by neo4j.

the class TestSslCertificateFactory method shouldLoadBinaryCertificates.

/**
     * For backwards-compatibility reasons, we support both PEM-encoded certificates *and* raw binary files containing
     * the certificate data.
     *
     * @throws Throwable
     */
@Test
public void shouldLoadBinaryCertificates() throws Throwable {
    // Given
    SelfSignedCertificate cert = new SelfSignedCertificate("example.com");
    Certificates certs = new Certificates();
    File cPath = tmpDir.newFile("certificate");
    byte[] raw = certs.loadCertificates(cert.certificate())[0].getEncoded();
    try (FileChannel ch = FileChannel.open(cPath.toPath(), WRITE)) {
        FileUtils.writeAll(ch, ByteBuffer.wrap(raw));
    }
    // When
    Certificate[] certificates = certs.loadCertificates(cPath);
    // Then
    assertThat(certificates.length, equalTo(1));
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FileChannel(java.nio.channels.FileChannel) File(java.io.File) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Aggregations

Certificate (java.security.cert.Certificate)723 X509Certificate (java.security.cert.X509Certificate)469 CertificateFactory (java.security.cert.CertificateFactory)272 ByteArrayInputStream (java.io.ByteArrayInputStream)237 KeyStore (java.security.KeyStore)133 PrivateKey (java.security.PrivateKey)132 IOException (java.io.IOException)106 CertificateException (java.security.cert.CertificateException)102 KeyFactory (java.security.KeyFactory)89 KeyStoreException (java.security.KeyStoreException)88 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)72 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)69 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)63 ArrayList (java.util.ArrayList)63 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)56 Entry (java.security.KeyStore.Entry)53 PublicKey (java.security.PublicKey)48 InputStream (java.io.InputStream)40 FileInputStream (java.io.FileInputStream)39 Key (java.security.Key)36