Hi, I'm implementing the client side of a web socket connection with tokio-tungstenite
and I got it working with the native_tls
create but from what I read online a lot of people seem to migrate to rustls
. Therefore I wanted to give it a try but I couldn't get it to work.
This is the code for my web socket client using native_tls
use tokio_tungstenite::{Connector, connect_async_tls_with_config};
#[tokio::main]
async fn main() {
let cert_file = fs::read("certs/localhost.crt").unwrap();
let cert = native_tls::Certificate::from_pem(&cert_file).unwrap();
let tls_connector = native_tls::TlsConnector::builder()
.add_root_certificate(cert)
.build()
.unwrap();
let connector = Connector::NativeTls(tls_connector);
// Connect to the web socket
let url = Url::parse("wss://localhost:3000/ws").unwrap();
let (ws_stream, _) = connect_async_tls_with_config(
url, None, Some(connector)
).await.unwrap();
}
This works perfectly fine.
The following code is what I tried to get it working with rustls
:
use tokio_tungstenite::{Connector, connect_async_tls_with_config};
use rustls::{RootCertStore, ClientConfig};
#[tokio::main]
async fn main() {
let cert_file = fs::read("certs/localhost.crt.der").unwrap();
let rust_cert = rustls::Certificate(cert_file);
let mut root_cert_store = RootCertStore::empty();
root_cert_store.add(&rust_cert).unwrap();
let config = ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_cert_store)
.with_no_client_auth();
let connector = Connector::Rustls(Arc::new(config));
// Connect to the web socket
let url = Url::parse("wss://localhost:3000/ws").unwrap();
let (ws_stream, _) = connect_async_tls_with_config(
url, None, Some(connector)
).await.unwrap();
}
This gives me the following error:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Io(Custom { kind: InvalidData, error: InvalidCertificateData("invalid peer certificate: UnknownIssuer") })', src/main.rs:76:90
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
As it complains about the certificate data I think it might be an issue with converting the localhost.crt
PEM file to the DER format (which is needed to create rustls::Certificate
). I used this command for the conversion:
openssl x509 -in localhost.crt -outform der -out localhost.crt.der
Thank you very much for reading through all of this and in advance for your help. I appreciate any help or hint to guide me into the right direction