From 80e0dd03ba987293a874450dfbe1d2c53e974110 Mon Sep 17 00:00:00 2001 From: Brian Olsen Date: Thu, 10 Oct 2019 18:33:47 +0200 Subject: [PATCH] Add method to create Asn1Time from time_t value This is mostly just a rework of the earlier work done by @illegalprime in his PR #673 and credit should go to him. --- openssl-sys/src/asn1.rs | 1 + openssl/src/asn1.rs | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/openssl-sys/src/asn1.rs b/openssl-sys/src/asn1.rs index 593926335..2f2bf1b13 100644 --- a/openssl-sys/src/asn1.rs +++ b/openssl-sys/src/asn1.rs @@ -43,6 +43,7 @@ extern "C" { pub fn ASN1_TIME_diff(pday: *mut c_int, psec: *mut c_int, from: *const ASN1_TIME, to: *const ASN1_TIME) -> c_int; pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int; + pub fn ASN1_TIME_set(from: *mut ASN1_TIME, to: time_t) -> *mut ASN1_TIME; pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER); pub fn ASN1_INTEGER_get(dest: *const ASN1_INTEGER) -> c_long; diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 4e22511d9..6cd47f06d 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -26,7 +26,7 @@ //! ``` use ffi; use foreign_types::{ForeignType, ForeignTypeRef}; -use libc::{c_char, c_int, c_long}; +use libc::{c_char, c_int, c_long, time_t}; #[cfg(ossl102)] use std::cmp::Ordering; use std::ffi::CString; @@ -237,6 +237,16 @@ impl Asn1Time { Asn1Time::from_period(days as c_long * 60 * 60 * 24) } + /// Creates a new time from the specified `time_t` value + pub fn from_unix(time: time_t) -> Result { + ffi::init(); + + unsafe { + let handle = cvt_p(ffi::ASN1_TIME_set(ptr::null_mut(), time))?; + Ok(Asn1Time::from_ptr(handle)) + } + } + /// Creates a new time corresponding to the specified ASN1 time string. /// /// This corresponds to [`ASN1_TIME_set_string`]. @@ -542,6 +552,12 @@ mod tests { Asn1Time::from_str_x509("99991231235959Z").unwrap(); } + #[test] + fn time_from_unix() { + let t = Asn1Time::from_unix(0).unwrap(); + assert_eq!("Jan 1 00:00:00 1970 GMT", t.to_string()); + } + #[test] #[cfg(ossl102)] fn time_eq() { -- GitLab