security_framework

Module secure_transport

Source
Expand description

SSL/TLS encryption support using Secure Transport.

§Examples

To connect as a client to a server with a certificate trusted by the system:

use std::io::prelude::*;
use std::net::TcpStream;
use security_framework::secure_transport::ClientBuilder;

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

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

To connect to a server with a certificate that’s not trusted by the system, specify the root certificates for the server’s chain to the ClientBuilder:

use std::io::prelude::*;
use std::net::TcpStream;
use security_framework::secure_transport::ClientBuilder;

let stream = TcpStream::connect("my_server.com:443").unwrap();
let mut stream = ClientBuilder::new()
                     .anchor_certificates(&[root_cert])
                     .handshake("my_server.com", stream)
                     .unwrap();

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

For more advanced configuration, the SslContext type can be used directly.

To run a server:

use std::net::TcpListener;
use std::thread;
use security_framework::secure_transport::{SslContext, SslProtocolSide, SslConnectionType};

// Create a TCP listener and start accepting on it.
let mut listener = TcpListener::bind("0.0.0.0:443").unwrap();

for stream in listener.incoming() {
    let stream = stream.unwrap();
    thread::spawn(move || {
        // Create a new context configured to operate on the server side of
        // a traditional SSL/TLS session.
        let mut ctx = SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)
                          .unwrap();

        // Install the certificate chain that we will be using.
        ctx.set_certificate(identity, &[intermediate_cert, root_cert]).unwrap();

        // Perform the SSL/TLS handshake and get our stream.
        let mut stream = ctx.handshake(stream).unwrap();
    });
}

Structs§

Enums§