gpt4 book ai didi

android - 如何在 Smack 4.2 中使用证书

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:00 25 4
gpt4 key购买 nike

我正在尝试连接到 Blah.im XMPP 服务器,但它需要 SSL/TLS 证书才能连接。我正在使用下面的代码进行连接,但如何在此连接中使用证书?

 XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.
builder()
.setHost("jabber.blah.im")
.setPort(5222)
.setXmppDomain("blah.im")
.setUsernameAndPassword(username, password)
.setSendPresence(true)
.setSecurityMode(SecurityMode.required)
.setDebuggerEnabled(true)
.build();

XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
connection.login();

最佳答案

使用以下代码为连接配置 SSL/TLC 证书。

  try {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
.setDebuggerEnabled(XMPP_DEBUG_MODE)
.setXmppDomain(JidCreate.from(SERVICE_NAME).asDomainBareJid())
.setHost(SERVER_NAME)
.setPort(5222)
.setSendPresence(true)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

KeyStore keyStore = configKeyStore(builder);

configSSLContext(builder, keyStore);

config = builder.build();

} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | XmppStringprepException e) {
e.printStackTrace();
}

//配置 keystore

  private KeyStore configKeyStore(XMPPTCPConnectionConfiguration.Builder builder) throws KeyStoreException {
KeyStore keyStore;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
builder.setKeystorePath(null);
builder.setKeystoreType("AndroidCAStore");
keyStore = KeyStore.getInstance("AndroidCAStore");
} else {
builder.setKeystoreType("BKS");
keyStore = KeyStore.getInstance("BKS");

String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null)
path = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
builder.setKeystorePath(path);
}
return keyStore;
}

//配置ssl上下文

  private void configSSLContext(XMPPTCPConnectionConfiguration.Builder builder, KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

builder.setCustomSSLContext(sslContext);
}

关于android - 如何在 Smack 4.2 中使用证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com