use std::{fmt, sync::Arc};
use rsa::RsaPublicKey;
pub const XMLENC_NS: &str = "http://www.w3.org/2001/04/xmlenc#";
pub const XMLENC11_NS: &str = "http://www.w3.org/2009/xmlenc11#";
pub const XMLDSIG_NS: &str = "http://www.w3.org/2000/09/xmldsig#";
pub const MAX_CIPHER_VALUE_BASE64_LEN: usize =
crate::hard_limits::ENCRYPTION_CIPHER_VALUE_BASE64_BYTE_CEILING;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EncryptedDataType {
Element,
Content,
Other(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataEncryptionAlgorithm {
Aes128Cbc,
Aes256Cbc,
Aes128Gcm,
Aes256Gcm,
}
impl DataEncryptionAlgorithm {
pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
match uri {
"http://www.w3.org/2001/04/xmlenc#aes128-cbc" => Ok(Self::Aes128Cbc),
"http://www.w3.org/2001/04/xmlenc#aes256-cbc" => Ok(Self::Aes256Cbc),
"http://www.w3.org/2009/xmlenc11#aes128-gcm" => Ok(Self::Aes128Gcm),
"http://www.w3.org/2009/xmlenc11#aes256-gcm" => Ok(Self::Aes256Gcm),
_ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
}
}
pub const fn key_len(self) -> usize {
match self {
Self::Aes128Cbc | Self::Aes128Gcm => 16,
Self::Aes256Cbc | Self::Aes256Gcm => 32,
}
}
pub const fn uri(self) -> &'static str {
match self {
Self::Aes128Cbc => "http://www.w3.org/2001/04/xmlenc#aes128-cbc",
Self::Aes256Cbc => "http://www.w3.org/2001/04/xmlenc#aes256-cbc",
Self::Aes128Gcm => "http://www.w3.org/2009/xmlenc11#aes128-gcm",
Self::Aes256Gcm => "http://www.w3.org/2009/xmlenc11#aes256-gcm",
}
}
pub(crate) const fn minimum_ciphertext_len(self) -> usize {
match self {
Self::Aes128Cbc | Self::Aes256Cbc => 32,
Self::Aes128Gcm | Self::Aes256Gcm => 28,
}
}
pub(crate) fn ciphertext_len_for_plaintext(self, plaintext_len: usize) -> Option<usize> {
match self {
Self::Aes128Cbc | Self::Aes256Cbc => (plaintext_len / 16)
.checked_add(1)?
.checked_mul(16)?
.checked_add(16),
Self::Aes128Gcm | Self::Aes256Gcm => plaintext_len.checked_add(28),
}
}
}
pub(crate) fn validate_ciphertext_framing(
algorithm: DataEncryptionAlgorithm,
ciphertext_len: usize,
) -> Result<(), XmlEncError> {
let minimum = algorithm.minimum_ciphertext_len();
if ciphertext_len < minimum {
let algorithm_name = match algorithm {
DataEncryptionAlgorithm::Aes128Cbc | DataEncryptionAlgorithm::Aes256Cbc => "AES-CBC",
DataEncryptionAlgorithm::Aes128Gcm | DataEncryptionAlgorithm::Aes256Gcm => "AES-GCM",
};
return Err(XmlEncError::DataTooShort {
algorithm: algorithm_name,
minimum,
actual: ciphertext_len,
});
}
if matches!(
algorithm,
DataEncryptionAlgorithm::Aes128Cbc | DataEncryptionAlgorithm::Aes256Cbc
) && !(ciphertext_len - 16).is_multiple_of(16)
{
return Err(XmlEncError::InvalidCbcCiphertextLength(ciphertext_len - 16));
}
Ok(())
}
impl KeyTransportAlgorithm {
pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
match uri {
"http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" => Ok(Self::RsaOaepMgf1p),
"http://www.w3.org/2009/xmlenc11#rsa-oaep" => Ok(Self::RsaOaep11),
_ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
}
}
pub const fn uri(self) -> &'static str {
match self {
Self::RsaOaepMgf1p => "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p",
Self::RsaOaep11 => "http://www.w3.org/2009/xmlenc11#rsa-oaep",
}
}
}
impl KeyWrapAlgorithm {
pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
match uri {
"http://www.w3.org/2001/04/xmlenc#kw-aes128" => Ok(Self::AesKw128),
"http://www.w3.org/2001/04/xmlenc#kw-aes256" => Ok(Self::AesKw256),
_ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
}
}
pub const fn key_len(self) -> usize {
match self {
Self::AesKw128 => 16,
Self::AesKw256 => 32,
}
}
pub const fn uri(self) -> &'static str {
match self {
Self::AesKw128 => "http://www.w3.org/2001/04/xmlenc#kw-aes128",
Self::AesKw256 => "http://www.w3.org/2001/04/xmlenc#kw-aes256",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyTransportAlgorithm {
RsaOaepMgf1p,
RsaOaep11,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyWrapAlgorithm {
AesKw128,
AesKw256,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OaepDigestAlgorithm {
Sha1,
Sha256,
Sha384,
Sha512,
}
impl OaepDigestAlgorithm {
pub fn from_uri(uri: &str) -> Option<Self> {
match uri {
"http://www.w3.org/2000/09/xmldsig#sha1" => Some(Self::Sha1),
"http://www.w3.org/2001/04/xmlenc#sha256" => Some(Self::Sha256),
"http://www.w3.org/2001/04/xmlenc#sha384"
| "http://www.w3.org/2001/04/xmldsig-more#sha384" => Some(Self::Sha384),
"http://www.w3.org/2001/04/xmlenc#sha512" => Some(Self::Sha512),
_ => None,
}
}
pub fn from_mgf_uri(uri: &str) -> Option<Self> {
match uri {
"http://www.w3.org/2009/xmlenc11#mgf1sha1" => Some(Self::Sha1),
"http://www.w3.org/2009/xmlenc11#mgf1sha256" => Some(Self::Sha256),
"http://www.w3.org/2009/xmlenc11#mgf1sha384" => Some(Self::Sha384),
"http://www.w3.org/2009/xmlenc11#mgf1sha512" => Some(Self::Sha512),
_ => None,
}
}
pub const fn uri(self) -> &'static str {
match self {
Self::Sha1 => "http://www.w3.org/2000/09/xmldsig#sha1",
Self::Sha256 => "http://www.w3.org/2001/04/xmlenc#sha256",
Self::Sha384 => "http://www.w3.org/2001/04/xmlenc#sha384",
Self::Sha512 => "http://www.w3.org/2001/04/xmlenc#sha512",
}
}
pub const fn mgf_uri(self) -> &'static str {
match self {
Self::Sha1 => "http://www.w3.org/2009/xmlenc11#mgf1sha1",
Self::Sha256 => "http://www.w3.org/2009/xmlenc11#mgf1sha256",
Self::Sha384 => "http://www.w3.org/2009/xmlenc11#mgf1sha384",
Self::Sha512 => "http://www.w3.org/2009/xmlenc11#mgf1sha512",
}
}
}
#[cfg(test)]
mod tests {
use super::OaepDigestAlgorithm;
#[test]
fn oaep_sha384_accepts_both_interoperable_digest_uris() {
for uri in [
"http://www.w3.org/2001/04/xmlenc#sha384",
"http://www.w3.org/2001/04/xmldsig-more#sha384",
] {
assert_eq!(
OaepDigestAlgorithm::from_uri(uri),
Some(OaepDigestAlgorithm::Sha384)
);
}
}
#[test]
fn oaep_mgf_uris_round_trip() {
for algorithm in [
OaepDigestAlgorithm::Sha1,
OaepDigestAlgorithm::Sha256,
OaepDigestAlgorithm::Sha384,
OaepDigestAlgorithm::Sha512,
] {
assert_eq!(
OaepDigestAlgorithm::from_mgf_uri(algorithm.mgf_uri()),
Some(algorithm)
);
}
assert_eq!(
OaepDigestAlgorithm::from_mgf_uri("urn:unsupported-mgf"),
None
);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RsaOaepParameters {
pub algorithm: KeyTransportAlgorithm,
pub digest: OaepDigestAlgorithm,
pub mgf_digest: OaepDigestAlgorithm,
pub label: Vec<u8>,
}
impl RsaOaepParameters {
pub fn legacy() -> Self {
Self {
algorithm: KeyTransportAlgorithm::RsaOaepMgf1p,
digest: OaepDigestAlgorithm::Sha1,
mgf_digest: OaepDigestAlgorithm::Sha1,
label: Vec::new(),
}
}
pub fn xmlenc11(digest: OaepDigestAlgorithm, mgf_digest: OaepDigestAlgorithm) -> Self {
Self {
algorithm: KeyTransportAlgorithm::RsaOaep11,
digest,
mgf_digest,
label: Vec::new(),
}
}
pub fn label(mut self, label: impl Into<Vec<u8>>) -> Self {
self.label = label.into();
self
}
}
impl Default for RsaOaepParameters {
fn default() -> Self {
Self::xmlenc11(OaepDigestAlgorithm::Sha256, OaepDigestAlgorithm::Sha256)
}
}
#[derive(Clone)]
pub enum EncryptionRecipient {
RsaOaep {
public_key: Arc<dyn crate::provider::KeyTransportKey>,
parameters: RsaOaepParameters,
recipient: Option<String>,
key_name: Option<String>,
},
AesKeyWrap {
kek: Vec<u8>,
algorithm: KeyWrapAlgorithm,
recipient: Option<String>,
key_name: Option<String>,
},
}
impl fmt::Debug for EncryptionRecipient {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RsaOaep {
parameters,
recipient,
key_name,
..
} => formatter
.debug_struct("EncryptionRecipient::RsaOaep")
.field("public_key", &"[PUBLIC KEY]")
.field("parameters", parameters)
.field("recipient", recipient)
.field("key_name", key_name)
.finish(),
Self::AesKeyWrap {
algorithm,
recipient,
key_name,
..
} => formatter
.debug_struct("EncryptionRecipient::AesKeyWrap")
.field("kek", &"[REDACTED]")
.field("algorithm", algorithm)
.field("recipient", recipient)
.field("key_name", key_name)
.finish(),
}
}
}
impl EncryptionRecipient {
pub fn rsa_oaep(public_key: RsaPublicKey) -> Self {
Self::provider_key_transport(Arc::new(crate::provider::RustCryptoRsaPublicKey::new(
public_key,
)))
}
pub fn provider_key_transport(public_key: Arc<dyn crate::provider::KeyTransportKey>) -> Self {
Self::RsaOaep {
public_key,
parameters: RsaOaepParameters::default(),
recipient: None,
key_name: None,
}
}
pub fn aes_key_wrap(kek: impl Into<Vec<u8>>, algorithm: KeyWrapAlgorithm) -> Self {
Self::AesKeyWrap {
kek: kek.into(),
algorithm,
recipient: None,
key_name: None,
}
}
pub fn oaep_parameters(mut self, parameters: RsaOaepParameters) -> Self {
if let Self::RsaOaep {
parameters: current,
..
} = &mut self
{
*current = parameters;
}
self
}
pub fn recipient(mut self, value: impl Into<String>) -> Self {
match &mut self {
Self::RsaOaep { recipient, .. } | Self::AesKeyWrap { recipient, .. } => {
*recipient = Some(value.into());
}
}
self
}
pub fn key_name(mut self, value: impl Into<String>) -> Self {
match &mut self {
Self::RsaOaep { key_name, .. } | Self::AesKeyWrap { key_name, .. } => {
*key_name = Some(value.into());
}
}
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplacementMode {
ReplaceElement,
ReplaceContent,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionResult {
pub encrypted_data_xml: String,
pub replacement: ReplacementMode,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DocumentEncryptionOptions<'a> {
pub element_id: Option<&'a str>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionMethod {
pub algorithm: String,
pub key_size_bits: Option<usize>,
pub oaep_digest: Option<String>,
pub mgf_algorithm: Option<String>,
pub oaep_params: Option<Vec<u8>>,
}
impl EncryptionMethod {
pub(crate) fn validate_structure(&self) -> Result<(), XmlEncError> {
if self.key_size_bits == Some(0) {
return Err(XmlEncError::InvalidStructure(
"KeySize must be a positive integer".into(),
));
}
let is_legacy_oaep = self.algorithm == KeyTransportAlgorithm::RsaOaepMgf1p.uri();
let is_oaep11 = self.algorithm == KeyTransportAlgorithm::RsaOaep11.uri();
if (self.oaep_params.is_some()
|| self.oaep_digest.is_some()
|| self.mgf_algorithm.is_some())
&& !is_legacy_oaep
&& !is_oaep11
{
return Err(XmlEncError::InvalidStructure(
"OAEP parameters are only valid for RSA-OAEP EncryptionMethod".into(),
));
}
if self.mgf_algorithm.is_some() && !is_oaep11 {
return Err(XmlEncError::InvalidStructure(
"MGF is only valid for XML Encryption 1.1 RSA-OAEP".into(),
));
}
if let (Some(actual), Some(expected)) =
(self.key_size_bits, fixed_aes_key_size(&self.algorithm))
&& actual != expected
{
return Err(XmlEncError::InvalidStructure(format!(
"EncryptionMethod {} requires KeySize {expected}, got {actual}",
self.algorithm
)));
}
Ok(())
}
}
fn fixed_aes_key_size(algorithm: &str) -> Option<usize> {
let key_len = DataEncryptionAlgorithm::from_uri(algorithm)
.map(DataEncryptionAlgorithm::key_len)
.or_else(|_| KeyWrapAlgorithm::from_uri(algorithm).map(KeyWrapAlgorithm::key_len))
.ok()?;
Some(key_len * 8)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CipherData {
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedKey {
pub id: Option<String>,
pub recipient: Option<String>,
pub key_name: Option<String>,
pub encryption_method: EncryptionMethod,
pub cipher_data: CipherData,
pub reference_list: Option<ReferenceList>,
pub carried_key_name: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReferenceList {
pub data_references: Vec<String>,
pub key_references: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedData {
pub id: Option<String>,
pub encrypted_type: Option<EncryptedDataType>,
pub key_name: Option<String>,
pub encryption_method: EncryptionMethod,
pub encrypted_keys: Vec<EncryptedKey>,
pub cipher_data: CipherData,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecryptedContent {
Xml(String),
Bytes(Vec<u8>),
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum XmlEncError {
#[error("XML Encryption policy violation: {0}")]
Policy(#[from] crate::policy::PolicyViolation),
#[error("cryptographic provider error: {0}")]
Provider(#[from] crate::provider::ProviderError),
#[error("XML parsing error: {0}")]
XmlParse(#[from] roxmltree::Error),
#[error("XML document error: {0}")]
Document(#[from] crate::document::XmlDocumentError),
#[error("missing required {0}")]
MissingRequired(&'static str),
#[error("invalid encrypted structure: {0}")]
InvalidStructure(String),
#[error("selected node ID is missing or ambiguous: {id}")]
SelectedNodeUnavailable {
id: String,
},
#[error("unsupported encryption algorithm: {0}")]
UnsupportedAlgorithm(String),
#[error("invalid base64 data: {0}")]
Base64(String),
#[error("{algorithm} ciphertext is too short: need at least {minimum} bytes, got {actual}")]
DataTooShort {
algorithm: &'static str,
minimum: usize,
actual: usize,
},
#[error("AES-CBC ciphertext length must be a non-zero multiple of 16 bytes, got {0}")]
InvalidCbcCiphertextLength(usize),
#[error("invalid XMLEnc padding")]
InvalidPadding,
#[error("AES-GCM authentication failed")]
AeadAuthenticationFailed,
#[error("{algorithm:?} requires a {expected}-byte key, got {actual}")]
InvalidKeySize {
algorithm: DataEncryptionAlgorithm,
expected: usize,
actual: usize,
},
#[error(
"{algorithm:?} cannot safely select among {actual} unordered decryption key candidates"
)]
AmbiguousKeyCandidates {
algorithm: DataEncryptionAlgorithm,
actual: usize,
},
#[error("{algorithm:?} requires a {expected}-byte KEK, got {actual}")]
InvalidKekSize {
algorithm: KeyWrapAlgorithm,
expected: usize,
actual: usize,
},
#[error("wrapped-key value must be {expected} bytes, got {actual}")]
InvalidWrappedKeyLength {
expected: usize,
actual: usize,
},
#[error("invalid encryption configuration: {0}")]
InvalidEncryptionConfig(String),
#[error("no suitable decryption key was resolved")]
KeyNotFound,
#[error("no matching EncryptedData element was found")]
EncryptedDataNotFound,
#[error("more than one EncryptedData element matched; select one by Id")]
AmbiguousEncryptedData,
#[error("no matching element was found for encryption")]
EncryptionTargetNotFound,
#[error("more than one element matched the encryption target")]
AmbiguousEncryptionTarget,
#[error("EncryptedData must declare Element or Content Type for document replacement")]
ReplacementRequiresXml,
#[error("RSA-OAEP key unwrap failed: {0}")]
Rsa(String),
#[error("RSA-OAEP key wrap failed: {0}")]
RsaEncrypt(String),
#[error("AES key unwrap failed integrity validation")]
KeyWrapIntegrity,
#[error("operating-system random number generation failed: {0}")]
Rng(String),
#[error("XML encryption serialization failed: {0}")]
XmlSerialize(String),
#[error("decrypted XML is not valid UTF-8: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
}
impl fmt::Display for DataEncryptionAlgorithm {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Aes128Cbc => "AES-128-CBC",
Self::Aes256Cbc => "AES-256-CBC",
Self::Aes128Gcm => "AES-128-GCM",
Self::Aes256Gcm => "AES-256-GCM",
})
}
}