SignerInformation.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  14. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  15. using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
  16. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
  17. {
  18. /**
  19. * an expanded SignerInfo block from a CMS Signed message
  20. */
  21. public class SignerInformation
  22. {
  23. private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
  24. private SignerID sid;
  25. private CmsProcessable content;
  26. private byte[] signature;
  27. private DerObjectIdentifier contentType;
  28. private byte[] calculatedDigest;
  29. private byte[] resultDigest;
  30. // Derived
  31. private Asn1.Cms.AttributeTable signedAttributeTable;
  32. private Asn1.Cms.AttributeTable unsignedAttributeTable;
  33. private readonly bool isCounterSignature;
  34. protected SignerInfo info;
  35. protected AlgorithmIdentifier digestAlgorithm;
  36. protected AlgorithmIdentifier encryptionAlgorithm;
  37. protected readonly Asn1Set signedAttributeSet;
  38. protected readonly Asn1Set unsignedAttributeSet;
  39. internal SignerInformation(
  40. SignerInfo info,
  41. DerObjectIdentifier contentType,
  42. CmsProcessable content,
  43. IDigestCalculator digestCalculator)
  44. {
  45. this.info = info;
  46. this.sid = new SignerID();
  47. this.contentType = contentType;
  48. this.isCounterSignature = contentType == null;
  49. try
  50. {
  51. SignerIdentifier s = info.SignerID;
  52. if (s.IsTagged)
  53. {
  54. Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID);
  55. sid.SubjectKeyIdentifier = octs.GetEncoded();
  56. }
  57. else
  58. {
  59. Asn1.Cms.IssuerAndSerialNumber iAnds =
  60. Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID);
  61. sid.Issuer = iAnds.Name;
  62. sid.SerialNumber = iAnds.SerialNumber.Value;
  63. }
  64. }
  65. catch (IOException)
  66. {
  67. throw new ArgumentException("invalid sid in SignerInfo");
  68. }
  69. this.digestAlgorithm = info.DigestAlgorithm;
  70. this.signedAttributeSet = info.AuthenticatedAttributes;
  71. this.unsignedAttributeSet = info.UnauthenticatedAttributes;
  72. this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
  73. this.signature = (byte[])info.EncryptedDigest.GetOctets().Clone();
  74. this.content = content;
  75. this.calculatedDigest = (digestCalculator != null) ? digestCalculator.GetDigest() : null;
  76. }
  77. /**
  78. * Protected constructor. In some cases clients have their own idea about how to encode
  79. * the signed attributes and calculate the signature. This constructor is to allow developers
  80. * to deal with that by extending off the class and overriding e.g. SignedAttributes property.
  81. *
  82. * @param baseInfo the SignerInformation to base this one on.
  83. */
  84. protected SignerInformation(SignerInformation baseInfo)
  85. {
  86. this.info = baseInfo.info;
  87. this.content = baseInfo.content;
  88. this.contentType = baseInfo.contentType;
  89. this.isCounterSignature = baseInfo.IsCounterSignature;
  90. this.sid = baseInfo.sid;
  91. this.digestAlgorithm = info.DigestAlgorithm;
  92. this.signedAttributeSet = info.AuthenticatedAttributes;
  93. this.unsignedAttributeSet = info.UnauthenticatedAttributes;
  94. this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
  95. this.signature = (byte[])info.EncryptedDigest.GetOctets().Clone();
  96. this.calculatedDigest = baseInfo.calculatedDigest;
  97. this.signedAttributeTable = baseInfo.signedAttributeTable;
  98. this.unsignedAttributeTable = baseInfo.unsignedAttributeTable;
  99. }
  100. public bool IsCounterSignature
  101. {
  102. get { return isCounterSignature; }
  103. }
  104. public DerObjectIdentifier ContentType
  105. {
  106. get { return contentType; }
  107. }
  108. public SignerID SignerID
  109. {
  110. get { return sid; }
  111. }
  112. /**
  113. * return the version number for this objects underlying SignerInfo structure.
  114. */
  115. public int Version
  116. {
  117. get { return info.Version.IntValueExact; }
  118. }
  119. public AlgorithmIdentifier DigestAlgorithmID
  120. {
  121. get { return digestAlgorithm; }
  122. }
  123. /**
  124. * return the object identifier for the signature.
  125. */
  126. public string DigestAlgOid
  127. {
  128. get { return digestAlgorithm.Algorithm.Id; }
  129. }
  130. /**
  131. * return the signature parameters, or null if there aren't any.
  132. */
  133. public Asn1Object DigestAlgParams
  134. {
  135. get
  136. {
  137. Asn1Encodable ae = digestAlgorithm.Parameters;
  138. return ae == null ? null : ae.ToAsn1Object();
  139. }
  140. }
  141. /**
  142. * return the content digest that was calculated during verification.
  143. */
  144. public byte[] GetContentDigest()
  145. {
  146. if (resultDigest == null)
  147. {
  148. throw new InvalidOperationException("method can only be called after verify.");
  149. }
  150. return (byte[])resultDigest.Clone();
  151. }
  152. public AlgorithmIdentifier EncryptionAlgorithmID
  153. {
  154. get { return encryptionAlgorithm; }
  155. }
  156. /**
  157. * return the object identifier for the signature.
  158. */
  159. public string EncryptionAlgOid
  160. {
  161. get { return encryptionAlgorithm.Algorithm.Id; }
  162. }
  163. /**
  164. * return the signature/encryption algorithm parameters, or null if
  165. * there aren't any.
  166. */
  167. public Asn1Object EncryptionAlgParams
  168. {
  169. get
  170. {
  171. Asn1Encodable ae = encryptionAlgorithm.Parameters;
  172. return ae == null ? null : ae.ToAsn1Object();
  173. }
  174. }
  175. /**
  176. * return a table of the signed attributes - indexed by
  177. * the OID of the attribute.
  178. */
  179. public Asn1.Cms.AttributeTable SignedAttributes
  180. {
  181. get
  182. {
  183. if (signedAttributeSet != null && signedAttributeTable == null)
  184. {
  185. signedAttributeTable = new Asn1.Cms.AttributeTable(signedAttributeSet);
  186. }
  187. return signedAttributeTable;
  188. }
  189. }
  190. /**
  191. * return a table of the unsigned attributes indexed by
  192. * the OID of the attribute.
  193. */
  194. public Asn1.Cms.AttributeTable UnsignedAttributes
  195. {
  196. get
  197. {
  198. if (unsignedAttributeSet != null && unsignedAttributeTable == null)
  199. {
  200. unsignedAttributeTable = new Asn1.Cms.AttributeTable(unsignedAttributeSet);
  201. }
  202. return unsignedAttributeTable;
  203. }
  204. }
  205. /**
  206. * return the encoded signature
  207. */
  208. public byte[] GetSignature()
  209. {
  210. return (byte[]) signature.Clone();
  211. }
  212. /**
  213. * Return a SignerInformationStore containing the counter signatures attached to this
  214. * signer. If no counter signatures are present an empty store is returned.
  215. */
  216. public SignerInformationStore GetCounterSignatures()
  217. {
  218. // TODO There are several checks implied by the RFC3852 comments that are missing
  219. /*
  220. The countersignature attribute MUST be an unsigned attribute; it MUST
  221. NOT be a signed attribute, an authenticated attribute, an
  222. unauthenticated attribute, or an unprotected attribute.
  223. */
  224. Asn1.Cms.AttributeTable unsignedAttributeTable = UnsignedAttributes;
  225. if (unsignedAttributeTable == null)
  226. {
  227. return new SignerInformationStore(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(0));
  228. }
  229. IList counterSignatures = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  230. /*
  231. The UnsignedAttributes syntax is defined as a SET OF Attributes. The
  232. UnsignedAttributes in a signerInfo may include multiple instances of
  233. the countersignature attribute.
  234. */
  235. Asn1EncodableVector allCSAttrs = unsignedAttributeTable.GetAll(CmsAttributes.CounterSignature);
  236. foreach (Asn1.Cms.Attribute counterSignatureAttribute in allCSAttrs)
  237. {
  238. /*
  239. A countersignature attribute can have multiple attribute values. The
  240. syntax is defined as a SET OF AttributeValue, and there MUST be one
  241. or more instances of AttributeValue present.
  242. */
  243. Asn1Set values = counterSignatureAttribute.AttrValues;
  244. if (values.Count < 1)
  245. {
  246. // TODO Throw an appropriate exception?
  247. }
  248. foreach (Asn1Encodable asn1Obj in values)
  249. {
  250. /*
  251. Countersignature values have the same meaning as SignerInfo values
  252. for ordinary signatures, except that:
  253. 1. The signedAttributes field MUST NOT contain a content-type
  254. attribute; there is no content type for countersignatures.
  255. 2. The signedAttributes field MUST contain a message-digest
  256. attribute if it contains any other attributes.
  257. 3. The input to the message-digesting process is the contents
  258. octets of the DER encoding of the signatureValue field of the
  259. SignerInfo value with which the attribute is associated.
  260. */
  261. SignerInfo si = SignerInfo.GetInstance(asn1Obj.ToAsn1Object());
  262. string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.Algorithm.Id);
  263. counterSignatures.Add(new SignerInformation(si, null, null, new CounterSignatureDigestCalculator(digestName, GetSignature())));
  264. }
  265. }
  266. return new SignerInformationStore(counterSignatures);
  267. }
  268. /**
  269. * return the DER encoding of the signed attributes.
  270. * @throws IOException if an encoding error occurs.
  271. */
  272. public virtual byte[] GetEncodedSignedAttributes()
  273. {
  274. return signedAttributeSet == null
  275. ? null
  276. : signedAttributeSet.GetEncoded(Asn1Encodable.Der);
  277. }
  278. private bool DoVerify(
  279. AsymmetricKeyParameter key)
  280. {
  281. DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.Algorithm;
  282. Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters;
  283. string digestName = Helper.GetDigestAlgName(this.EncryptionAlgOid);
  284. if (digestName.Equals(sigAlgOid.Id))
  285. {
  286. digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
  287. }
  288. IDigest digest = Helper.GetDigestInstance(digestName);
  289. ISigner sig;
  290. if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
  291. {
  292. // RFC 4056 2.2
  293. // When the id-RSASSA-PSS algorithm identifier is used for a signature,
  294. // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
  295. if (sigParams == null)
  296. throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
  297. try
  298. {
  299. // TODO Provide abstract configuration mechanism
  300. // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)
  301. Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
  302. sigParams.ToAsn1Object());
  303. if (!pss.HashAlgorithm.Algorithm.Equals(this.digestAlgorithm.Algorithm))
  304. throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
  305. if (!pss.MaskGenAlgorithm.Algorithm.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
  306. throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
  307. IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.Algorithm);
  308. int saltLength = pss.SaltLength.IntValueExact;
  309. // RFC 4055 3.1
  310. // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
  311. if (!Asn1.Pkcs.RsassaPssParameters.DefaultTrailerField.Equals(pss.TrailerField))
  312. throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
  313. IAsymmetricBlockCipher rsa = new RsaBlindedEngine();
  314. if (signedAttributeSet == null && calculatedDigest != null)
  315. {
  316. sig = PssSigner.CreateRawSigner(rsa, pssDigest, pssDigest, saltLength, PssSigner.TrailerImplicit);
  317. }
  318. else
  319. {
  320. sig = new PssSigner(rsa, pssDigest, saltLength);
  321. }
  322. }
  323. catch (Exception e)
  324. {
  325. throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
  326. }
  327. }
  328. else
  329. {
  330. // TODO Probably too strong a check at the moment
  331. // if (sigParams != null)
  332. // throw new CmsException("unrecognised signature parameters provided");
  333. string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
  334. sig = Helper.GetSignatureInstance(signatureName);
  335. //sig = Helper.GetSignatureInstance(this.EncryptionAlgOid);
  336. //sig = SignerUtilities.GetSigner(sigAlgOid);
  337. }
  338. try
  339. {
  340. if (calculatedDigest != null)
  341. {
  342. resultDigest = calculatedDigest;
  343. }
  344. else
  345. {
  346. if (content != null)
  347. {
  348. content.Write(new DigestSink(digest));
  349. }
  350. else if (signedAttributeSet == null)
  351. {
  352. // TODO Get rid of this exception and just treat content==null as empty not missing?
  353. throw new CmsException("data not encapsulated in signature - use detached constructor.");
  354. }
  355. resultDigest = DigestUtilities.DoFinal(digest);
  356. }
  357. }
  358. catch (IOException e)
  359. {
  360. throw new CmsException("can't process mime object to create signature.", e);
  361. }
  362. // RFC 3852 11.1 Check the content-type attribute is correct
  363. {
  364. Asn1Object validContentType = GetSingleValuedSignedAttribute(
  365. CmsAttributes.ContentType, "content-type");
  366. if (validContentType == null)
  367. {
  368. if (!isCounterSignature && signedAttributeSet != null)
  369. throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
  370. }
  371. else
  372. {
  373. if (isCounterSignature)
  374. throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
  375. if (!(validContentType is DerObjectIdentifier))
  376. throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
  377. DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;
  378. if (!signedContentType.Equals(contentType))
  379. throw new CmsException("content-type attribute value does not match eContentType");
  380. }
  381. }
  382. // RFC 3852 11.2 Check the message-digest attribute is correct
  383. {
  384. Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
  385. CmsAttributes.MessageDigest, "message-digest");
  386. if (validMessageDigest == null)
  387. {
  388. if (signedAttributeSet != null)
  389. throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
  390. }
  391. else
  392. {
  393. if (!(validMessageDigest is Asn1OctetString))
  394. {
  395. throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
  396. }
  397. Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;
  398. if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
  399. throw new CmsException("message-digest attribute value does not match calculated value");
  400. }
  401. }
  402. // RFC 3852 11.4 Validate countersignature attribute(s)
  403. {
  404. Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
  405. if (signedAttrTable != null
  406. && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
  407. {
  408. throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
  409. }
  410. Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
  411. if (unsignedAttrTable != null)
  412. {
  413. foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
  414. {
  415. if (csAttr.AttrValues.Count < 1)
  416. throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
  417. // Note: We don't recursively validate the countersignature value
  418. }
  419. }
  420. }
  421. try
  422. {
  423. sig.Init(false, key);
  424. if (signedAttributeSet == null)
  425. {
  426. if (calculatedDigest != null)
  427. {
  428. if (sig is PssSigner)
  429. {
  430. sig.BlockUpdate(resultDigest, 0, resultDigest.Length);
  431. }
  432. else
  433. {
  434. // need to decrypt signature and check message bytes
  435. return VerifyDigest(resultDigest, key, this.GetSignature());
  436. }
  437. }
  438. else if (content != null)
  439. {
  440. try
  441. {
  442. // TODO Use raw signature of the hash value instead
  443. content.Write(new SignerSink(sig));
  444. }
  445. catch (SignatureException e)
  446. {
  447. throw new CmsStreamException("signature problem: " + e);
  448. }
  449. }
  450. }
  451. else
  452. {
  453. byte[] tmp = this.GetEncodedSignedAttributes();
  454. sig.BlockUpdate(tmp, 0, tmp.Length);
  455. }
  456. return sig.VerifySignature(this.GetSignature());
  457. }
  458. catch (InvalidKeyException e)
  459. {
  460. throw new CmsException("key not appropriate to signature in message.", e);
  461. }
  462. catch (IOException e)
  463. {
  464. throw new CmsException("can't process mime object to create signature.", e);
  465. }
  466. catch (SignatureException e)
  467. {
  468. throw new CmsException("invalid signature format in message: " + e.Message, e);
  469. }
  470. }
  471. private bool IsNull(
  472. Asn1Encodable o)
  473. {
  474. return (o is Asn1Null) || (o == null);
  475. }
  476. private DigestInfo DerDecode(
  477. byte[] encoding)
  478. {
  479. if (encoding[0] != (int)(Asn1Tags.Constructed | Asn1Tags.Sequence))
  480. {
  481. throw new IOException("not a digest info object");
  482. }
  483. DigestInfo digInfo = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));
  484. // length check to avoid Bleichenbacher vulnerability
  485. if (digInfo.GetEncoded().Length != encoding.Length)
  486. {
  487. throw new CmsException("malformed RSA signature");
  488. }
  489. return digInfo;
  490. }
  491. private bool VerifyDigest(
  492. byte[] digest,
  493. AsymmetricKeyParameter key,
  494. byte[] signature)
  495. {
  496. string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
  497. try
  498. {
  499. if (algorithm.Equals("RSA"))
  500. {
  501. IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");
  502. c.Init(false, key);
  503. byte[] decrypt = c.DoFinal(signature);
  504. DigestInfo digInfo = DerDecode(decrypt);
  505. if (!digInfo.AlgorithmID.Algorithm.Equals(digestAlgorithm.Algorithm))
  506. {
  507. return false;
  508. }
  509. if (!IsNull(digInfo.AlgorithmID.Parameters))
  510. {
  511. return false;
  512. }
  513. byte[] sigHash = digInfo.GetDigest();
  514. return Arrays.ConstantTimeAreEqual(digest, sigHash);
  515. }
  516. else if (algorithm.Equals("DSA"))
  517. {
  518. ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");
  519. sig.Init(false, key);
  520. sig.BlockUpdate(digest, 0, digest.Length);
  521. return sig.VerifySignature(signature);
  522. }
  523. else
  524. {
  525. throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
  526. }
  527. }
  528. catch (SecurityUtilityException e)
  529. {
  530. throw e;
  531. }
  532. catch (GeneralSecurityException e)
  533. {
  534. throw new CmsException("Exception processing signature: " + e, e);
  535. }
  536. catch (IOException e)
  537. {
  538. throw new CmsException("Exception decoding signature: " + e, e);
  539. }
  540. }
  541. /**
  542. * verify that the given public key successfully handles and confirms the
  543. * signature associated with this signer.
  544. */
  545. public bool Verify(
  546. AsymmetricKeyParameter pubKey)
  547. {
  548. if (pubKey.IsPrivate)
  549. throw new ArgumentException("Expected public key", "pubKey");
  550. // Optional, but still need to validate if present
  551. GetSigningTime();
  552. return DoVerify(pubKey);
  553. }
  554. /**
  555. * verify that the given certificate successfully handles and confirms
  556. * the signature associated with this signer and, if a signingTime
  557. * attribute is available, that the certificate was valid at the time the
  558. * signature was generated.
  559. */
  560. public bool Verify(
  561. X509Certificate cert)
  562. {
  563. Asn1.Cms.Time signingTime = GetSigningTime();
  564. if (signingTime != null)
  565. {
  566. cert.CheckValidity(signingTime.Date);
  567. }
  568. return DoVerify(cert.GetPublicKey());
  569. }
  570. /**
  571. * Return the base ASN.1 CMS structure that this object contains.
  572. *
  573. * @return an object containing a CMS SignerInfo structure.
  574. */
  575. public SignerInfo ToSignerInfo()
  576. {
  577. return info;
  578. }
  579. private Asn1Object GetSingleValuedSignedAttribute(
  580. DerObjectIdentifier attrOID, string printableName)
  581. {
  582. Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
  583. if (unsignedAttrTable != null
  584. && unsignedAttrTable.GetAll(attrOID).Count > 0)
  585. {
  586. throw new CmsException("The " + printableName
  587. + " attribute MUST NOT be an unsigned attribute");
  588. }
  589. Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
  590. if (signedAttrTable == null)
  591. {
  592. return null;
  593. }
  594. Asn1EncodableVector v = signedAttrTable.GetAll(attrOID);
  595. switch (v.Count)
  596. {
  597. case 0:
  598. return null;
  599. case 1:
  600. Asn1.Cms.Attribute t = (Asn1.Cms.Attribute) v[0];
  601. Asn1Set attrValues = t.AttrValues;
  602. if (attrValues.Count != 1)
  603. throw new CmsException("A " + printableName
  604. + " attribute MUST have a single attribute value");
  605. return attrValues[0].ToAsn1Object();
  606. default:
  607. throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the "
  608. + printableName + " attribute");
  609. }
  610. }
  611. private Asn1.Cms.Time GetSigningTime()
  612. {
  613. Asn1Object validSigningTime = GetSingleValuedSignedAttribute(
  614. CmsAttributes.SigningTime, "signing-time");
  615. if (validSigningTime == null)
  616. return null;
  617. try
  618. {
  619. return Asn1.Cms.Time.GetInstance(validSigningTime);
  620. }
  621. catch (ArgumentException)
  622. {
  623. throw new CmsException("signing-time attribute value not a valid 'Time' structure");
  624. }
  625. }
  626. /**
  627. * Return a signer information object with the passed in unsigned
  628. * attributes replacing the ones that are current associated with
  629. * the object passed in.
  630. *
  631. * @param signerInformation the signerInfo to be used as the basis.
  632. * @param unsignedAttributes the unsigned attributes to add.
  633. * @return a copy of the original SignerInformationObject with the changed attributes.
  634. */
  635. public static SignerInformation ReplaceUnsignedAttributes(
  636. SignerInformation signerInformation,
  637. Asn1.Cms.AttributeTable unsignedAttributes)
  638. {
  639. SignerInfo sInfo = signerInformation.info;
  640. Asn1Set unsignedAttr = null;
  641. if (unsignedAttributes != null)
  642. {
  643. unsignedAttr = new DerSet(unsignedAttributes.ToAsn1EncodableVector());
  644. }
  645. return new SignerInformation(
  646. new SignerInfo(
  647. sInfo.SignerID,
  648. sInfo.DigestAlgorithm,
  649. sInfo.AuthenticatedAttributes,
  650. sInfo.DigestEncryptionAlgorithm,
  651. sInfo.EncryptedDigest,
  652. unsignedAttr),
  653. signerInformation.contentType,
  654. signerInformation.content,
  655. null);
  656. }
  657. /**
  658. * Return a signer information object with passed in SignerInformationStore representing counter
  659. * signatures attached as an unsigned attribute.
  660. *
  661. * @param signerInformation the signerInfo to be used as the basis.
  662. * @param counterSigners signer info objects carrying counter signature.
  663. * @return a copy of the original SignerInformationObject with the changed attributes.
  664. */
  665. public static SignerInformation AddCounterSigners(
  666. SignerInformation signerInformation,
  667. SignerInformationStore counterSigners)
  668. {
  669. // TODO Perform checks from RFC 3852 11.4
  670. SignerInfo sInfo = signerInformation.info;
  671. Asn1.Cms.AttributeTable unsignedAttr = signerInformation.UnsignedAttributes;
  672. Asn1EncodableVector v;
  673. if (unsignedAttr != null)
  674. {
  675. v = unsignedAttr.ToAsn1EncodableVector();
  676. }
  677. else
  678. {
  679. v = new Asn1EncodableVector();
  680. }
  681. Asn1EncodableVector sigs = new Asn1EncodableVector();
  682. foreach (SignerInformation sigInf in counterSigners.GetSigners())
  683. {
  684. sigs.Add(sigInf.ToSignerInfo());
  685. }
  686. v.Add(new Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(sigs)));
  687. return new SignerInformation(
  688. new SignerInfo(
  689. sInfo.SignerID,
  690. sInfo.DigestAlgorithm,
  691. sInfo.AuthenticatedAttributes,
  692. sInfo.DigestEncryptionAlgorithm,
  693. sInfo.EncryptedDigest,
  694. new DerSet(v)),
  695. signerInformation.contentType,
  696. signerInformation.content,
  697. null);
  698. }
  699. }
  700. }
  701. #pragma warning restore
  702. #endif