Module openssl::ssl

source ·
Expand description

SSL/TLS support.

SslConnector and SslAcceptor should be used in most cases - they handle configuration of the OpenSSL primitives for you.

§Examples

To connect as a client to a remote server:

use openssl::ssl::{SslMethod, SslConnector};
use std::io::{Read, Write};
use std::net::TcpStream;

let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();

let stream = TcpStream::connect("google.com:443").unwrap();
let mut stream = connector.connect("google.com", stream).unwrap();

stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
let mut res = vec![];
stream.read_to_end(&mut res).unwrap();
println!("{}", String::from_utf8_lossy(&res));

To accept connections as a server from remote clients:

use openssl::ssl::{SslMethod, SslAcceptor, SslStream, SslFiletype};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;


let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
acceptor.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
acceptor.set_certificate_chain_file("certs.pem").unwrap();
acceptor.check_private_key().unwrap();
let acceptor = Arc::new(acceptor.build());

let listener = TcpListener::bind("0.0.0.0:8443").unwrap();

fn handle_client(stream: SslStream<TcpStream>) {
    // ...
}

for stream in listener.incoming() {
    match stream {
        Ok(stream) => {
            let acceptor = acceptor.clone();
            thread::spawn(move || {
                let stream = acceptor.accept(stream).unwrap();
                handle_client(stream);
            });
        }
        Err(e) => { /* connection failed */ }
    }
}

Structs§

Enums§

Functions§

  • Returns the OpenSSL name of a cipher corresponding to an RFC-standard cipher name.
  • A standard implementation of protocol selection for Application Layer Protocol Negotiation (ALPN).