CMSEnvelopedDataStreamGenerator.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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.IO;
  11. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  12. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  13. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  14. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  15. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Cms
  16. {
  17. /**
  18. * General class for generating a CMS enveloped-data message stream.
  19. * <p>
  20. * A simple example of usage.
  21. * <pre>
  22. * CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();
  23. *
  24. * edGen.AddKeyTransRecipient(cert);
  25. *
  26. * MemoryStream bOut = new MemoryStream();
  27. *
  28. * Stream out = edGen.Open(
  29. * bOut, CMSEnvelopedDataGenerator.AES128_CBC);*
  30. * out.Write(data);
  31. *
  32. * out.Close();
  33. * </pre>
  34. * </p>
  35. */
  36. public class CmsEnvelopedDataStreamGenerator
  37. : CmsEnvelopedGenerator
  38. {
  39. private object _originatorInfo = null;
  40. private object _unprotectedAttributes = null;
  41. private int _bufferSize;
  42. private bool _berEncodeRecipientSet;
  43. public CmsEnvelopedDataStreamGenerator()
  44. {
  45. }
  46. /// <summary>Constructor allowing specific source of randomness</summary>
  47. /// <param name="random">Instance of <c>SecureRandom</c> to use.</param>
  48. public CmsEnvelopedDataStreamGenerator(SecureRandom random)
  49. : base(random)
  50. {
  51. }
  52. /// <summary>Set the underlying string size for encapsulated data.</summary>
  53. /// <param name="bufferSize">Length of octet strings to buffer the data.</param>
  54. public void SetBufferSize(
  55. int bufferSize)
  56. {
  57. _bufferSize = bufferSize;
  58. }
  59. /// <summary>Use a BER Set to store the recipient information.</summary>
  60. public void SetBerEncodeRecipients(
  61. bool berEncodeRecipientSet)
  62. {
  63. _berEncodeRecipientSet = berEncodeRecipientSet;
  64. }
  65. private DerInteger Version
  66. {
  67. get
  68. {
  69. int version = (_originatorInfo != null || _unprotectedAttributes != null)
  70. ? 2
  71. : 0;
  72. return new DerInteger(version);
  73. }
  74. }
  75. /// <summary>
  76. /// Generate an enveloped object that contains an CMS Enveloped Data
  77. /// object using the passed in key generator.
  78. /// </summary>
  79. private Stream Open(
  80. Stream outStream,
  81. string encryptionOid,
  82. CipherKeyGenerator keyGen)
  83. {
  84. byte[] encKeyBytes = keyGen.GenerateKey();
  85. KeyParameter encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);
  86. Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);
  87. ICipherParameters cipherParameters;
  88. AlgorithmIdentifier encAlgID = GetAlgorithmIdentifier(
  89. encryptionOid, encKey, asn1Params, out cipherParameters);
  90. Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
  91. foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
  92. {
  93. try
  94. {
  95. recipientInfos.Add(rig.Generate(encKey, m_random));
  96. }
  97. catch (InvalidKeyException e)
  98. {
  99. throw new CmsException("key inappropriate for algorithm.", e);
  100. }
  101. catch (GeneralSecurityException e)
  102. {
  103. throw new CmsException("error making encrypted content.", e);
  104. }
  105. }
  106. return Open(outStream, encAlgID, cipherParameters, recipientInfos);
  107. }
  108. private Stream Open(
  109. Stream outStream,
  110. AlgorithmIdentifier encAlgID,
  111. ICipherParameters cipherParameters,
  112. Asn1EncodableVector recipientInfos)
  113. {
  114. try
  115. {
  116. //
  117. // ContentInfo
  118. //
  119. BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);
  120. cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);
  121. //
  122. // Encrypted Data
  123. //
  124. BerSequenceGenerator envGen = new BerSequenceGenerator(
  125. cGen.GetRawOutputStream(), 0, true);
  126. envGen.AddObject(this.Version);
  127. Stream envRaw = envGen.GetRawOutputStream();
  128. Asn1Generator recipGen = _berEncodeRecipientSet
  129. ? (Asn1Generator) new BerSetGenerator(envRaw)
  130. : new DerSetGenerator(envRaw);
  131. foreach (Asn1Encodable ae in recipientInfos)
  132. {
  133. recipGen.AddObject(ae);
  134. }
  135. recipGen.Close();
  136. BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw);
  137. eiGen.AddObject(CmsObjectIdentifiers.Data);
  138. eiGen.AddObject(encAlgID);
  139. Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
  140. eiGen.GetRawOutputStream(), 0, false, _bufferSize);
  141. IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm);
  142. cipher.Init(true, new ParametersWithRandom(cipherParameters, m_random));
  143. CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);
  144. return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen);
  145. }
  146. catch (SecurityUtilityException e)
  147. {
  148. throw new CmsException("couldn't create cipher.", e);
  149. }
  150. catch (InvalidKeyException e)
  151. {
  152. throw new CmsException("key invalid in message.", e);
  153. }
  154. catch (IOException e)
  155. {
  156. throw new CmsException("exception decoding algorithm parameters.", e);
  157. }
  158. }
  159. /**
  160. * generate an enveloped object that contains an CMS Enveloped Data object
  161. * @throws IOException
  162. */
  163. public Stream Open(
  164. Stream outStream,
  165. string encryptionOid)
  166. {
  167. CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
  168. keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength));
  169. return Open(outStream, encryptionOid, keyGen);
  170. }
  171. /**
  172. * generate an enveloped object that contains an CMS Enveloped Data object
  173. * @throws IOException
  174. */
  175. public Stream Open(
  176. Stream outStream,
  177. string encryptionOid,
  178. int keySize)
  179. {
  180. CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
  181. keyGen.Init(new KeyGenerationParameters(m_random, keySize));
  182. return Open(outStream, encryptionOid, keyGen);
  183. }
  184. private class CmsEnvelopedDataOutputStream
  185. : BaseOutputStream
  186. {
  187. private readonly CmsEnvelopedGenerator _outer;
  188. private readonly CipherStream _out;
  189. private readonly BerSequenceGenerator _cGen;
  190. private readonly BerSequenceGenerator _envGen;
  191. private readonly BerSequenceGenerator _eiGen;
  192. public CmsEnvelopedDataOutputStream(
  193. CmsEnvelopedGenerator outer,
  194. CipherStream outStream,
  195. BerSequenceGenerator cGen,
  196. BerSequenceGenerator envGen,
  197. BerSequenceGenerator eiGen)
  198. {
  199. _outer = outer;
  200. _out = outStream;
  201. _cGen = cGen;
  202. _envGen = envGen;
  203. _eiGen = eiGen;
  204. }
  205. public override void Write(byte[] buffer, int offset, int count)
  206. {
  207. _out.Write(buffer, offset, count);
  208. }
  209. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  210. public override void Write(ReadOnlySpan<byte> buffer)
  211. {
  212. _out.Write(buffer);
  213. }
  214. #endif
  215. public override void WriteByte(byte value)
  216. {
  217. _out.WriteByte(value);
  218. }
  219. protected override void Dispose(bool disposing)
  220. {
  221. if (disposing)
  222. {
  223. _out.Dispose();
  224. // TODO Parent context(s) should really be closed explicitly
  225. _eiGen.Close();
  226. if (_outer.unprotectedAttributeGenerator != null)
  227. {
  228. Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(
  229. new Dictionary<CmsAttributeTableParameter, object>());
  230. Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector());
  231. _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs));
  232. }
  233. _envGen.Close();
  234. _cGen.Close();
  235. }
  236. base.Dispose(disposing);
  237. }
  238. }
  239. }
  240. }
  241. #pragma warning restore
  242. #endif