SignerInformation.cs 23 KB

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