From 9dcff17ee0075213fa3f2fefcaa6579336f68be1 Mon Sep 17 00:00:00 2001 From: Justus Winter Date: Thu, 16 Jan 2020 15:21:33 +0100 Subject: openpgp: Consolidate public key encryption code. --- openpgp/src/crypto/asymmetric.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'openpgp/src/crypto/asymmetric.rs') diff --git a/openpgp/src/crypto/asymmetric.rs b/openpgp/src/crypto/asymmetric.rs index 7185a471..e8dd32e4 100644 --- a/openpgp/src/crypto/asymmetric.rs +++ b/openpgp/src/crypto/asymmetric.rs @@ -269,3 +269,39 @@ impl From for Key { key.mark_parts_secret().expect("XXX") } } + +impl Key { + /// Encrypts the given data with this key. + pub fn encrypt(&self, data: &SessionKey) -> Result { + use crate::PublicKeyAlgorithm::*; + + #[allow(deprecated)] + match self.pk_algo() { + RSAEncryptSign | RSAEncrypt => { + // Extract the public recipient. + match self.mpis() { + mpis::PublicKey::RSA { e, n } => { + // The ciphertext has the length of the modulus. + let mut esk = vec![0u8; n.value().len()]; + let mut rng = Yarrow::default(); + let pk = rsa::PublicKey::new(n.value(), e.value())?; + rsa::encrypt_pkcs1(&pk, &mut rng, data, + &mut esk)?; + Ok(mpis::Ciphertext::RSA { + c: MPI::new(&esk), + }) + }, + pk => { + Err(Error::MalformedPacket( + format!( + "Key: Expected RSA public key, got {:?}", + pk)).into()) + }, + } + }, + ECDH => crate::crypto::ecdh::encrypt(self.mark_parts_public_ref(), + data), + algo => Err(Error::UnsupportedPublicKeyAlgorithm(algo).into()), + } + } +} -- cgit v1.2.3