Implement save_der for X509 and X509Req

This commit is contained in:
Onur Aslan 2016-07-29 12:11:53 +03:00
parent bdfa54cfdb
commit 5ed77df197
3 changed files with 38 additions and 0 deletions

View File

@ -841,6 +841,9 @@ extern "C" {
pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) -> c_int;
pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int;
pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int;
pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int;
pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *const *mut u8) -> c_int;
pub fn d2i_RSA_PUBKEY(k: *const *mut RSA, buf: *const *const u8, len: c_uint) -> *mut RSA;
pub fn i2d_RSAPrivateKey(k: *mut RSA, buf: *const *mut u8) -> c_int;

View File

@ -532,6 +532,17 @@ impl<'ctx> X509<'ctx> {
}
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
}
/// Returns a DER serialized form of the certificate
pub fn save_der(&self) -> Result<Vec<u8>, SslError> {
let mut mem_bio = try!(MemBio::new());
unsafe {
ffi::i2d_X509_bio(mem_bio.get_handle(), self.handle);
}
let mut v = Vec::new();
try!(io::copy(&mut mem_bio, &mut v).map_err(StreamError));
Ok(v)
}
}
extern "C" {
@ -637,6 +648,17 @@ impl X509Req {
}
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
}
/// Returns a DER serialized form of the CSR
pub fn save_der(&self) -> Result<Vec<u8>, SslError> {
let mut mem_bio = try!(MemBio::new());
unsafe {
ffi::i2d_X509_REQ_bio(mem_bio.get_handle(), self.handle);
}
let mut v = Vec::new();
try!(io::copy(&mut mem_bio, &mut v).map_err(StreamError));
Ok(v)
}
}
impl Drop for X509Req {

View File

@ -92,6 +92,19 @@ fn test_cert_loading() {
assert_eq!(fingerprint, hash_vec);
}
#[test]
fn test_save_der() {
let cert_path = Path::new("test/cert.pem");
let mut file = File::open(&cert_path)
.ok()
.expect("Failed to open `test/cert.pem`");
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
let der = cert.save_der().unwrap();
assert!(!der.is_empty());
}
#[test]
fn test_subject_read_cn() {
let cert_path = Path::new("test/cert.pem");