Support for PKCS#8 unencrypted private key deserialization

This commit is contained in:
oberien 2019-12-01 03:02:01 +01:00
parent 454cb6f9bc
commit a7fa260331
4 changed files with 34 additions and 0 deletions

View File

@ -123,6 +123,8 @@ cfg_if! {
}
}
pub enum PKCS8_PRIV_KEY_INFO {}
pub enum EVP_PKEY_ASN1_METHOD {}
pub enum EVP_PKEY_CTX {}

View File

@ -137,6 +137,13 @@ extern "C" {
cb: pem_password_cb,
u: *mut c_void,
) -> *mut EVP_PKEY;
pub fn d2i_PKCS8_PRIV_KEY_INFO_bio(
bp: *mut BIO,
x: *mut *mut PKCS8_PRIV_KEY_INFO,
) -> *mut PKCS8_PRIV_KEY_INFO;
pub fn EVP_PKCS82PKEY(
p8: *const PKCS8_PRIV_KEY_INFO,
) -> *mut EVP_PKEY;
pub fn PEM_read_bio_PKCS7(
bio: *mut BIO,

View File

@ -524,6 +524,25 @@ impl PKey<Private> {
ffi::d2i_AutoPrivateKey
}
/// Deserializes a DER-formatted PKCS#8 unencrypted private key.
///
/// This method is mainly for interoperability reasons. Encrypted keyfiles should be preferred.
pub fn private_key_from_pkcs8(
der: &[u8],
) -> Result<PKey<Private>, ErrorStack>
{
unsafe {
ffi::init();
let bio = MemBioSlice::new(der)?;
let p8inf = cvt_p(ffi::d2i_PKCS8_PRIV_KEY_INFO_bio(
bio.as_ptr(),
ptr::null_mut(),
))?;
cvt_p(ffi::EVP_PKCS82PKEY(p8inf))
.map(|p| PKey::from_ptr(p))
}
}
/// Deserializes a DER-formatted PKCS#8 private key, using a callback to retrieve the password
/// if the key is encrpyted.
///
@ -639,6 +658,12 @@ mod tests {
assert!(PKey::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err());
}
#[test]
fn test_unencrypted_pkcs8() {
let key = include_bytes!("../test/pkcs8-nocrypt.der");
PKey::private_key_from_pkcs8(key).unwrap();
}
#[test]
fn test_encrypted_pkcs8_passphrase() {
let key = include_bytes!("../test/pkcs8.der");

Binary file not shown.