aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSteven Fackler <[email protected]>2017-02-11 11:15:15 -0800
committerGitHub <[email protected]>2017-02-11 11:15:15 -0800
commit6d3fcedd665bb27f908e920e73e4a57847d23795 (patch)
tree8a59cbac9ad087a91b4785eb872de520818dd8bd
parentMerge pull request #568 from mredlek/x509_req_version_subject (diff)
parentFix for libressl (diff)
downloadrust-openssl-6d3fcedd665bb27f908e920e73e4a57847d23795.tar.xz
rust-openssl-6d3fcedd665bb27f908e920e73e4a57847d23795.zip
Merge pull request #515 from sfackler/x509-builder
Add X509 builders, deprecate X509Generator
-rw-r--r--openssl-sys/src/lib.rs40
-rw-r--r--openssl-sys/src/libressl.rs3
-rw-r--r--openssl-sys/src/ossl10x.rs3
-rw-r--r--openssl-sys/src/ossl110.rs3
-rw-r--r--openssl/Cargo.toml4
-rw-r--r--openssl/src/bn.rs9
-rw-r--r--openssl/src/conf.rs37
-rw-r--r--openssl/src/lib.rs1
-rw-r--r--openssl/src/pkcs12.rs33
-rw-r--r--openssl/src/ssl/mod.rs6
-rw-r--r--openssl/src/stack.rs34
-rw-r--r--openssl/src/x509/extension.rs422
-rw-r--r--openssl/src/x509/mod.rs506
-rw-r--r--openssl/src/x509/tests.rs108
14 files changed, 1005 insertions, 204 deletions
diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs
index 446101c2..3d90461b 100644
--- a/openssl-sys/src/lib.rs
+++ b/openssl-sys/src/lib.rs
@@ -33,6 +33,7 @@ pub enum ASN1_OBJECT {}
pub enum BN_CTX {}
pub enum BN_GENCB {}
pub enum CONF {}
+pub enum CONF_METHOD {}
pub enum COMP_METHOD {}
pub enum EC_KEY {}
pub enum EC_GROUP {}
@@ -1426,20 +1427,17 @@ extern {
pub fn BIO_set_flags(b: *mut BIO, flags: c_int);
pub fn BIO_clear_flags(b: *mut BIO, flags: c_int);
+ pub fn BN_CTX_new() -> *mut BN_CTX;
+ pub fn BN_CTX_free(ctx: *mut BN_CTX);
+
pub fn BN_new() -> *mut BIGNUM;
pub fn BN_dup(n: *const BIGNUM) -> *mut BIGNUM;
pub fn BN_clear(bn: *mut BIGNUM);
pub fn BN_free(bn: *mut BIGNUM);
pub fn BN_clear_free(bn: *mut BIGNUM);
-
- pub fn BN_CTX_new() -> *mut BN_CTX;
- pub fn BN_CTX_free(ctx: *mut BN_CTX);
-
pub fn BN_num_bits(bn: *const BIGNUM) -> c_int;
pub fn BN_set_negative(bn: *mut BIGNUM, n: c_int);
pub fn BN_set_word(bn: *mut BIGNUM, n: BN_ULONG) -> c_int;
-
- /* Arithmetic operations on BIGNUMs */
pub fn BN_add(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int;
pub fn BN_div(dv: *mut BIGNUM, rem: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int;
pub fn BN_exp(r: *mut BIGNUM, a: *const BIGNUM, p: *const BIGNUM, ctx: *mut BN_CTX) -> c_int;
@@ -1459,8 +1457,6 @@ extern {
pub fn BN_mod_word(r: *const BIGNUM, w: BN_ULONG) -> BN_ULONG;
pub fn BN_sqr(r: *mut BIGNUM, a: *const BIGNUM, ctx: *mut BN_CTX) -> c_int;
pub fn BN_sub(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int;
-
- /* Bit operations on BIGNUMs */
pub fn BN_clear_bit(a: *mut BIGNUM, n: c_int) -> c_int;
pub fn BN_is_bit_set(a: *const BIGNUM, n: c_int) -> c_int;
pub fn BN_lshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int;
@@ -1469,33 +1465,26 @@ extern {
pub fn BN_rshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int;
pub fn BN_set_bit(a: *mut BIGNUM, n: c_int) -> c_int;
pub fn BN_rshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int;
-
- /* Comparisons on BIGNUMs */
pub fn BN_cmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int;
pub fn BN_ucmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int;
-
- /* Prime handling */
pub fn BN_generate_prime_ex(r: *mut BIGNUM, bits: c_int, safe: c_int, add: *const BIGNUM, rem: *const BIGNUM, cb: *mut BN_GENCB) -> c_int;
pub fn BN_is_prime_ex(p: *const BIGNUM, checks: c_int, ctx: *mut BN_CTX, cb: *mut BN_GENCB) -> c_int;
pub fn BN_is_prime_fasttest_ex(p: *const BIGNUM, checks: c_int, ctx: *mut BN_CTX, do_trial_division: c_int, cb: *mut BN_GENCB) -> c_int;
-
- /* Random number handling */
pub fn BN_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int;
pub fn BN_pseudo_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int;
pub fn BN_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int;
pub fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int;
-
- /* Conversion from/to binary representation */
pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM;
pub fn BN_bn2bin(a: *const BIGNUM, to: *mut u8) -> c_int;
-
- /* Conversion from/to decimal string representation */
pub fn BN_dec2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int;
pub fn BN_bn2dec(a: *const BIGNUM) -> *mut c_char;
-
- /* Conversion from/to hexidecimal string representation */
pub fn BN_hex2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int;
pub fn BN_bn2hex(a: *const BIGNUM) -> *mut c_char;
+ pub fn BN_to_ASN1_INTEGER(bn: *const BIGNUM, ai: *mut ASN1_INTEGER) -> *mut ASN1_INTEGER;
+
+ pub fn NCONF_default() -> *mut CONF_METHOD;
+ pub fn NCONF_new(meth: *mut CONF_METHOD) -> *mut CONF;
+ pub fn NCONF_free(conf: *mut CONF);
pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void,
len: size_t) -> c_int;
@@ -1923,6 +1912,8 @@ extern {
pub fn X509_gmtime_adj(time: *mut ASN1_TIME, adj: c_long) -> *mut ASN1_TIME;
pub fn X509_new() -> *mut X509;
pub fn X509_set_issuer_name(x: *mut X509, name: *mut X509_NAME) -> c_int;
+ pub fn X509_set_subject_name(x: *mut X509, name: *mut X509_NAME) -> c_int;
+ pub fn X509_set_serialNumber(x: *mut X509, sn: *mut ASN1_INTEGER) -> c_int;
pub fn X509_set_version(x: *mut X509, version: c_long) -> c_int;
pub fn X509_set_pubkey(x: *mut X509, pkey: *mut EVP_PKEY) -> c_int;
pub fn X509_sign(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int;
@@ -1936,6 +1927,7 @@ extern {
pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION);
+ pub fn X509_NAME_new() -> *mut X509_NAME;
pub fn X509_NAME_free(x: *mut X509_NAME);
pub fn X509_NAME_add_entry_by_txt(x: *mut X509_NAME, field: *const c_char, ty: c_int, bytes: *const c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int;
pub fn X509_NAME_get_index_by_NID(n: *mut X509_NAME, nid: c_int, last_pos: c_int) -> c_int;
@@ -1959,12 +1951,14 @@ extern {
pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int;
pub fn X509V3_set_ctx(ctx: *mut X509V3_CTX, issuer: *mut X509, subject: *mut X509, req: *mut X509_REQ, crl: *mut X509_CRL, flags: c_int);
+ pub fn X509V3_set_nconf(ctx: *mut X509V3_CTX, conf: *mut CONF);
+ pub fn X509_REQ_new() -> *mut X509_REQ;
+ pub fn X509_REQ_set_version(req: *mut X509_REQ, version: c_long) -> c_int;
+ pub fn X509_REQ_set_subject_name(req: *mut X509_REQ, name: *mut X509_NAME) -> c_int;
+ pub fn X509_REQ_set_pubkey(req: *mut X509_REQ, pkey: *mut EVP_PKEY) -> c_int;
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 X509_REQ_set_version(x: *mut X509_REQ, version: c_long) -> c_int;
- pub fn X509_REQ_set_subject_name(req: *mut X509_REQ, name: *mut ::X509_NAME) -> c_int;
-
#[cfg(not(ossl101))]
pub fn X509_VERIFY_PARAM_free(param: *mut X509_VERIFY_PARAM);
diff --git a/openssl-sys/src/libressl.rs b/openssl-sys/src/libressl.rs
index 197d2c22..40490cd0 100644
--- a/openssl-sys/src/libressl.rs
+++ b/openssl-sys/src/libressl.rs
@@ -707,6 +707,7 @@ extern {
pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_get_ext_d2i(x: *mut ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void;
+ pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *mut c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int;
pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY;
pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING;
pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509;
@@ -723,9 +724,11 @@ extern {
pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX);
pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int;
+ pub fn sk_new_null() -> *mut _STACK;
pub fn sk_num(st: *const _STACK) -> c_int;
pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void;
pub fn sk_free(st: *mut _STACK);
+ pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int;
pub fn sk_pop_free(st: *mut _STACK, free: Option<unsafe extern "C" fn (*mut c_void)>);
pub fn sk_pop(st: *mut _STACK) -> *mut c_void;
diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs
index 12b70601..0ffe3850 100644
--- a/openssl-sys/src/ossl10x.rs
+++ b/openssl-sys/src/ossl10x.rs
@@ -856,6 +856,7 @@ extern {
pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_get_ext_d2i(x: *mut ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void;
+ pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *mut c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int;
#[cfg(not(ossl101))]
pub fn X509_get0_signature(psig: *mut *mut ::ASN1_BIT_STRING, palg: *mut *mut ::X509_ALGOR, x: *const ::X509);
#[cfg(not(ossl101))]
@@ -878,9 +879,11 @@ extern {
pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX);
pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int;
+ pub fn sk_new_null() -> *mut _STACK;
pub fn sk_num(st: *const _STACK) -> c_int;
pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void;
pub fn sk_free(st: *mut _STACK);
+ pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int;
pub fn sk_pop_free(st: *mut _STACK, free: Option<unsafe extern "C" fn (*mut c_void)>);
pub fn sk_pop(st: *mut _STACK) -> *mut c_void;
diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs
index 7ab10d4a..24ac47d2 100644
--- a/openssl-sys/src/ossl110.rs
+++ b/openssl-sys/src/ossl110.rs
@@ -86,6 +86,7 @@ extern {
pub fn X509_set1_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_set1_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int;
pub fn X509_get_ext_d2i(x: *const ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void;
+ pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *const c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int;
pub fn X509_get_signature_nid(x: *const X509) -> c_int;
pub fn X509_ALGOR_get0(paobj: *mut *const ::ASN1_OBJECT, pptype: *mut c_int, ppval: *mut *const c_void, alg: *const ::X509_ALGOR);
pub fn X509_NAME_get_entry(n: *const ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY;
@@ -182,8 +183,10 @@ extern {
pub fn OpenSSL_version_num() -> c_ulong;
pub fn OpenSSL_version(key: c_int) -> *const c_char;
+ pub fn OPENSSL_sk_new_null() -> *mut ::OPENSSL_STACK;
pub fn OPENSSL_sk_free(st: *mut ::OPENSSL_STACK);
pub fn OPENSSL_sk_pop_free(st: *mut ::OPENSSL_STACK, free: Option<unsafe extern "C" fn (*mut c_void)>);
+ pub fn OPENSSL_sk_push(st: *mut ::OPENSSL_STACK, data: *const c_void) -> c_int;
pub fn OPENSSL_sk_pop(st: *mut ::OPENSSL_STACK) -> *mut c_void;
pub fn PKCS12_create(pass: *const c_char,
diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml
index 5d9aab92..34d8e3db 100644
--- a/openssl/Cargo.toml
+++ b/openssl/Cargo.toml
@@ -19,7 +19,7 @@ v110 = []
[dependencies]
bitflags = "0.7"
-foreign-types = "0.1"
+foreign-types = "0.2"
lazy_static = "0.2"
libc = "0.2"
openssl-sys = { version = "0.9.6", path = "../openssl-sys" }
@@ -28,4 +28,4 @@ openssl-sys = { version = "0.9.6", path = "../openssl-sys" }
tempdir = "0.3"
winapi = "0.2"
ws2_32-sys = "0.2"
-hex = "0.2"
+hex = "0.2" \ No newline at end of file
diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs
index 7d288eee..9557b5bb 100644
--- a/openssl/src/bn.rs
+++ b/openssl/src/bn.rs
@@ -7,6 +7,7 @@ use std::{fmt, ptr};
use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref};
use {cvt, cvt_p, cvt_n};
+use asn1::Asn1Integer;
use error::ErrorStack;
use string::OpensslString;
@@ -513,6 +514,14 @@ impl BigNumRef {
Ok(OpensslString::from_ptr(buf))
}
}
+
+ /// Returns an `Asn1Integer` containing the value of `self`.
+ pub fn to_asn1_integer(&self) -> Result<Asn1Integer, ErrorStack> {
+ unsafe {
+ cvt_p(ffi::BN_to_ASN1_INTEGER(self.as_ptr(), ptr::null_mut()))
+ .map(|p| Asn1Integer::from_ptr(p))
+ }
+ }
}
foreign_type! {
diff --git a/openssl/src/conf.rs b/openssl/src/conf.rs
new file mode 100644
index 00000000..a648bb15
--- /dev/null
+++ b/openssl/src/conf.rs
@@ -0,0 +1,37 @@
+use ffi;
+
+use cvt_p;
+use error::ErrorStack;
+
+pub struct ConfMethod(*mut ffi::CONF_METHOD);
+
+impl ConfMethod {
+ pub fn default() -> ConfMethod {
+ unsafe {
+ ffi::init();
+ ConfMethod(ffi::NCONF_default())
+ }
+ }
+
+ pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod {
+ ConfMethod(ptr)
+ }
+
+ pub fn as_ptr(&self) -> *mut ffi::CONF_METHOD {
+ self.0
+ }
+}
+
+foreign_type! {
+ type CType = ffi::CONF;
+ fn drop = ffi::NCONF_free;
+
+ pub struct Conf;
+ pub struct ConfRef;
+}
+
+impl Conf {
+ pub fn new(method: ConfMethod) -> Result<Conf, ErrorStack> {
+ unsafe { cvt_p(ffi::NCONF_new(method.as_ptr())).map(Conf) }
+ }
+}
diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs
index 507af1d4..86de35d0 100644
--- a/openssl/src/lib.rs
+++ b/openssl/src/lib.rs
@@ -29,6 +29,7 @@ mod util;
pub mod aes;
pub mod asn1;
pub mod bn;
+pub mod conf;
pub mod crypto;
pub mod dh;
pub mod dsa;
diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs
index 1e23668e..9f014af6 100644
--- a/openssl/src/pkcs12.rs
+++ b/openssl/src/pkcs12.rs
@@ -173,10 +173,12 @@ mod test {
use hash::MessageDigest;
use hex::ToHex;
- use ::rsa::Rsa;
- use ::pkey::*;
- use ::x509::*;
- use ::x509::extension::*;
+ use asn1::Asn1Time;
+ use rsa::Rsa;
+ use pkey::PKey;
+ use nid;
+ use x509::{X509, X509Name};
+ use x509::extension::KeyUsage;
use super::*;
@@ -200,13 +202,22 @@ mod test {
let rsa = Rsa::generate(2048).unwrap();
let pkey = PKey::from_rsa(rsa).unwrap();
- let gen = X509Generator::new()
- .set_valid_period(365*2)
- .add_name("CN".to_owned(), subject_name.to_string())
- .set_sign_hash(MessageDigest::sha256())
- .add_extension(Extension::KeyUsage(vec![KeyUsageOption::DigitalSignature]));
-
- let cert = gen.sign(&pkey).unwrap();
+ let mut name = X509Name::builder().unwrap();
+ name.append_entry_by_nid(nid::COMMONNAME, subject_name).unwrap();
+ let name = name.build();
+
+ let key_usage = KeyUsage::new().digital_signature().build().unwrap();;
+
+ let mut builder = X509::builder().unwrap();
+ builder.set_version(2).unwrap();
+ builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
+ builder.set_not_after(&Asn1Time::days_from_now(365).unwrap()).unwrap();
+ builder.set_subject_name(&name).unwrap();
+ builder.set_issuer_name(&name).unwrap();
+ builder.append_extension(key_usage).unwrap();
+ builder.set_pubkey(&pkey).unwrap();
+ builder.sign(&pkey, MessageDigest::sha256()).unwrap();
+ let cert = builder.build();
let pkcs12_builder = Pkcs12::builder();
let pkcs12 = pkcs12_builder.build("mypass", subject_name, &pkey, &cert).unwrap();
diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs
index 860e2e00..5a65aa77 100644
--- a/openssl/src/ssl/mod.rs
+++ b/openssl/src/ssl/mod.rs
@@ -1061,9 +1061,15 @@ impl ForeignType for SslCipher {
type CType = ffi::SSL_CIPHER;
type Ref = SslCipherRef;
+ #[inline]
unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher {
SslCipher(ptr)
}
+
+ #[inline]
+ fn as_ptr(&self) -> *mut ffi::SSL_CIPHER {
+ self.0
+ }
}
impl Deref for SslCipher {
diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs
index 372040aa..268afde7 100644
--- a/openssl/src/stack.rs
+++ b/openssl/src/stack.rs
@@ -5,15 +5,21 @@ use std::convert::AsRef;
use std::iter;
use std::marker::PhantomData;
use std::mem;
+use ffi;
+
+use {cvt, cvt_p};
+use error::ErrorStack;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use util::Opaque;
#[cfg(ossl10x)]
use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free, sk_num as OPENSSL_sk_num,
- sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK};
+ sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK,
+ sk_new_null as OPENSSL_sk_new_null, sk_push as OPENSSL_sk_push};
#[cfg(ossl110)]
-use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK};
+use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK,
+ OPENSSL_sk_new_null, OPENSSL_sk_push};
/// Trait implemented by types which can be placed in a stack.
///
@@ -30,9 +36,12 @@ pub trait Stackable: ForeignType {
pub struct Stack<T: Stackable>(*mut T::StackType);
impl<T: Stackable> Stack<T> {
- /// Return a new Stack<T>, taking ownership of the handle
- pub unsafe fn from_ptr(stack: *mut T::StackType) -> Stack<T> {
- Stack(stack)
+ pub fn new() -> Result<Stack<T>, ErrorStack> {
+ unsafe {
+ ffi::init();
+ let ptr = try!(cvt_p(OPENSSL_sk_new_null()));
+ Ok(Stack(ptr as *mut _))
+ }
}
}
@@ -75,9 +84,15 @@ impl<T: Stackable> ForeignType for Stack<T> {
type CType = T::StackType;
type Ref = StackRef<T>;
+ #[inline]
unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack<T> {
Stack(ptr)
}
+
+ #[inline]
+ fn as_ptr(&self) -> *mut T::StackType {
+ self.0
+ }
}
impl<T: Stackable> Deref for Stack<T> {
@@ -197,6 +212,15 @@ impl<T: Stackable> StackRef<T> {
}
}
+ /// Pushes a value onto the top of the stack.
+ pub fn push(&mut self, data: T) -> Result<(), ErrorStack> {
+ unsafe {
+ try!(cvt(OPENSSL_sk_push(self.as_stack(), data.as_ptr() as *mut _)));
+ mem::forget(data);
+ Ok(())
+ }
+ }
+
/// Removes the last element from the stack and returns it.
pub fn pop(&mut self) -> Option<T> {
unsafe {
diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs
index 398bbb3e..c9f60a92 100644
--- a/openssl/src/x509/extension.rs
+++ b/openssl/src/x509/extension.rs
@@ -1,12 +1,15 @@
-use std::fmt;
+use std::fmt::{self, Write};
+use error::ErrorStack;
use nid::{self, Nid};
+use x509::{X509v3Context, X509Extension};
/// Type-only version of the `Extension` enum.
///
/// See the `Extension` documentation for more information on the different
/// variants.
#[derive(Clone,Hash,PartialEq,Eq)]
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub enum ExtensionType {
KeyUsage,
ExtKeyUsage,
@@ -21,6 +24,7 @@ pub enum ExtensionType {
/// Only one extension of each type is allow in a certificate.
/// See RFC 3280 for more information about extensions.
#[derive(Clone)]
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub enum Extension {
/// The purposes of the key contained in the certificate
KeyUsage(Vec<KeyUsageOption>),
@@ -56,6 +60,7 @@ pub enum Extension {
}
impl Extension {
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn get_type(&self) -> ExtensionType {
match self {
&Extension::KeyUsage(_) => ExtensionType::KeyUsage,
@@ -69,6 +74,7 @@ impl Extension {
}
impl ExtensionType {
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn get_nid(&self) -> Option<Nid> {
match self {
&ExtensionType::KeyUsage => Some(nid::KEY_USAGE),
@@ -80,6 +86,7 @@ impl ExtensionType {
}
}
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn get_name(&self) -> Option<&str> {
match self {
&ExtensionType::OtherStr(ref s) => Some(s),
@@ -120,6 +127,7 @@ impl ToString for Extension {
}
#[derive(Clone,Copy)]
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub enum KeyUsageOption {
DigitalSignature,
NonRepudiation,
@@ -149,6 +157,7 @@ impl fmt::Display for KeyUsageOption {
}
#[derive(Clone)]
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub enum ExtKeyUsageOption {
ServerAuth,
ClientAuth,
@@ -185,6 +194,7 @@ impl fmt::Display for ExtKeyUsageOption {
}
#[derive(Clone, Copy)]
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub enum AltNameOption {
/// The value is specified as OID;content. See `man ASN1_generate_nconf` for more information on the content syntax.
///
@@ -219,3 +229,413 @@ impl fmt::Display for AltNameOption {
})
}
}
+
+pub struct BasicConstraints {
+ critical: bool,
+ ca: bool,
+ pathlen: Option<u32>,
+}
+
+impl BasicConstraints {
+ pub fn new() -> BasicConstraints {
+ BasicConstraints {
+ critical: false,
+ ca: false,
+ pathlen: None,
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut BasicConstraints {
+ self.critical = true;
+ self
+ }
+
+ pub fn ca(&mut self) -> &mut BasicConstraints {
+ self.ca = true;
+ self
+ }
+
+ pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints {
+ self.pathlen = Some(pathlen);
+ self
+ }
+
+ pub fn build(&self) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ if self.critical {
+ value.push_str("critical,");
+ }
+ value.push_str("CA:");
+ if self.ca {
+ value.push_str("TRUE");
+ } else {
+ value.push_str("FALSE");
+ }
+ if let Some(pathlen) = self.pathlen {
+ write!(value, ",pathlen:{}", pathlen).unwrap();
+ }
+ X509Extension::new_nid(None, None, nid::BASIC_CONSTRAINTS, &value)
+ }
+}
+
+pub struct KeyUsage {
+ critical: bool,
+ digital_signature: bool,
+ non_repudiation: bool,
+ key_encipherment: bool,
+ data_encipherment: bool,
+ key_agreement: bool,
+ key_cert_sign: bool,
+ crl_sign: bool,
+ encipher_only: bool,
+ decipher_only: bool,
+}
+
+impl KeyUsage {
+ pub fn new() -> KeyUsage {
+ KeyUsage {
+ critical: false,
+ digital_signature: false,
+ non_repudiation: false,
+ key_encipherment: false,
+ data_encipherment: false,
+ key_agreement: false,
+ key_cert_sign: false,
+ crl_sign: false,
+ encipher_only: false,
+ decipher_only: false,
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut KeyUsage {
+ self.critical = true;
+ self
+ }
+
+ pub fn digital_signature(&mut self) -> &mut KeyUsage {
+ self.digital_signature = true;
+ self
+ }
+
+ pub fn non_repudiation(&mut self) -> &mut KeyUsage {
+ self.non_repudiation = true;
+ self
+ }
+
+ pub fn key_encipherment(&mut self) -> &mut KeyUsage {
+ self.key_encipherment = true;
+ self
+ }
+
+ pub fn data_encipherment(&mut self) -> &mut KeyUsage {
+ self.data_encipherment = true;
+ self
+ }
+
+ pub fn key_agreement(&mut self) -> &mut KeyUsage {
+ self.key_agreement = true;
+ self
+ }
+
+ pub fn key_cert_sign(&mut self) -> &mut KeyUsage {
+ self.key_cert_sign = true;
+ self
+ }
+
+ pub fn crl_sign(&mut self) -> &mut KeyUsage {
+ self.crl_sign = true;
+ self
+ }
+
+ pub fn encipher_only(&mut self) -> &mut KeyUsage {
+ self.encipher_only = true;
+ self
+ }
+
+ pub fn decipher_only(&mut self) -> &mut KeyUsage {
+ self.decipher_only = true;
+ self
+ }
+
+ pub fn build(&self) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ let mut first = true;
+ append(&mut value, &mut first, self.critical, "critical");
+ append(&mut value, &mut first, self.digital_signature, "digitalSignature");
+ append(&mut value, &mut first, self.non_repudiation, "nonRepudiation");
+ append(&mut value, &mut first, self.key_encipherment, "keyEncipherment");
+ append(&mut value, &mut first, self.data_encipherment, "dataEncipherment");
+ append(&mut value, &mut first, self.key_agreement, "keyAgreement");
+ append(&mut value, &mut first, self.key_cert_sign, "keyCertSign");
+ append(&mut value, &mut first, self.crl_sign, "cRLSign");
+ append(&mut value, &mut first, self.encipher_only, "encipherOnly");
+ append(&mut value, &mut first, self.decipher_only, "decipherOnly");
+ X509Extension::new_nid(None, None, nid::KEY_USAGE, &value)
+ }
+}
+
+pub struct ExtendedKeyUsage {
+ critical: bool,
+ server_auth: bool,
+ client_auth: bool,
+ code_signing: bool,
+ email_protection: bool,
+ time_stamping: bool,
+ ms_code_ind: bool,
+ ms_code_com: bool,
+ ms_ctl_sign: bool,
+ ms_sgc: bool,
+ ms_efs: bool,
+ ns_sgc: bool,
+ other: Vec<String>,
+}
+
+impl ExtendedKeyUsage {
+ pub fn new() -> ExtendedKeyUsage {
+ ExtendedKeyUsage {
+ critical: false,
+ server_auth: false,
+ client_auth: false,
+ code_signing: false,
+ email_protection: false,
+ time_stamping: false,
+ ms_code_ind: false,
+ ms_code_com: false,
+ ms_ctl_sign: false,
+ ms_sgc: false,
+ ms_efs: false,
+ ns_sgc: false,
+ other: vec![],
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut ExtendedKeyUsage {
+ self.critical = true;
+ self
+ }
+
+ pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage {
+ self.server_auth = true;
+ self
+ }
+
+ pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage {
+ self.client_auth = true;
+ self
+ }
+
+ pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage {
+ self.code_signing = true;
+ self
+ }
+
+ pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage {
+ self.time_stamping = true;
+ self
+ }
+
+ pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage {
+ self.ms_code_ind = true;
+ self
+ }
+
+ pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage {
+ self.ms_code_com = true;
+ self
+ }
+
+ pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage {
+ self.ms_ctl_sign = true;
+ self
+ }
+
+ pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage {
+ self.ms_sgc = true;
+ self
+ }
+
+ pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage {
+ self.ms_efs = true;
+ self
+ }
+
+ pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage {
+ self.ns_sgc = true;
+ self
+ }
+
+ pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage {
+ self.other.push(other.to_owned());
+ self
+ }
+
+ pub fn build(&self) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ let mut first = true;
+ append(&mut value, &mut first, self.critical, "critical");
+ append(&mut value, &mut first, self.server_auth, "serverAuth");
+ append(&mut value, &mut first, self.client_auth, "clientAuth");
+ append(&mut value, &mut first, self.code_signing, "codeSigning");
+ append(&mut value, &mut first, self.email_protection, "emailProtection");
+ append(&mut value, &mut first, self.time_stamping, "timeStamping");
+ append(&mut value, &mut first, self.ms_code_ind, "msCodeInd");
+ append(&mut value, &mut first, self.ms_code_com, "msCodeCom");
+ append(&mut value, &mut first, self.ms_ctl_sign, "msCTLSign");
+ append(&mut value, &mut first, self.ms_sgc, "msSGC");
+ append(&mut value, &mut first, self.ms_efs, "msEFS");
+ append(&mut value, &mut first, self.ns_sgc, "nsSGC");
+ for other in &self.other {
+ append(&mut value, &mut first, true, other);
+ }
+ X509Extension::new_nid(None, None, nid::EXT_KEY_USAGE, &value)
+ }
+}
+
+pub struct SubjectKeyIdentifier {
+ critical: bool,
+}
+
+impl SubjectKeyIdentifier {
+ pub fn new() -> SubjectKeyIdentifier {
+ SubjectKeyIdentifier {
+ critical: false,
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut SubjectKeyIdentifier {
+ self.critical = true;
+ self
+ }
+
+ pub fn build(&self, ctx: &X509v3Context) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ let mut first = true;
+ append(&mut value, &mut first, self.critical, "critical");
+ append(&mut value, &mut first, true, "hash");
+ X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_KEY_IDENTIFIER, &value)
+ }
+}
+
+pub struct AuthorityKeyIdentifier {
+ critical: bool,
+ keyid: Option<bool>,
+ issuer: Option<bool>,
+}
+
+impl AuthorityKeyIdentifier {
+ pub fn new() -> AuthorityKeyIdentifier {
+ AuthorityKeyIdentifier {
+ critical: false,
+ keyid: None,
+ issuer: None,
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier {
+ self.critical = true;
+ self
+ }
+
+ pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
+ self.keyid = Some(always);
+ self
+ }
+
+ pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
+ self.issuer = Some(always);
+ self
+ }
+
+ pub fn build(&self, ctx: &X509v3Context) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ let mut first = true;
+ append(&mut value, &mut first, self.critical, "critical");
+ match self.keyid {
+ Some(true) => append(&mut value, &mut first, true, "keyid:always"),
+ Some(false) => append(&mut value, &mut first, true, "keyid"),
+ None => {}
+ }
+ match self.issuer {
+ Some(true) => append(&mut value, &mut first, true, "issuer:always"),
+ Some(false) => append(&mut value, &mut first, true, "issuer"),
+ None => {}
+ }
+ X509Extension::new_nid(None, Some(ctx), nid::AUTHORITY_KEY_IDENTIFIER, &value)
+ }
+}
+
+pub struct SubjectAlternativeName {
+ critical: bool,
+ names: Vec<String>,
+}
+
+impl SubjectAlternativeName {
+ pub fn new() -> SubjectAlternativeName {
+ SubjectAlternativeName {
+ critical: false,
+ names: vec![],
+ }
+ }
+
+ pub fn critical(&mut self) -> &mut SubjectAlternativeName {
+ self.critical = true;
+ self
+ }
+
+ pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("email:{}", email));
+ self
+ }
+
+ pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("URI:{}", uri));
+ self
+ }
+
+ pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("DNS:{}", dns));
+ self
+ }
+
+ pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("RID:{}", rid));
+ self
+ }
+
+ pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("IP:{}", ip));
+ self
+ }
+
+ pub fn dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("dirName:{}", dir_name));
+ self
+ }
+
+ pub fn other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName {
+ self.names.push(format!("otherName:{}", other_name));
+ self
+ }
+
+ pub fn build(&self, ctx: &X509v3Context) -> Result<X509Extension, ErrorStack> {
+ let mut value = String::new();
+ let mut first = true;
+ append(&mut value, &mut first, self.critical, "critical");
+ for name in &self.names {
+ append(&mut value, &mut first, true, name);
+ }
+ X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_ALT_NAME, &value)
+ }
+}
+
+fn append(value: &mut String, first: &mut bool, should: bool, element: &str) {
+ if !should {
+ return;
+ }
+
+ if !*first {
+ value.push(',');
+ }
+ *first = false;
+ value.push_str(element);
+}
diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs
index 0d329da4..4df05ad0 100644
--- a/openssl/src/x509/mod.rs
+++ b/openssl/src/x509/mod.rs
@@ -1,11 +1,13 @@
+#![allow(deprecated)]
+use libc::{c_int, c_long};
use ffi;
use foreign_types::{ForeignType, ForeignTypeRef};
-use libc::{c_char, c_int, c_long, c_ulong};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt;
+use std::marker::PhantomData;
use std::mem;
use std::path::Path;
use std::ptr;
@@ -13,15 +15,16 @@ use std::slice;
use std::str;
use {cvt, cvt_p};
-use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1BitStringRef, Asn1ObjectRef};
+use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1BitStringRef, Asn1IntegerRef, Asn1ObjectRef};
use bio::MemBioSlice;
+use bn::{BigNum, MSB_MAYBE_ZERO};
+use conf::ConfRef;
+use error::ErrorStack;
use hash::MessageDigest;
+use nid::{self, Nid};
use pkey::{PKey, PKeyRef};
-use rand::rand_bytes;
-use error::ErrorStack;
-use nid::Nid;
-use string::OpensslString;
use stack::{Stack, StackRef, Stackable};
+use string::OpensslString;
#[cfg(ossl10x)]
use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data, X509_STORE_CTX_get_chain};
@@ -94,31 +97,7 @@ impl X509StoreContextRef {
}
}
-#[allow(non_snake_case)]
-/// Generator of private key/certificate pairs
-///
-/// # Example
-///
-/// ```
-/// use openssl::hash::MessageDigest;
-/// use openssl::pkey::PKey;
-/// use openssl::rsa::Rsa;
-/// use openssl::x509::X509Generator;
-/// use openssl::x509::extension::{Extension, KeyUsageOption};
-///
-/// let rsa = Rsa::generate(2048).unwrap();
-/// let pkey = PKey::from_rsa(rsa).unwrap();
-///
-/// let gen = X509Generator::new()
-/// .set_valid_period(365*2)
-/// .add_name("CN".to_owned(), "SuperMegaCorp Inc.".to_owned())
-/// .set_sign_hash(MessageDigest::sha256())
-/// .add_extension(Extension::KeyUsage(vec![KeyUsageOption::DigitalSignature]));
-///
-/// let cert = gen.sign(&pkey).unwrap();
-/// let cert_pem = cert.to_pem().unwrap();
-/// let pkey_pem = pkey.private_key_to_pem().unwrap();
-/// ```
+#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub struct X509Generator {
days: u32,
names: Vec<(String, String)>,
@@ -126,6 +105,7 @@ pub struct X509Generator {
hash_type: MessageDigest,
}
+#[allow(deprecated)]
impl X509Generator {
/// Creates a new generator with the following defaults:
///
@@ -134,6 +114,7 @@ impl X509Generator {
/// CN: "rust-openssl"
///
/// hash: SHA1
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn new() -> X509Generator {
X509Generator {
days: 365,
@@ -144,6 +125,7 @@ impl X509Generator {
}
/// Sets certificate validity period in days since today
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn set_valid_period(mut self, days: u32) -> X509Generator {
self.days = days;
self
@@ -155,6 +137,7 @@ impl X509Generator {
/// # let generator = openssl::x509::X509Generator::new();
/// generator.add_name("CN".to_string(),"example.com".to_string());
/// ```
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator {
self.names.push((attr_type, attr_value));
self
@@ -166,6 +149,7 @@ impl X509Generator {
/// # let generator = openssl::x509::X509Generator::new();
/// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]);
/// ```
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn add_names<I>(mut self, attrs: I) -> X509Generator
where I: IntoIterator<Item = (String, String)>
{
@@ -184,6 +168,7 @@ impl X509Generator {
/// # let generator = openssl::x509::X509Generator::new();
/// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]));
/// ```
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator {
self.extensions.add(ext);
self
@@ -200,6 +185,7 @@ impl X509Generator {
/// # let generator = openssl::x509::X509Generator::new();
/// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]);
/// ```
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn add_extensions<I>(mut self, exts: I) -> X509Generator
where I: IntoIterator<Item = extension::Extension>
{
@@ -210,131 +196,66 @@ impl X509Generator {
self
}
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn set_sign_hash(mut self, hash_type: MessageDigest) -> X509Generator {
self.hash_type = hash_type;
self
}
- fn add_extension_internal(x509: *mut ffi::X509,
- exttype: &extension::ExtensionType,
- value: &str)
- -> Result<(), ErrorStack> {
- unsafe {
- let mut ctx: ffi::X509V3_CTX = mem::zeroed();
- ffi::X509V3_set_ctx(&mut ctx, x509, x509, ptr::null_mut(), ptr::null_mut(), 0);
- let value = CString::new(value.as_bytes()).unwrap();
- let ext = match exttype.get_nid() {
- Some(nid) => {
- try!(cvt_p(ffi::X509V3_EXT_nconf_nid(ptr::null_mut(),
- &mut ctx,
- nid.as_raw(),
- value.as_ptr() as *mut c_char)))
- }
- None => {
- let name = CString::new(exttype.get_name().unwrap().as_bytes()).unwrap();
- try!(cvt_p(ffi::X509V3_EXT_nconf(ptr::null_mut(),
- &mut ctx,
- name.as_ptr() as *mut c_char,
- value.as_ptr() as *mut c_char)))
- }
- };
- if ffi::X509_add_ext(x509, ext, -1) != 1 {
- ffi::X509_EXTENSION_free(ext);
- Err(ErrorStack::get())
- } else {
- Ok(())
- }
- }
- }
-
- fn add_name_internal(name: *mut ffi::X509_NAME,
- key: &str,
- value: &str)
- -> Result<(), ErrorStack> {
- let value_len = value.len() as c_int;
- unsafe {
- let key = CString::new(key.as_bytes()).unwrap();
- let value = CString::new(value.as_bytes()).unwrap();
- cvt(ffi::X509_NAME_add_entry_by_txt(name,
- key.as_ptr() as *const _,
- ffi::MBSTRING_UTF8,
- value.as_ptr() as *const _,
- value_len,
- -1,
- 0))
- .map(|_| ())
- }
- }
-
- fn random_serial() -> Result<c_long, ErrorStack> {
- let len = mem::size_of::<c_long>();
- let mut bytes = vec![0; len];
- try!(rand_bytes(&mut bytes));
- let mut res = 0;
- for b in bytes.iter() {
- res = res << 8;
- res |= (*b as c_long) & 0xff;
- }
-
- // While OpenSSL is actually OK to have negative serials
- // other libraries (for example, Go crypto) can drop
- // such certificates as invalid, so we clear the high bit
- Ok(((res as c_ulong) >> 1) as c_long)
- }
-
/// Sets the certificate public-key, then self-sign and return it
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn sign(&self, p_key: &PKeyRef) -> Result<X509, ErrorStack> {
- ffi::init();
-
- unsafe {
- let x509 = X509::from_ptr(try!(cvt_p(ffi::X509_new())));
-
- try!(cvt(ffi::X509_set_version(x509.as_ptr(), 2)));
- try!(cvt(ffi::ASN1_INTEGER_set(ffi::X509_get_serialNumber(x509.as_ptr()),
- try!(X509Generator::random_serial()))));
-
- let not_before = try!(Asn1Time::days_from_now(0));
- let not_after = try!(Asn1Time::days_from_now(self.days));
+ let mut builder = try!(X509::builder());
+ try!(builder.set_version(2));
- try!(cvt(X509_set_notBefore(x509.as_ptr(), not_before.as_ptr() as *const _)));
- // If prev line succeded - ownership should go to cert
- mem::forget(not_before);
+ let mut serial = try!(BigNum::new());
+ try!(serial.rand(128, MSB_MAYBE_ZERO, false));
+ let serial = try!(serial.to_asn1_integer());
+ try!(builder.set_serial_number(&serial));
- try!(cvt(X509_set_notAfter(x509.as_ptr(), not_after.as_ptr() as *const _)));
- // If prev line succeded - ownership should go to cert
- mem::forget(not_after);
+ let not_before = try!(Asn1Time::days_from_now(0));
+ try!(builder.set_not_before(&not_before));
+ let not_after = try!(Asn1Time::days_from_now(self.days));
+ try!(builder.set_not_after(&not_after));
- try!(cvt(ffi::X509_set_pubkey(x509.as_ptr(), p_key.as_ptr())));
+ try!(builder.set_pubkey(p_key));
- let name = try!(cvt_p(ffi::X509_get_subject_name(x509.as_ptr())));
-
- let default = [("CN", "rust-openssl")];
- let default_iter = &mut default.iter().map(|&(k, v)| (k, v));
- let arg_iter = &mut self.names.iter().map(|&(ref k, ref v)| (&k[..], &v[..]));
- let iter: &mut Iterator<Item = (&str, &str)> = if self.names.len() == 0 {
- default_iter
- } else {
- arg_iter
- };
-
- for (key, val) in iter {
- try!(X509Generator::add_name_internal(name, &key, &val));
+ let mut name = try!(X509Name::builder());
+ if self.names.is_empty() {
+ try!(name.append_entry_by_nid(nid::COMMONNAME, "rust-openssl"));
+ } else {
+ for &(ref key, ref value) in &self.names {
+ try!(name.append_entry_by_text(key, value));
}
- try!(cvt(ffi::X509_set_issuer_name(x509.as_ptr(), name)));
+ }
+ let name = name.build();
- for (exttype, ext) in self.extensions.iter() {
- try!(X509Generator::add_extension_internal(x509.as_ptr(),
- &exttype,
- &ext.to_string()));
- }
+ try!(builder.set_subject_name(&name));
+ try!(builder.set_issuer_name(&name));
- let hash_fn = self.hash_type.as_ptr();
- try!(cvt(ffi::X509_sign(x509.as_ptr(), p_key.as_ptr(), hash_fn)));
- Ok(x509)
+ for (exttype, ext) in self.extensions.iter() {
+ let extension = match exttype.get_nid() {
+ Some(nid) => {
+ let ctx = builder.x509v3_context(None, None);
+ try!(X509Extension::new_nid(None, Some(&ctx), nid, &ext.to_string()))
+ }
+ None => {
+ let ctx = builder.x509v3_context(None, None);
+ try!(X509Extension::new(None,
+ Some(&ctx),
+ &exttype.get_name().unwrap(),
+ &ext.to_string()))
+ }
+ };
+ try!(builder.append_extension(extension));
}
+
+ try!(builder.sign(p_key, self.hash_type));
+ Ok(builder.build())
}
/// Obtain a certificate signing request (CSR)
+ #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn request(&self, p_key: &PKeyRef) -> Result<X509Req, ErrorStack> {
let cert = match self.sign(p_key) {
Ok(c) => c,
@@ -360,6 +281,108 @@ impl X509Generator {
}
}
+/// A builder type which can create `X509` objects.
+pub struct X509Builder(X509);
+
+impl X509Builder {
+ /// Creates a new builder.
+ pub fn new() -> Result<X509Builder, ErrorStack> {
+ unsafe {
+ ffi::init();
+ cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p)))
+ }
+ }
+
+ /// Sets the notAfter constraint on the certificate.
+ pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> {
+ unsafe { cvt(X509_set_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) }
+ }
+
+ /// Sets the notBefore constraint on the certificate.
+ pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> {
+ unsafe { cvt(X509_set_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) }
+ }
+
+ /// Sets the version of the certificate.
+ ///
+ /// Note that the version is zero-indexed; that is, a certificate corresponding to version 3 of
+ /// the X.509 standard should pass `2` to this method.
+ pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) }
+ }
+
+ /// Sets the serial number of the certificate.
+ pub fn set_serial_number(&mut self,
+ serial_number: &Asn1IntegerRef)
+ -> Result<(), ErrorStack> {
+ unsafe {
+ cvt(ffi::X509_set_serialNumber(self.0.as_ptr(), serial_number.as_ptr())).map(|_| ())
+ }
+ }
+
+ /// Sets the issuer name of the certificate.
+ pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_set_issuer_name(self.0.as_ptr(), issuer_name.as_ptr())).map(|_| ()) }
+ }
+
+ /// Sets the subject name of the certificate.
+ pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> {
+ unsafe {
+ cvt(ffi::X509_set_subject_name(self.0.as_ptr(), subject_name.as_ptr())).map(|_| ())
+ }
+ }
+
+ /// Sets the public key associated with the certificate.
+ pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) }
+ }
+
+ /// Returns a context object which is needed to create certain X509 extension values.
+ ///
+ /// Set `issuer` to `None` if the certificate will be self-signed.
+ pub fn x509v3_context<'a>(&'a self,
+ issuer: Option<&'a X509Ref>,
+ conf: Option<&'a ConfRef>)
+ -> X509v3Context<'a> {
+ unsafe {
+ let mut ctx = mem::zeroed();
+
+ let issuer = match issuer {
+ Some(issuer) => issuer.as_ptr(),
+ None => self.0.as_ptr(),
+ };
+ let subject = self.0.as_ptr();
+ ffi::X509V3_set_ctx(&mut ctx, issuer, subject, ptr::null_mut(), ptr::null_mut(), 0);
+
+ // nodb case taken care of since we zeroed ctx above
+ if let Some(conf) = conf {
+ ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr());
+ }
+
+ X509v3Context(ctx, PhantomData)
+ }
+ }
+
+ /// Adds an X509 extension value to the certificate.
+ pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> {
+ unsafe {
+ try!(cvt(ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1)));
+ mem::forget(extension);
+ Ok(())
+ }
+ }
+
+ /// Signs the certificate with a private key.
+ pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) }
+ }
+
+ /// Consumes the builder, returning the certificate.
+ pub fn build(self) -> X509 {
+ self.0
+ }
+}
+
foreign_type! {
type CType = ffi::X509;
fn drop = ffi::X509_free;
@@ -483,6 +506,11 @@ impl ToOwned for X509Ref {
}
impl X509 {
+ /// Returns a new builder.
+ pub fn builder() -> Result<X509Builder, ErrorStack> {
+ X509Builder::new()
+ }
+
from_pem!(X509, ffi::PEM_read_bio_X509);
from_der!(X509, ffi::d2i_X509);
@@ -545,6 +573,122 @@ impl Stackable for X509 {
type StackType = ffi::stack_st_X509;
}
+/// A context object required to construct certain X509 extension values.
+pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>);
+
+impl<'a> X509v3Context<'a> {
+ pub fn as_ptr(&self) -> *mut ffi::X509V3_CTX {
+ &self.0 as *const _ as *mut _
+ }
+}
+
+foreign_type! {
+ type CType = ffi::X509_EXTENSION;
+ fn drop = ffi::X509_EXTENSION_free;
+
+ pub struct X509Extension;
+ pub struct X509ExtensionRef;
+}
+
+impl Stackable for X509Extension {
+ type StackType = ffi::stack_st_X509_EXTENSION;
+}
+
+impl X509Extension {
+ /// Constructs an X509 extension value. See `man x509v3_config` for information on supported
+ /// names and their value formats.
+ ///
+ /// Some extension types, such as `subjectAlternativeName`, require an `X509v3Context` to be
+ /// provided.
+ ///
+ /// See the extension module for builder types which will construct certain common extensions.
+ pub fn new(conf: Option<&ConfRef>,
+ context: Option<&X509v3Context>,
+ name: &str,
+ value: &str)
+ -> Result<X509Extension, ErrorStack> {
+ let name = CString::new(name).unwrap();
+ let value = CString::new(value).unwrap();
+ unsafe {
+ ffi::init();
+ let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr);
+ let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr);
+ let name = name.as_ptr() as *mut _;
+ let value = value.as_ptr() as *mut _;
+
+ cvt_p(ffi::X509V3_EXT_nconf(conf, context, name, value)).map(X509Extension)
+ }
+ }
+
+ /// Constructs an X509 extension value. See `man x509v3_config` for information on supported
+ /// extensions and their value formats.
+ ///
+ /// Some extension types, such as `nid::SUBJECT_ALTERNATIVE_NAME`, require an `X509v3Context` to
+ /// be provided.
+ ///
+ /// See the extension module for builder types which will construct certain common extensions.
+ pub fn new_nid(conf: Option<&ConfRef>,
+ context: Option<&X509v3Context>,
+ name: Nid,
+ value: &str)
+ -> Result<X509Extension, ErrorStack> {
+ let value = CString::new(value).unwrap();
+ unsafe {
+ ffi::init();
+ let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr);
+ let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr);
+ let name = name.as_raw();
+ let value = value.as_ptr() as *mut _;
+
+ cvt_p(ffi::X509V3_EXT_nconf_nid(conf, context, name, value)).map(X509Extension)
+ }
+ }
+}
+
+pub struct X509NameBuilder(X509Name);
+
+impl X509NameBuilder {
+ pub fn new() -> Result<X509NameBuilder, ErrorStack> {
+ unsafe {
+ ffi::init();
+ cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p)))
+ }
+ }
+
+ pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> {
+ unsafe {
+ let field = CString::new(field).unwrap();
+ assert!(value.len() <= c_int::max_value() as usize);
+ cvt(ffi::X509_NAME_add_entry_by_txt(self.0.as_ptr(),
+ field.as_ptr() as *mut _,
+ ffi::MBSTRING_UTF8,
+ value.as_ptr(),
+ value.len() as c_int,
+ -1,
+ 0))
+ .map(|_| ())
+ }
+ }
+
+ pub fn append_entry_by_nid(&mut self, field: Nid, value: &str) -> Result<(), ErrorStack> {
+ unsafe {
+ assert!(value.len() <= c_int::max_value() as usize);
+ cvt(ffi::X509_NAME_add_entry_by_NID(self.0.as_ptr(),
+ field.as_raw(),
+ ffi::MBSTRING_UTF8,
+ value.as_ptr() as *mut _,
+ value.len() as c_int,
+ -1,
+ 0))
+ .map(|_| ())
+ }
+ }
+
+ pub fn build(self) -> X509Name {
+ self.0
+ }
+}
+
foreign_type! {
type CType = ffi::X509_NAME;
fn drop = ffi::X509_NAME_free;
@@ -554,6 +698,11 @@ foreign_type! {
}
impl X509Name {
+ /// Returns a new builder.
+ pub fn builder() -> Result<X509NameBuilder, ErrorStack> {
+ X509NameBuilder::new()
+ }
+
/// Loads subject names from a file containing PEM-formatted certificates.
///
/// This is commonly used in conjunction with `SslContextBuilder::set_client_ca_list`.
@@ -622,6 +771,70 @@ impl X509NameEntryRef {
}
}
+pub struct X509ReqBuilder(X509Req);
+
+impl X509ReqBuilder {
+ pub fn new() -> Result<X509ReqBuilder, ErrorStack> {
+ unsafe {
+ ffi::init();
+ cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p)))
+ }
+
+ }
+
+ pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_REQ_set_version(self.0.as_ptr(), version.into())).map(|_| ()) }
+ }
+
+ pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> {
+ unsafe {
+ cvt(ffi::X509_REQ_set_subject_name(self.0.as_ptr(), subject_name.as_ptr())).map(|_| ())
+ }
+ }
+
+ pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_REQ_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) }
+ }
+
+ pub fn x509v3_context<'a>(&'a self,
+ conf: Option<&'a ConfRef>)
+ -> X509v3Context<'a> {
+ unsafe {
+ let mut ctx = mem::zeroed();
+
+ ffi::X509V3_set_ctx(&mut ctx,
+ ptr::null_mut(),
+ ptr::null_mut(),
+ self.0.as_ptr(),
+ ptr::null_mut(),
+ 0);
+
+ // nodb case taken care of since we zeroed ctx above
+ if let Some(conf) = conf {
+ ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr());
+ }
+
+ X509v3Context(ctx, PhantomData)
+ }
+ }
+
+ pub fn add_extensions(&mut self,
+ extensions: &StackRef<X509Extension>)
+ -> Result<(), ErrorStack> {
+ unsafe {
+ cvt(ffi::X509_REQ_add_extensions(self.0.as_ptr(), extensions.as_ptr())).map(|_| ())
+ }
+ }
+
+ pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> {
+ unsafe { cvt(ffi::X509_REQ_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) }
+ }
+
+ pub fn build(self) -> X509Req {
+ self.0
+ }
+}
+
foreign_type! {
type CType = ffi::X509_REQ;
fn drop = ffi::X509_REQ_free;
@@ -631,6 +844,10 @@ foreign_type! {
}
impl X509Req {
+ pub fn builder() -> Result<X509ReqBuilder, ErrorStack> {
+ X509ReqBuilder::new()
+ }
+
/// Reads CSR from PEM
pub fn from_pem(buf: &[u8]) -> Result<X509Req, ErrorStack> {
let mem_bio = try!(MemBioSlice::new(buf));
@@ -657,13 +874,6 @@ impl X509ReqRef {
}
}
- pub fn set_version(&mut self, value: i32) -> Result<(), ErrorStack>
- {
- unsafe {
- cvt(ffi::X509_REQ_set_version(self.as_ptr(), value as c_long)).map(|_| ())
- }
- }
-
pub fn subject_name(&self) -> &X509NameRef {
unsafe {
let name = compat::X509_REQ_get_subject_name(self.as_ptr());
@@ -671,12 +881,6 @@ impl X509ReqRef {
X509NameRef::from_ptr(name)
}
}
-
- pub fn set_subject_name(&mut self, value: &X509NameRef) -> Result<(), ErrorStack> {
- unsafe {
- cvt(ffi::X509_REQ_set_subject_name(self.as_ptr(), value.as_ptr())).map(|_| ())
- }
- }
}
/// A collection of X.509 extensions.
diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs
index 58db3a8b..2632eade 100644
--- a/openssl/src/x509/tests.rs
+++ b/openssl/src/x509/tests.rs
@@ -1,13 +1,17 @@
use hex::{FromHex, ToHex};
+use asn1::Asn1Time;
+use bn::{BigNum, MSB_MAYBE_ZERO};
use ec::{NAMED_CURVE, EcGroup, EcKey};
use hash::MessageDigest;
use nid::X9_62_PRIME256V1;
use pkey::PKey;
use rsa::Rsa;
+use stack::Stack;
+use x509::{X509, X509Generator, X509Name, X509Req};
+use x509::extension::{Extension, BasicConstraints, KeyUsage, ExtendedKeyUsage,
+ SubjectKeyIdentifier, AuthorityKeyIdentifier, SubjectAlternativeName};
use ssl::{SslMethod, SslContextBuilder};
-use x509::{X509, X509Generator, X509Req};
-use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr};
use x509::extension::AltNameOption as SAN;
use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment};
use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth};
@@ -18,13 +22,13 @@ fn get_generator() -> X509Generator {
.set_valid_period(365 * 2)
.add_name("CN".to_string(), "test_me".to_string())
.set_sign_hash(MessageDigest::sha1())
- .add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]))
- .add_extension(ExtKeyUsage(vec![ClientAuth,
+ .add_extension(Extension::KeyUsage(vec![DigitalSignature, KeyEncipherment]))
+ .add_extension(Extension::ExtKeyUsage(vec![ClientAuth,
ServerAuth,
ExtKeyUsageOption::Other("2.999.1".to_owned())]))
- .add_extension(SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())]))
- .add_extension(OtherNid(nid::BASIC_CONSTRAINTS, "critical,CA:TRUE".to_owned()))
- .add_extension(OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned()))
+ .add_extension(Extension::SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())]))
+ .add_extension(Extension::OtherNid(nid::BASIC_CONSTRAINTS, "critical,CA:TRUE".to_owned()))
+ .add_extension(Extension::OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned()))
}
fn pkey() -> PKey {
@@ -51,8 +55,8 @@ fn test_cert_gen() {
fn test_cert_gen_extension_ordering() {
let pkey = pkey();
get_generator()
- .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned()))
- .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned()))
+ .add_extension(Extension::OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned()))
+ .add_extension(Extension::OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned()))
.sign(&pkey)
.expect("Failed to generate cert with order-dependent extensions");
}
@@ -63,8 +67,8 @@ fn test_cert_gen_extension_ordering() {
fn test_cert_gen_extension_bad_ordering() {
let pkey = pkey();
let result = get_generator()
- .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned()))
- .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned()))
+ .add_extension(Extension::OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned()))
+ .add_extension(Extension::OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned()))
.sign(&pkey);
assert!(result.is_err());
@@ -184,6 +188,88 @@ fn test_subject_alt_name_iter() {
}
#[test]
+fn x509_builder() {
+ let pkey = pkey();
+
+ let mut name = X509Name::builder().unwrap();
+ name.append_entry_by_nid(nid::COMMONNAME, "foobar.com").unwrap();
+ let name = name.build();
+
+ let mut builder = X509::builder().unwrap();
+ builder.set_version(2).unwrap();
+ builder.set_subject_name(&name).unwrap();
+ builder.set_issuer_name(&name).unwrap();
+ builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
+ builder.set_not_after(&Asn1Time::days_from_now(365).unwrap()).unwrap();
+ builder.set_pubkey(&pkey).unwrap();
+
+ let mut serial = BigNum::new().unwrap();;
+ serial.rand(128, MSB_MAYBE_ZERO, false).unwrap();
+ builder.set_serial_number(&serial.to_asn1_integer().unwrap()).unwrap();
+
+ let basic_constraints = BasicConstraints::new().critical().ca().build().unwrap();
+ builder.append_extension(basic_constraints).unwrap();
+ let key_usage = KeyUsage::new().digital_signature().key_encipherment().build().unwrap();
+ builder.append_extension(key_usage).unwrap();
+ let ext_key_usage = ExtendedKeyUsage::new()
+ .client_auth()
+ .server_auth()
+ .other("2.999.1")
+ .build()
+ .unwrap();
+ builder.append_extension(ext_key_usage).unwrap();
+ let subject_key_identifier = SubjectKeyIdentifier::new()
+ .build(&builder.x509v3_context(None, None))
+ .unwrap();
+ builder.append_extension(subject_key_identifier).unwrap();
+ let authority_key_identifier = AuthorityKeyIdentifier::new()
+ .keyid(true)
+ .build(&builder.x509v3_context(None, None))
+ .unwrap();
+ builder.append_extension(authority_key_identifier).unwrap();
+ let subject_alternative_name = SubjectAlternativeName::new()
+ .dns("example.com")
+ .build(&builder.x509v3_context(None, None))
+ .unwrap();
+ builder.append_extension(subject_alternative_name).unwrap();
+
+ builder.sign(&pkey, MessageDigest::sha256()).unwrap();
+
+ let x509 = builder.build();
+
+ assert!(pkey.public_eq(&x509.public_key().unwrap()));
+
+ let cn = x509.subject_name().entries_by_nid(nid::COMMONNAME).next().unwrap();
+ assert_eq!("foobar.com".as_bytes(), cn.data().as_slice());
+}
+
+#[test]
+fn x509_req_builder() {
+ let pkey = pkey();
+
+ let mut name = X509Name::builder().unwrap();
+ name.append_entry_by_nid(nid::COMMONNAME, "foobar.com").unwrap();
+ let name = name.build();
+
+ let mut builder = X509Req::builder().unwrap();
+ builder.set_version(2).unwrap();
+ builder.set_subject_name(&name).unwrap();
+ builder.set_pubkey(&pkey).unwrap();
+
+ let mut extensions = Stack::new().unwrap();
+ let key_usage = KeyUsage::new().digital_signature().key_encipherment().build().unwrap();
+ extensions.push(key_usage).unwrap();
+ let subject_alternative_name = SubjectAlternativeName::new()
+ .dns("example.com")
+ .build(&builder.x509v3_context(None))
+ .unwrap();
+ extensions.push(subject_alternative_name).unwrap();
+ builder.add_extensions(&extensions).unwrap();
+
+ builder.sign(&pkey, MessageDigest::sha256()).unwrap();
+}
+
+#[test]
fn test_stack_from_pem() {
let certs = include_bytes!("../../test/certs.pem");
let certs = X509::stack_from_pem(certs).unwrap();