SignerInformation.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  10. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
  13. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  14. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  15. using Best.HTTP.SecureProtocol.Org.BouncyCastle.X509;
  16. namespace Best.HTTP.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(new List<SignerInformation>(0));
  228. }
  229. var counterSignatures = new List<SignerInformation>();
  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 signedContentType))
  376. throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
  377. if (!signedContentType.Equals(contentType))
  378. throw new CmsException("content-type attribute value does not match eContentType");
  379. }
  380. }
  381. // RFC 3852 11.2 Check the message-digest attribute is correct
  382. {
  383. Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
  384. CmsAttributes.MessageDigest, "message-digest");
  385. if (validMessageDigest == null)
  386. {
  387. if (signedAttributeSet != null)
  388. throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
  389. }
  390. else
  391. {
  392. if (!(validMessageDigest is Asn1OctetString signedMessageDigest))
  393. throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
  394. if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
  395. throw new CmsException("message-digest attribute value does not match calculated value");
  396. }
  397. }
  398. // RFC 3852 11.4 Validate countersignature attribute(s)
  399. {
  400. Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
  401. if (signedAttrTable != null
  402. && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
  403. {
  404. throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
  405. }
  406. Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
  407. if (unsignedAttrTable != null)
  408. {
  409. foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
  410. {
  411. if (csAttr.AttrValues.Count < 1)
  412. throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
  413. // Note: We don't recursively validate the countersignature value
  414. }
  415. }
  416. }
  417. try
  418. {
  419. sig.Init(false, key);
  420. if (signedAttributeSet == null)
  421. {
  422. if (calculatedDigest != null)
  423. {
  424. if (sig is PssSigner)
  425. {
  426. sig.BlockUpdate(resultDigest, 0, resultDigest.Length);
  427. }
  428. else
  429. {
  430. // need to decrypt signature and check message bytes
  431. return VerifyDigest(resultDigest, key, this.GetSignature());
  432. }
  433. }
  434. else if (content != null)
  435. {
  436. try
  437. {
  438. // TODO Use raw signature of the hash value instead
  439. content.Write(new SignerSink(sig));
  440. }
  441. catch (SignatureException e)
  442. {
  443. throw new CmsStreamException("signature problem: " + e);
  444. }
  445. }
  446. }
  447. else
  448. {
  449. byte[] tmp = this.GetEncodedSignedAttributes();
  450. sig.BlockUpdate(tmp, 0, tmp.Length);
  451. }
  452. return sig.VerifySignature(this.GetSignature());
  453. }
  454. catch (InvalidKeyException e)
  455. {
  456. throw new CmsException("key not appropriate to signature in message.", e);
  457. }
  458. catch (IOException e)
  459. {
  460. throw new CmsException("can't process mime object to create signature.", e);
  461. }
  462. catch (SignatureException e)
  463. {
  464. throw new CmsException("invalid signature format in message: " + e.Message, e);
  465. }
  466. }
  467. private bool IsNull(
  468. Asn1Encodable o)
  469. {
  470. return (o is Asn1Null) || (o == null);
  471. }
  472. private DigestInfo DerDecode(
  473. byte[] encoding)
  474. {
  475. if (encoding[0] != (int)(Asn1Tags.Constructed | Asn1Tags.Sequence))
  476. {
  477. throw new IOException("not a digest info object");
  478. }
  479. DigestInfo digInfo = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));
  480. // length check to avoid Bleichenbacher vulnerability
  481. if (digInfo.GetEncoded().Length != encoding.Length)
  482. {
  483. throw new CmsException("malformed RSA signature");
  484. }
  485. return digInfo;
  486. }
  487. private bool VerifyDigest(
  488. byte[] digest,
  489. AsymmetricKeyParameter key,
  490. byte[] signature)
  491. {
  492. string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
  493. try
  494. {
  495. if (algorithm.Equals("RSA"))
  496. {
  497. IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");
  498. c.Init(false, key);
  499. byte[] decrypt = c.DoFinal(signature);
  500. DigestInfo digInfo = DerDecode(decrypt);
  501. if (!digInfo.AlgorithmID.Algorithm.Equals(digestAlgorithm.Algorithm))
  502. {
  503. return false;
  504. }
  505. if (!IsNull(digInfo.AlgorithmID.Parameters))
  506. {
  507. return false;
  508. }
  509. byte[] sigHash = digInfo.GetDigest();
  510. return Arrays.ConstantTimeAreEqual(digest, sigHash);
  511. }
  512. else if (algorithm.Equals("DSA"))
  513. {
  514. ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");
  515. sig.Init(false, key);
  516. sig.BlockUpdate(digest, 0, digest.Length);
  517. return sig.VerifySignature(signature);
  518. }
  519. else
  520. {
  521. throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
  522. }
  523. }
  524. catch (SecurityUtilityException e)
  525. {
  526. throw e;
  527. }
  528. catch (GeneralSecurityException e)
  529. {
  530. throw new CmsException("Exception processing signature: " + e, e);
  531. }
  532. catch (IOException e)
  533. {
  534. throw new CmsException("Exception decoding signature: " + e, e);
  535. }
  536. }
  537. /**
  538. * verify that the given public key successfully handles and confirms the
  539. * signature associated with this signer.
  540. */
  541. public bool Verify(
  542. AsymmetricKeyParameter pubKey)
  543. {
  544. if (pubKey.IsPrivate)
  545. throw new ArgumentException("Expected public key", "pubKey");
  546. // Optional, but still need to validate if present
  547. GetSigningTime();
  548. return DoVerify(pubKey);
  549. }
  550. /**
  551. * verify that the given certificate successfully handles and confirms
  552. * the signature associated with this signer and, if a signingTime
  553. * attribute is available, that the certificate was valid at the time the
  554. * signature was generated.
  555. */
  556. public bool Verify(
  557. X509Certificate cert)
  558. {
  559. Asn1.Cms.Time signingTime = GetSigningTime();
  560. if (signingTime != null)
  561. {
  562. cert.CheckValidity(signingTime.ToDateTime());
  563. }
  564. return DoVerify(cert.GetPublicKey());
  565. }
  566. /**
  567. * Return the base ASN.1 CMS structure that this object contains.
  568. *
  569. * @return an object containing a CMS SignerInfo structure.
  570. */
  571. public SignerInfo ToSignerInfo()
  572. {
  573. return info;
  574. }
  575. private Asn1Object GetSingleValuedSignedAttribute(
  576. DerObjectIdentifier attrOID, string printableName)
  577. {
  578. Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
  579. if (unsignedAttrTable != null
  580. && unsignedAttrTable.GetAll(attrOID).Count > 0)
  581. {
  582. throw new CmsException("The " + printableName
  583. + " attribute MUST NOT be an unsigned attribute");
  584. }
  585. Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
  586. if (signedAttrTable == null)
  587. {
  588. return null;
  589. }
  590. Asn1EncodableVector v = signedAttrTable.GetAll(attrOID);
  591. switch (v.Count)
  592. {
  593. case 0:
  594. return null;
  595. case 1:
  596. Asn1.Cms.Attribute t = (Asn1.Cms.Attribute) v[0];
  597. Asn1Set attrValues = t.AttrValues;
  598. if (attrValues.Count != 1)
  599. throw new CmsException("A " + printableName
  600. + " attribute MUST have a single attribute value");
  601. return attrValues[0].ToAsn1Object();
  602. default:
  603. throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the "
  604. + printableName + " attribute");
  605. }
  606. }
  607. private Asn1.Cms.Time GetSigningTime()
  608. {
  609. Asn1Object validSigningTime = GetSingleValuedSignedAttribute(
  610. CmsAttributes.SigningTime, "signing-time");
  611. if (validSigningTime == null)
  612. return null;
  613. try
  614. {
  615. return Asn1.Cms.Time.GetInstance(validSigningTime);
  616. }
  617. catch (ArgumentException)
  618. {
  619. throw new CmsException("signing-time attribute value not a valid 'Time' structure");
  620. }
  621. }
  622. /**
  623. * Return a signer information object with the passed in unsigned
  624. * attributes replacing the ones that are current associated with
  625. * the object passed in.
  626. *
  627. * @param signerInformation the signerInfo to be used as the basis.
  628. * @param unsignedAttributes the unsigned attributes to add.
  629. * @return a copy of the original SignerInformationObject with the changed attributes.
  630. */
  631. public static SignerInformation ReplaceUnsignedAttributes(
  632. SignerInformation signerInformation,
  633. Asn1.Cms.AttributeTable unsignedAttributes)
  634. {
  635. SignerInfo sInfo = signerInformation.info;
  636. Asn1Set unsignedAttr = null;
  637. if (unsignedAttributes != null)
  638. {
  639. unsignedAttr = new DerSet(unsignedAttributes.ToAsn1EncodableVector());
  640. }
  641. return new SignerInformation(
  642. new SignerInfo(
  643. sInfo.SignerID,
  644. sInfo.DigestAlgorithm,
  645. sInfo.AuthenticatedAttributes,
  646. sInfo.DigestEncryptionAlgorithm,
  647. sInfo.EncryptedDigest,
  648. unsignedAttr),
  649. signerInformation.contentType,
  650. signerInformation.content,
  651. null);
  652. }
  653. /**
  654. * Return a signer information object with passed in SignerInformationStore representing counter
  655. * signatures attached as an unsigned attribute.
  656. *
  657. * @param signerInformation the signerInfo to be used as the basis.
  658. * @param counterSigners signer info objects carrying counter signature.
  659. * @return a copy of the original SignerInformationObject with the changed attributes.
  660. */
  661. public static SignerInformation AddCounterSigners(
  662. SignerInformation signerInformation,
  663. SignerInformationStore counterSigners)
  664. {
  665. // TODO Perform checks from RFC 3852 11.4
  666. SignerInfo sInfo = signerInformation.info;
  667. Asn1.Cms.AttributeTable unsignedAttr = signerInformation.UnsignedAttributes;
  668. Asn1EncodableVector v;
  669. if (unsignedAttr != null)
  670. {
  671. v = unsignedAttr.ToAsn1EncodableVector();
  672. }
  673. else
  674. {
  675. v = new Asn1EncodableVector();
  676. }
  677. Asn1EncodableVector sigs = new Asn1EncodableVector();
  678. foreach (SignerInformation sigInf in counterSigners.GetSigners())
  679. {
  680. sigs.Add(sigInf.ToSignerInfo());
  681. }
  682. v.Add(new Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(sigs)));
  683. return new SignerInformation(
  684. new SignerInfo(
  685. sInfo.SignerID,
  686. sInfo.DigestAlgorithm,
  687. sInfo.AuthenticatedAttributes,
  688. sInfo.DigestEncryptionAlgorithm,
  689. sInfo.EncryptedDigest,
  690. new DerSet(v)),
  691. signerInformation.contentType,
  692. signerInformation.content,
  693. null);
  694. }
  695. }
  696. }
  697. #pragma warning restore
  698. #endif