README.md
1# rust-native-tls
2
3[![CircleCI](https://circleci.com/gh/sfackler/rust-native-tls.svg?style=shield)](https://circleci.com/gh/sfackler/rust-native-tls) [![Build Status](https://travis-ci.org/sfackler/rust-native-tls.svg?branch=master)](https://travis-ci.org/sfackler/rust-native-tls)
4
5[Documentation](https://docs.rs/native-tls)
6
7An abstraction over platform-specific TLS implementations.
8
9Specifically, this crate uses SChannel on Windows (via the [`schannel`] crate),
10Secure Transport on macOS (via the [`security-framework`] crate), and OpenSSL (via
11the [`openssl`] crate) on all other platforms.
12
13[`schannel`]: https://crates.io/crates/schannel
14[`security-framework`]: https://crates.io/crates/security-framework
15[`openssl`]: https://crates.io/crates/openssl
16
17## Installation
18
19```toml
20# Cargo.toml
21[dependencies]
22native-tls = "0.2"
23```
24
25## Usage
26
27An example client looks like:
28
29```rust
30extern crate native_tls;
31
32use native_tls::TlsConnector;
33use std::io::{Read, Write};
34use std::net::TcpStream;
35
36fn main() {
37 let connector = TlsConnector::new().unwrap();
38
39 let stream = TcpStream::connect("google.com:443").unwrap();
40 let mut stream = connector.connect("google.com", stream).unwrap();
41
42 stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
43 let mut res = vec![];
44 stream.read_to_end(&mut res).unwrap();
45 println!("{}", String::from_utf8_lossy(&res));
46}
47```
48
49To accept connections as a server from remote clients:
50
51```rust,no_run
52extern crate native_tls;
53
54use native_tls::{Identity, TlsAcceptor, TlsStream};
55use std::fs::File;
56use std::io::{Read};
57use std::net::{TcpListener, TcpStream};
58use std::sync::Arc;
59use std::thread;
60
61fn main() {
62 let mut file = File::open("identity.pfx").unwrap();
63 let mut identity = vec![];
64 file.read_to_end(&mut identity).unwrap();
65 let identity = Identity::from_pkcs12(&identity, "hunter2").unwrap();
66
67 let acceptor = TlsAcceptor::new(identity).unwrap();
68 let acceptor = Arc::new(acceptor);
69
70 let listener = TcpListener::bind("0.0.0.0:8443").unwrap();
71
72 fn handle_client(stream: TlsStream<TcpStream>) {
73 // ...
74 }
75
76 for stream in listener.incoming() {
77 match stream {
78 Ok(stream) => {
79 let acceptor = acceptor.clone();
80 thread::spawn(move || {
81 let stream = acceptor.accept(stream).unwrap();
82 handle_client(stream);
83 });
84 }
85 Err(e) => { /* connection failed */ }
86 }
87 }
88}
89```
90
91# License
92
93`rust-native-tls` is primarily distributed under the terms of both the MIT
94license and the Apache License (Version 2.0), with portions covered by various
95BSD-like licenses.
96
97See LICENSE-APACHE, and LICENSE-MIT for details.
98