CMSAuthenticatedDataStreamGenerator.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
  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 authenticated-data message stream.
  19. * <p>
  20. * A simple example of usage.
  21. * <pre>
  22. * CMSAuthenticatedDataStreamGenerator edGen = new CMSAuthenticatedDataStreamGenerator();
  23. *
  24. * edGen.addKeyTransRecipient(cert);
  25. *
  26. * ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  27. *
  28. * OutputStream out = edGen.open(
  29. * bOut, CMSAuthenticatedDataGenerator.AES128_CBC, "BC");*
  30. * out.write(data);
  31. *
  32. * out.close();
  33. * </pre>
  34. * </p>
  35. */
  36. public class CmsAuthenticatedDataStreamGenerator
  37. : CmsAuthenticatedGenerator
  38. {
  39. // TODO Add support
  40. // private object _originatorInfo = null;
  41. // private object _unprotectedAttributes = null;
  42. private int _bufferSize;
  43. private bool _berEncodeRecipientSet;
  44. public CmsAuthenticatedDataStreamGenerator()
  45. {
  46. }
  47. /// <summary>Constructor allowing specific source of randomness</summary>
  48. /// <param name="random">Instance of <c>SecureRandom</c> to use.</param>
  49. public CmsAuthenticatedDataStreamGenerator(SecureRandom random)
  50. : base(random)
  51. {
  52. }
  53. /**
  54. * Set the underlying string size for encapsulated data
  55. *
  56. * @param bufferSize length of octet strings to buffer the data.
  57. */
  58. public void SetBufferSize(
  59. int bufferSize)
  60. {
  61. _bufferSize = bufferSize;
  62. }
  63. /**
  64. * Use a BER Set to store the recipient information
  65. */
  66. public void SetBerEncodeRecipients(
  67. bool berEncodeRecipientSet)
  68. {
  69. _berEncodeRecipientSet = berEncodeRecipientSet;
  70. }
  71. /**
  72. * generate an enveloped object that contains an CMS Enveloped Data
  73. * object using the given provider and the passed in key generator.
  74. * @throws java.io.IOException
  75. */
  76. private Stream Open(
  77. Stream outStr,
  78. string macOid,
  79. CipherKeyGenerator keyGen)
  80. {
  81. // FIXME Will this work for macs?
  82. byte[] encKeyBytes = keyGen.GenerateKey();
  83. KeyParameter encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);
  84. Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);
  85. ICipherParameters cipherParameters;
  86. AlgorithmIdentifier macAlgId = GetAlgorithmIdentifier(
  87. macOid, encKey, asn1Params, out cipherParameters);
  88. Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
  89. foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
  90. {
  91. try
  92. {
  93. recipientInfos.Add(rig.Generate(encKey, m_random));
  94. }
  95. catch (InvalidKeyException e)
  96. {
  97. throw new CmsException("key inappropriate for algorithm.", e);
  98. }
  99. catch (GeneralSecurityException e)
  100. {
  101. throw new CmsException("error making encrypted content.", e);
  102. }
  103. }
  104. // FIXME Only passing key at the moment
  105. // return Open(outStr, macAlgId, cipherParameters, recipientInfos);
  106. return Open(outStr, macAlgId, encKey, recipientInfos);
  107. }
  108. protected Stream Open(
  109. Stream outStr,
  110. AlgorithmIdentifier macAlgId,
  111. ICipherParameters cipherParameters,
  112. Asn1EncodableVector recipientInfos)
  113. {
  114. try
  115. {
  116. //
  117. // ContentInfo
  118. //
  119. BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);
  120. cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);
  121. //
  122. // Authenticated Data
  123. //
  124. BerSequenceGenerator authGen = new BerSequenceGenerator(
  125. cGen.GetRawOutputStream(), 0, true);
  126. authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));
  127. Stream authRaw = authGen.GetRawOutputStream();
  128. Asn1Generator recipGen = _berEncodeRecipientSet
  129. ? (Asn1Generator) new BerSetGenerator(authRaw)
  130. : new DerSetGenerator(authRaw);
  131. foreach (Asn1Encodable ae in recipientInfos)
  132. {
  133. recipGen.AddObject(ae);
  134. }
  135. recipGen.Close();
  136. authGen.AddObject(macAlgId);
  137. BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
  138. eiGen.AddObject(CmsObjectIdentifiers.Data);
  139. Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
  140. eiGen.GetRawOutputStream(), 0, true, _bufferSize);
  141. IMac mac = MacUtilities.GetMac(macAlgId.Algorithm);
  142. // TODO Confirm no ParametersWithRandom needed
  143. mac.Init(cipherParameters);
  144. Stream mOut = new TeeOutputStream(octetOutputStream, new MacSink(mac));
  145. return new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen);
  146. }
  147. catch (SecurityUtilityException e)
  148. {
  149. throw new CmsException("couldn't create cipher.", e);
  150. }
  151. catch (InvalidKeyException e)
  152. {
  153. throw new CmsException("key invalid in message.", e);
  154. }
  155. catch (IOException e)
  156. {
  157. throw new CmsException("exception decoding algorithm parameters.", e);
  158. }
  159. }
  160. /**
  161. * generate an enveloped object that contains an CMS Enveloped Data object
  162. */
  163. public Stream Open(
  164. Stream outStr,
  165. string encryptionOid)
  166. {
  167. CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
  168. keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength));
  169. return Open(outStr, encryptionOid, keyGen);
  170. }
  171. /**
  172. * generate an enveloped object that contains an CMS Enveloped Data object
  173. */
  174. public Stream Open(
  175. Stream outStr,
  176. string encryptionOid,
  177. int keySize)
  178. {
  179. CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
  180. keyGen.Init(new KeyGenerationParameters(m_random, keySize));
  181. return Open(outStr, encryptionOid, keyGen);
  182. }
  183. private class CmsAuthenticatedDataOutputStream
  184. : BaseOutputStream
  185. {
  186. private readonly Stream macStream;
  187. private readonly IMac mac;
  188. private readonly BerSequenceGenerator cGen;
  189. private readonly BerSequenceGenerator authGen;
  190. private readonly BerSequenceGenerator eiGen;
  191. public CmsAuthenticatedDataOutputStream(
  192. Stream macStream,
  193. IMac mac,
  194. BerSequenceGenerator cGen,
  195. BerSequenceGenerator authGen,
  196. BerSequenceGenerator eiGen)
  197. {
  198. this.macStream = macStream;
  199. this.mac = mac;
  200. this.cGen = cGen;
  201. this.authGen = authGen;
  202. this.eiGen = eiGen;
  203. }
  204. public override void Write(byte[] buffer, int offset, int count)
  205. {
  206. macStream.Write(buffer, offset, count);
  207. }
  208. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  209. public override void Write(ReadOnlySpan<byte> buffer)
  210. {
  211. macStream.Write(buffer);
  212. }
  213. #endif
  214. public override void WriteByte(byte value)
  215. {
  216. macStream.WriteByte(value);
  217. }
  218. protected override void Dispose(bool disposing)
  219. {
  220. if (disposing)
  221. {
  222. macStream.Dispose();
  223. // TODO Parent context(s) should really be be closed explicitly
  224. eiGen.Close();
  225. // [TODO] auth attributes go here
  226. byte[] macOctets = MacUtilities.DoFinal(mac);
  227. authGen.AddObject(new DerOctetString(macOctets));
  228. // [TODO] unauth attributes go here
  229. authGen.Close();
  230. cGen.Close();
  231. }
  232. base.Dispose(disposing);
  233. }
  234. }
  235. }
  236. }
  237. #pragma warning restore
  238. #endif