From 3e6e38b7a37a7088c3b851b24beaef4e8caa4dad Mon Sep 17 00:00:00 2001 From: Eric Chiang Date: Mon, 16 Aug 2021 11:20:30 -0700 Subject: [PATCH] add OBJ_get0_data() This allows encoding of an OBJECT IDENTIFIER, which uses complex base 128 encoding rules. https://luca.ntop.org/Teaching/Appunti/asn1.html Same as_slice() API as ASN1_STRING_get0_data(). Test data generated with the following Go program: https://play.golang.org/p/vA1PBcx1R4v --- openssl-sys/src/object.rs | 4 ++++ openssl/src/asn1.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/openssl-sys/src/object.rs b/openssl-sys/src/object.rs index fbc459bca..99abdebc9 100644 --- a/openssl-sys/src/object.rs +++ b/openssl-sys/src/object.rs @@ -18,4 +18,8 @@ extern "C" { -> c_int; pub fn OBJ_sn2nid(sn: *const libc::c_char) -> libc::c_int; pub fn OBJ_txt2obj(s: *const libc::c_char, no_name: libc::c_int) -> *mut ASN1_OBJECT; + #[cfg(ossl111)] + pub fn OBJ_length(obj: *const ASN1_OBJECT) -> libc::size_t; + #[cfg(ossl111)] + pub fn OBJ_get0_data(obj: *const ASN1_OBJECT) -> *const c_uchar; } diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 9c066c556..5d7fd0fd6 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -626,6 +626,22 @@ impl Asn1Object { Ok(Asn1Object::from_ptr(obj)) } } + + /// Return the OID as an DER encoded array of bytes. This is the ASN.1 + /// value, not including tag or length. + /// + /// This corresponds to [`OBJ_get0_data`]. + /// + /// Requires OpenSSL 1.1.1 or newer. + /// + /// [`OBJ_get0_data`]: https://www.openssl.org/docs/man1.1.0/man3/OBJ_get0_data.html + #[cfg(ossl111)] + pub fn as_slice(&self) -> &[u8] { + unsafe { + let len = ffi::OBJ_length(self.as_ptr()); + slice::from_raw_parts(ffi::OBJ_get0_data(self.as_ptr()), len) + } + } } impl Asn1ObjectRef { @@ -765,4 +781,14 @@ mod tests { .map(|object| object.to_string()) .expect_err("parsing invalid OID should fail"); } + + #[test] + #[cfg(ossl111)] + fn object_to_slice() { + let object = Asn1Object::from_str("2.16.840.1.101.3.4.2.1").unwrap(); + assert_eq!( + object.as_slice(), + &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01], + ); + } } -- GitLab