我正在尝试使用Android中的AWS连接密钥来使用MQTT websocket与设备进行连接,但尚未找到解决方案,请对此提供帮助。如果有人通过SSL / TLS通过3个证书AWS(ca,cert,private)android代码提供MQTT。
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(MainActivity.this, "ssl://" + pref.getMqttUrl(), clientId, persistence);
try {
String clientId = MqttClient.generateClientId();
MqttConnectOptions connectionOptions = new MqttConnectOptions();
connectionOptions.setCleanSession(true);
Log.e("Test", "ssl://" + pref.getMqttUrl());
try {
InputStream trustStoresIs = context.getResources().openRawResource(R.raw.ca_key);
String trustStoreType = KeyStore.getDefaultType();
KeyStore trustStore = KeyStore.getInstance(trustStoreType);
trustStore.load(trustStoresIs, context.getString(R.string.bks_password).toCharArray());
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(trustStore);
InputStream keyStoreStream = context.getResources().openRawResource(R.raw.user_cer_key);
KeyStore keyStore = null;
keyStore = KeyStore.getInstance("BKS");
keyStore.load(keyStoreStream, context.getString(R.string.bks_password).toCharArray());
KeyManagerFactory keyManagerFactory = null;
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, context.getString(R.string.bks_password).toCharArray());
SSLContext context = SSLContext.getInstance("SSL");
context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) context.getSocketFactory();
connectionOptions.setSocketFactory(sslsocketfactory);
} catch (KeyManagementException | CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mqttAndroidClient.connect(connectionOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.e("Mqtt","Connection Success!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e("Mqtt","Connection Failure!");
}
});
mqttAndroidClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
Log.e("Mqtt","Connection was lost!");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("mqtt Delivery Complete!");
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
出现错误
Mqttjavax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
谢谢。
答案 0 :(得分:1)
该错误表示您的信任库没有用于验证服务器身份的权限或完整证书链。
以下几行困扰我
InputStream trustStoresIs =
context.getResources().openRawResource(R.raw.ca_key);
这意味着您正在为CA链加载密钥而不是证书。另外,CA链往往具有不止一层的层次(主CA证书签署了中级CA证书),因此我希望您需要在信任存储中添加多个证书。