diff options
author | Justus Winter <justus@sequoia-pgp.org> | 2020-01-16 15:21:33 +0100 |
---|---|---|
committer | Justus Winter <justus@sequoia-pgp.org> | 2020-01-16 15:21:33 +0100 |
commit | 9dcff17ee0075213fa3f2fefcaa6579336f68be1 (patch) | |
tree | df699b50b6cc25f5b0af69be6eec79f768ba0675 /openpgp/src/crypto/asymmetric.rs | |
parent | 91c1881b81491882128c78e454adb41a5161a1f5 (diff) |
openpgp: Consolidate public key encryption code.
Diffstat (limited to 'openpgp/src/crypto/asymmetric.rs')
-rw-r--r-- | openpgp/src/crypto/asymmetric.rs | 36 |
1 files changed, 36 insertions, 0 deletions
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<KeyPair> for Key<key::SecretParts, key::UnspecifiedRole> { key.mark_parts_secret().expect("XXX") } } + +impl<P: key::KeyParts, R: key::KeyRole> Key<P, R> { + /// Encrypts the given data with this key. + pub fn encrypt(&self, data: &SessionKey) -> Result<mpis::Ciphertext> { + 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()), + } + } +} |