aboutsummaryrefslogtreecommitdiff
path: root/src/tls_util.rs
blob: a9e16c53d1fed7f0bd969bc4b556091d390c1a79 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use std::{fs, io};

use rustls::internal::pemfile;

use crate::error::Error;

pub fn load_certs(filename: &str) -> Result<Vec<rustls::Certificate>, Error> {
	let certfile = fs::File::open(&filename)?;
	let mut reader = io::BufReader::new(certfile);

	let certs = pemfile::certs(&mut reader).map_err(|_| {
		Error::Message(format!(
			"Could not deecode certificates from file: {}",
			filename
		))
	})?;

	if certs.is_empty() {
		return Err(Error::Message(format!(
			"Invalid certificate file: {}",
			filename
		)));
	}
	Ok(certs)
}

pub fn load_private_key(filename: &str) -> Result<rustls::PrivateKey, Error> {
	let keyfile = fs::File::open(&filename)?;
	let mut reader = io::BufReader::new(keyfile);

	let keys = pemfile::rsa_private_keys(&mut reader).map_err(|_| {
		Error::Message(format!(
			"Could not decode private key from file: {}",
			filename
		))
	})?;

	if keys.len() != 1 {
		return Err(Error::Message(format!(
			"Invalid private key file: {} ({} private keys)",
			filename,
			keys.len()
		)));
	}
	Ok(keys[0].clone())
}