Skip to content

Commit

Permalink
fix: handling other key encryption algorithms
Browse files Browse the repository at this point in the history
added vectors & tests accordingly
  • Loading branch information
nitneuqr committed Nov 19, 2024
1 parent aa1cf3d commit 3bfa0ec
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
30 changes: 21 additions & 9 deletions src/rust/src/pkcs7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,26 @@ fn deserialize_and_decrypt<'p>(
}
};

// Decrypt the key using the private key
let padding = types::PKCS1V15.get(py)?.call0()?;
let key = private_key
.call_method1(
pyo3::intern!(py, "decrypt"),
(recipient_info.encrypted_key, &padding),
)?
.extract::<pyo3::pybacked::PyBackedBytes>()?;
// Raise error when the key encryption algorithm is not RSA
let key = match recipient_info.key_encryption_algorithm.oid() {
&oid::RSA_OID => {
let padding = types::PKCS1V15.get(py)?.call0()?;
private_key
.call_method1(
pyo3::intern!(py, "decrypt"),
(recipient_info.encrypted_key, &padding),
)?
.extract::<pyo3::pybacked::PyBackedBytes>()?
}
_ => {
return Err(CryptographyError::from(
exceptions::UnsupportedAlgorithm::new_err((
"Only RSA with PKCS #1 v1.5 padding is currently supported for key decryption.",
exceptions::Reasons::UNSUPPORTED_SERIALIZATION,
)),
));
}
};

// Get algorithm
// TODO: implement all the possible algorithms
Expand All @@ -240,7 +252,7 @@ fn deserialize_and_decrypt<'p>(
_ => {
return Err(CryptographyError::from(
exceptions::UnsupportedAlgorithm::new_err((
"Only AES-128-CBC is currently supported for decryption.",
"Only AES-128-CBC is currently supported for content decryption.",
exceptions::Reasons::UNSUPPORTED_SERIALIZATION,
)),
));
Expand Down
19 changes: 18 additions & 1 deletion tests/hazmat/primitives/test_pkcs7.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,15 @@ def _load_rsa_cert_key():
return cert, key


def _load_rsa_oaep_pkcs7_pem():
enveloped = load_vectors_from_file(
os.path.join("pkcs7", "enveloped-rsa-oaep.pem"),
loader=lambda pemfile: pemfile.read(),
mode="rb",
)
return enveloped


def _load_aes_256_cbc_pkcs7_pem():
enveloped = load_vectors_from_file(
os.path.join("pkcs7", "enveloped-aes-256-cbc.pem"),
Expand Down Expand Up @@ -1197,7 +1206,15 @@ def test_smime_decrypt_no_recipient_match(
enveloped, another_cert, another_private_key, []
)

def test_smime_decrypt_unsupported_algorithm(
def test_smime_decrypt_unsupported_key_encryption_algorithm(
self, backend, data, certificate, private_key
):
enveloped = _load_rsa_oaep_pkcs7_pem()

with pytest.raises(exceptions.UnsupportedAlgorithm):
pkcs7.pkcs7_decrypt_pem(enveloped, certificate, private_key, [])

def test_smime_decrypt_unsupported_content_encryption_algorithm(
self, backend, data, certificate, private_key
):
enveloped = _load_aes_256_cbc_pkcs7_pem()
Expand Down

0 comments on commit 3bfa0ec

Please sign in to comment.