Struct cryptographic_message_syntax::asn1::rfc5652::SignedData
source · pub struct SignedData {
pub version: CmsVersion,
pub digest_algorithms: DigestAlgorithmIdentifiers,
pub content_info: EncapsulatedContentInfo,
pub certificates: Option<CertificateSet>,
pub crls: Option<RevocationInfoChoices>,
pub signer_infos: SignerInfos,
}Expand description
Represents signed data.
ASN.1 type specification:
SignedData ::= SEQUENCE {
version CMSVersion,
digestAlgorithms DigestAlgorithmIdentifiers,
encapContentInfo EncapsulatedContentInfo,
certificates [0] IMPLICIT CertificateSet OPTIONAL,
crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
signerInfos SignerInfos }
Fields§
§version: CmsVersion§digest_algorithms: DigestAlgorithmIdentifiers§content_info: EncapsulatedContentInfo§certificates: Option<CertificateSet>§crls: Option<RevocationInfoChoices>§signer_infos: SignerInfosImplementations§
source§impl SignedData
impl SignedData
sourcepub fn decode_ber(data: &[u8]) -> Result<Self, DecodeError<Infallible>>
pub fn decode_ber(data: &[u8]) -> Result<Self, DecodeError<Infallible>>
Attempt to decode BER encoded bytes to a parsed data structure.
sourcepub fn decode<S: Source>(
cons: &mut Constructed<'_, S>
) -> Result<Self, DecodeError<S::Error>>
pub fn decode<S: Source>(
cons: &mut Constructed<'_, S>
) -> Result<Self, DecodeError<S::Error>>
Examples found in repository?
More examples
src/lib.rs (line 958)
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
fn try_from(signer_info: &crate::asn1::rfc5652::SignerInfo) -> Result<Self, Self::Error> {
let (issuer, serial_number) = match &signer_info.sid {
SignerIdentifier::IssuerAndSerialNumber(issuer) => {
(issuer.issuer.clone(), issuer.serial_number.clone())
}
SignerIdentifier::SubjectKeyIdentifier(_) => {
return Err(CmsError::SubjectKeyIdentifierUnsupported);
}
};
let digest_algorithm = DigestAlgorithm::try_from(&signer_info.digest_algorithm)?;
// The "signature" algorithm can also be a key algorithm identifier. So we
// attempt to resolve using the more robust mechanism.
let signature_algorithm = SignatureAlgorithm::from_oid_and_digest_algorithm(
&signer_info.signature_algorithm.algorithm,
digest_algorithm,
)?;
let signature = signer_info.signature.to_bytes().to_vec();
let signed_attributes = if let Some(attributes) = &signer_info.signed_attributes {
// Content type attribute MUST be present.
let content_type = attributes
.iter()
.find(|attr| attr.typ == OID_CONTENT_TYPE)
.ok_or(CmsError::MissingSignedAttributeContentType)?;
// Content type attribute MUST have exactly 1 value.
if content_type.values.len() != 1 {
return Err(CmsError::MalformedSignedAttributeContentType);
}
let content_type = content_type
.values
.get(0)
.unwrap()
.deref()
.clone()
.decode(|cons| Oid::take_from(cons))
.map_err(|_| CmsError::MalformedSignedAttributeContentType)?;
// Message digest attribute MUST be present.
let message_digest = attributes
.iter()
.find(|attr| attr.typ == OID_MESSAGE_DIGEST)
.ok_or(CmsError::MissingSignedAttributeMessageDigest)?;
// Message digest attribute MUST have exactly 1 value.
if message_digest.values.len() != 1 {
return Err(CmsError::MalformedSignedAttributeMessageDigest);
}
let message_digest = message_digest
.values
.get(0)
.unwrap()
.deref()
.clone()
.decode(|cons| OctetString::take_from(cons))
.map_err(|_| CmsError::MalformedSignedAttributeMessageDigest)?
.to_bytes()
.to_vec();
// Signing time is optional, but common. So we pull it out for convenience.
let signing_time = attributes
.iter()
.find(|attr| attr.typ == OID_SIGNING_TIME)
.map(|attr| {
if attr.values.len() != 1 {
Err(CmsError::MalformedSignedAttributeSigningTime)
} else {
let time = attr
.values
.get(0)
.unwrap()
.deref()
.clone()
.decode(|cons| Time::take_from(cons))?;
let time = chrono::DateTime::from(time);
Ok(time)
}
})
.transpose()?;
Some(SignedAttributes {
content_type,
message_digest,
signing_time,
raw: attributes.clone(),
})
} else {
None
};
let digested_signed_attributes_data = signer_info.signed_attributes_digested_content()?;
let unsigned_attributes =
if let Some(attributes) = &signer_info.unsigned_attributes {
let time_stamp_token =
attributes
.iter()
.find(|attr| attr.typ == OID_TIME_STAMP_TOKEN)
.map(|attr| {
if attr.values.len() != 1 {
Err(CmsError::MalformedUnsignedAttributeTimeStampToken)
} else {
Ok(attr.values.get(0).unwrap().deref().clone().decode(|cons| {
crate::asn1::rfc5652::SignedData::decode(cons)
})?)
}
})
.transpose()?;
Some(UnsignedAttributes { time_stamp_token })
} else {
None
};
Ok(SignerInfo {
issuer,
serial_number,
digest_algorithm,
signature_algorithm,
signature,
signed_attributes,
digested_signed_attributes_data,
unsigned_attributes,
})
}sourcepub fn take_from<S: Source>(
cons: &mut Constructed<'_, S>
) -> Result<Self, DecodeError<S::Error>>
pub fn take_from<S: Source>(
cons: &mut Constructed<'_, S>
) -> Result<Self, DecodeError<S::Error>>
Examples found in repository?
src/time_stamp_protocol.rs (line 117)
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
pub fn signed_data(&self) -> Result<Option<SignedData>, DecodeError<Infallible>> {
if let Some(token) = &self.0.time_stamp_token {
let source = token.content.clone();
if token.content_type == OID_ID_SIGNED_DATA {
Ok(Some(source.decode(|cons| SignedData::take_from(cons))?))
} else {
Err(source
.into_source()
.content_err("invalid OID on signed data"))
}
} else {
Ok(None)
}
}sourcepub fn encode_ref(&self) -> impl Values + '_
pub fn encode_ref(&self) -> impl Values + '_
Examples found in repository?
src/signing.rs (line 389)
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn build_der(&self) -> Result<Vec<u8>, CmsError> {
let mut signer_infos = SignerInfos::default();
let mut seen_digest_algorithms = HashSet::new();
let mut seen_certificates = self.certificates.clone();
for signer in &self.signers {
seen_digest_algorithms.insert(signer.digest_algorithm);
if !seen_certificates
.iter()
.any(|x| x == &signer.signing_certificate)
{
seen_certificates.push(signer.signing_certificate.clone());
}
let version = CmsVersion::V1;
let digest_algorithm = DigestAlgorithmIdentifier {
algorithm: signer.digest_algorithm.into(),
parameters: None,
};
let sid = SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
issuer: signer.signing_certificate.issuer_name().clone(),
serial_number: signer.signing_certificate.serial_number_asn1().clone(),
});
// The message digest attribute is mandatory.
//
// Message digest is computed from override content on the signer
// or the encapsulated content if present. The "empty" hash is a
// valid value if no content (only signed attributes) are being signed.
let mut hasher = signer.digest_algorithm.digester();
if let Some(content) = &signer.message_id_content {
hasher.update(content);
} else {
match &self.signed_content {
SignedContent::None => {}
SignedContent::Inline(content) | SignedContent::External(content) => {
hasher.update(content)
}
}
}
let digest = hasher.finish();
let mut signed_attributes = SignedAttributes::default();
// The content-type field is mandatory.
signed_attributes.push(Attribute {
typ: Oid(Bytes::copy_from_slice(OID_CONTENT_TYPE.as_ref())),
values: vec![AttributeValue::new(Captured::from_values(
Mode::Der,
signer.content_type.encode_ref(),
))],
});
// Set `messageDigest` field
signed_attributes.push(Attribute {
typ: Oid(Bytes::copy_from_slice(OID_MESSAGE_DIGEST.as_ref())),
values: vec![AttributeValue::new(Captured::from_values(
Mode::Der,
digest.as_ref().encode(),
))],
});
// Add signing time because it is common to include.
signed_attributes.push(Attribute {
typ: Oid(Bytes::copy_from_slice(OID_SIGNING_TIME.as_ref())),
values: vec![AttributeValue::new(Captured::from_values(
Mode::Der,
UtcTime::now().encode(),
))],
});
signed_attributes.extend(signer.extra_signed_attributes.iter().cloned());
// According to RFC 5652, signed attributes are DER encoded. This means a SET
// (which SignedAttributes is) should be sorted. But bcder doesn't appear to do
// this. So we manually sort here.
let signed_attributes = signed_attributes.as_sorted()?;
let signed_attributes = Some(signed_attributes);
let signature_algorithm = signer.signature_algorithm()?.into();
// The function for computing the signed attributes digested content
// is on SignerInfo. So construct an instance so we can compute the
// signature.
let mut signer_info = SignerInfo {
version,
sid,
digest_algorithm,
signed_attributes,
signature_algorithm,
signature: SignatureValue::new(Bytes::copy_from_slice(&[])),
unsigned_attributes: None,
signed_attributes_data: None,
};
// The content being signed is the DER encoded signed attributes, if present, or the
// encapsulated content. Since we always create signed attributes above, it *must* be
// the DER encoded signed attributes.
let signed_content = signer_info
.signed_attributes_digested_content()?
.expect("presence of signed attributes should ensure this is Some(T)");
let signature = signer.signing_key.try_sign(&signed_content)?;
let signature_algorithm = signer.signing_key.signature_algorithm()?;
signer_info.signature = SignatureValue::new(Bytes::from(signature.clone()));
signer_info.signature_algorithm = signature_algorithm.into();
if let Some(url) = &signer.time_stamp_url {
// The message sent to the TSA (via a digest) is the signature of the signed data.
let res = time_stamp_message_http(
url.clone(),
signature.as_ref(),
signer.digest_algorithm,
)?;
if !res.is_success() {
return Err(TimeStampError::Unsuccessful(res.clone()).into());
}
let signed_data = res
.signed_data()?
.ok_or(CmsError::TimeStampProtocol(TimeStampError::BadResponse))?;
let mut unsigned_attributes = UnsignedAttributes::default();
unsigned_attributes.push(Attribute {
typ: Oid(Bytes::copy_from_slice(OID_TIME_STAMP_TOKEN.as_ref())),
values: vec![AttributeValue::new(Captured::from_values(
Mode::Der,
signed_data.encode_ref(),
))],
});
signer_info.unsigned_attributes = Some(unsigned_attributes);
}
signer_infos.push(signer_info);
}
let mut digest_algorithms = DigestAlgorithmIdentifiers::default();
digest_algorithms.extend(seen_digest_algorithms.into_iter().map(|alg| {
DigestAlgorithmIdentifier {
algorithm: alg.into(),
parameters: None,
}
}));
// Many consumers prefer the issuing certificate to come before the issued
// certificate. So we explicitly sort all the seen certificates in this order,
// attempting for all issuing certificates to come before the issued.
seen_certificates.sort_by(|a, b| a.compare_issuer(b));
let mut certificates = CertificateSet::default();
certificates.extend(
seen_certificates
.into_iter()
.map(|cert| CertificateChoices::Certificate(Box::new(cert.into()))),
);
// The certificates could have been encountered in any order. For best results,
// we want issuer certificates before their "children." So we apply sorting here.
let signed_data = SignedData {
version: CmsVersion::V1,
digest_algorithms,
content_info: EncapsulatedContentInfo {
content_type: self.content_type.clone(),
content: match &self.signed_content {
SignedContent::None | SignedContent::External(_) => None,
SignedContent::Inline(content) => {
Some(OctetString::new(Bytes::copy_from_slice(content)))
}
},
},
certificates: if certificates.is_empty() {
None
} else {
Some(certificates)
},
crls: None,
signer_infos,
};
let mut ber = Vec::new();
signed_data
.encode_ref()
.write_encoded(Mode::Der, &mut ber)?;
Ok(ber)
}Trait Implementations§
source§impl Clone for SignedData
impl Clone for SignedData
source§fn clone(&self) -> SignedData
fn clone(&self) -> SignedData
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moresource§impl Debug for SignedData
impl Debug for SignedData
source§impl PartialEq<SignedData> for SignedData
impl PartialEq<SignedData> for SignedData
source§fn eq(&self, other: &SignedData) -> bool
fn eq(&self, other: &SignedData) -> bool
This method tests for
self and other values to be equal, and is used
by ==.source§impl TryFrom<&SignedData> for SignedData
impl TryFrom<&SignedData> for SignedData
impl Eq for SignedData
impl StructuralEq for SignedData
impl StructuralPartialEq for SignedData
Auto Trait Implementations§
impl RefUnwindSafe for SignedData
impl Send for SignedData
impl Sync for SignedData
impl Unpin for SignedData
impl UnwindSafe for SignedData
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key and return true if they are equal.