Android SSL用法:从UI线程到后台线程的键输入流

时间:2013-06-14 08:33:01

标签: android ssl android-activity thread-safety

我对android SSL套接字使用有一个设计问题。为了能够初始化安全套接字,我需要能够从后台线程访问密钥输入流以初始化会话上下文。我使用另一个键输入流来初始化HttpsURLConnection,但我在UI线程中这样做(这可能是无关的。)我有几个后台线程在各个安全套接字上运行,我希望它们共享一个SslContextFactory。见下文。这是一个正确的设计吗? SSLContext是否是线程安全的?如果SSLContext不是线程安全的,我想知道如何为每个线程创建SSLContext而不返回(即,等待UI活动)到UI线程以获取新的键InputStream(原始资源上的流)对于每个线程。

class SslSessionContextFactory
{
    SSLContext sslContext;

    public SslSessionContextFactory(SslInfo info) throws Exception
    {
        KeyStore store = KeyStore.getInstance(info.getKeyStoreType());

        // Obtain the input stream for the key <--- this is the code in question.
        store.load(info.newKeyStream(), info.getPassphrase().toCharArray());

        TrustManagerFactory factory = TrustManagerFactory.getInstance(
                                          TrustManagerFactory.getDefaultAlgorithm());
        factory.init(store);

        // Initialize the SSL context.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, getCertificates(), new SecureRandom());
    }

    public SSLSessionContext getSessionContext()
    {
        // Initialize the session context.
        SSLSessionContext sessionContext = sslContext.getServerSessionContext();
        sessionContext.setSessionCacheSize(SESSION_CACHE_SIZE);
        sessionContext.setSessionTimeout(SESSION_TIMEOUT);
        return sessionContext;
    }
}

后台线程上的调用者会这样做:

SslSessionContextFactory cxtFactory = ...;
SocketFactory sktFactory = cxtFactory.getSessionContext().getSocketFactory();
... sktFactory.createSocket(host, port);

0 个答案:

没有答案