Skip to content

Instantly share code, notes, and snippets.

@mottet-dev
Forked from choestelus/ping-pg-tls.rs
Created March 18, 2019 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mottet-dev/77df238ae04aa06b83bf74273b8b1896 to your computer and use it in GitHub Desktop.
Save mottet-dev/77df238ae04aa06b83bf74273b8b1896 to your computer and use it in GitHub Desktop.
rust-postgres with TLS connection
extern crate openssl;
extern crate postgres;
use postgres::{Connection, TlsMode};
use openssl::ssl::{SslConnectorBuilder, SslMethod, SslVerifyMode};
use openssl::x509;
fn main() {
let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap();
connector.set_ca_file("root.crt").unwrap();
connector
.set_certificate_file("postgresql.crt", x509::X509_FILETYPE_PEM)
.unwrap();
connector
.set_private_key_file("postgresql.key", x509::X509_FILETYPE_PEM)
.unwrap();
// openssl::ssl::SslVerfifyMode constant in not defined yet in openssl 0.9.23 which is rust-postgres dependency
// disable certificate hostname check
let mode = SslVerifyMode::empty();
connector.set_verify(mode);
let negotiator = postgres::tls::openssl::OpenSsl::from(connector.build());
let conn = Connection::connect(
"postgres://postgres@localhost:5432",
TlsMode::Require(&negotiator),
).unwrap();
let res = conn.query("SELECT 1+1 as foo", &[]).unwrap();
for row in &res {
let foo: i32 = row.get(0);
println!("{}", foo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment