ArmoredOutputStream.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 System.Reflection;
  8. using System.Text;
  9. #if PORTABLE || NETFX_CORE
  10. using System.Linq;
  11. #endif
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  14. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg
  15. {
  16. /**
  17. * Basic output stream.
  18. */
  19. public class ArmoredOutputStream
  20. : BaseOutputStream
  21. {
  22. public static readonly string HeaderVersion = "Version";
  23. private static readonly byte[] encodingTable =
  24. {
  25. (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
  26. (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
  27. (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
  28. (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
  29. (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
  30. (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
  31. (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
  32. (byte)'v',
  33. (byte)'w', (byte)'x', (byte)'y', (byte)'z',
  34. (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
  35. (byte)'7', (byte)'8', (byte)'9',
  36. (byte)'+', (byte)'/'
  37. };
  38. /**
  39. * encode the input data producing a base 64 encoded byte array.
  40. */
  41. private static void Encode(
  42. Stream outStream,
  43. int[] data,
  44. int len)
  45. {
  46. Debug.Assert(len > 0);
  47. Debug.Assert(len < 4);
  48. byte[] bs = new byte[4];
  49. int d1 = data[0];
  50. bs[0] = encodingTable[(d1 >> 2) & 0x3f];
  51. switch (len)
  52. {
  53. case 1:
  54. {
  55. bs[1] = encodingTable[(d1 << 4) & 0x3f];
  56. bs[2] = (byte)'=';
  57. bs[3] = (byte)'=';
  58. break;
  59. }
  60. case 2:
  61. {
  62. int d2 = data[1];
  63. bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f];
  64. bs[2] = encodingTable[(d2 << 2) & 0x3f];
  65. bs[3] = (byte)'=';
  66. break;
  67. }
  68. case 3:
  69. {
  70. int d2 = data[1];
  71. int d3 = data[2];
  72. bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f];
  73. bs[2] = encodingTable[((d2 << 2) | (d3 >> 6)) & 0x3f];
  74. bs[3] = encodingTable[d3 & 0x3f];
  75. break;
  76. }
  77. }
  78. outStream.Write(bs, 0, bs.Length);
  79. }
  80. private readonly Stream outStream;
  81. private int[] buf = new int[3];
  82. private int bufPtr = 0;
  83. private Crc24 crc = new Crc24();
  84. private int chunkCount = 0;
  85. private int lastb;
  86. private bool start = true;
  87. private bool clearText = false;
  88. private bool newLine = false;
  89. private string type;
  90. private static readonly string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
  91. private static readonly string headerStart = "-----BEGIN PGP ";
  92. private static readonly string headerTail = "-----";
  93. private static readonly string footerStart = "-----END PGP ";
  94. private static readonly string footerTail = "-----";
  95. private static readonly string Version = "BCPG C# v" + HTTPManager.UserAgent;
  96. private readonly IDictionary headers;
  97. public ArmoredOutputStream(Stream outStream)
  98. {
  99. this.outStream = outStream;
  100. this.headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(1);
  101. SetHeader(HeaderVersion, Version);
  102. }
  103. public ArmoredOutputStream(Stream outStream, IDictionary headers)
  104. : this(outStream)
  105. {
  106. foreach (string header in headers.Keys)
  107. {
  108. IList headerList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
  109. headerList.Add(headers[header]);
  110. this.headers[header] = headerList;
  111. }
  112. }
  113. /**
  114. * Set an additional header entry. Any current value(s) under the same name will be
  115. * replaced by the new one. A null value will clear the entry for name. *
  116. * @param name the name of the header entry.
  117. * @param v the value of the header entry.
  118. */
  119. public void SetHeader(string name, string val)
  120. {
  121. if (val == null)
  122. {
  123. this.headers.Remove(name);
  124. }
  125. else
  126. {
  127. IList valueList = (IList)headers[name];
  128. if (valueList == null)
  129. {
  130. valueList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
  131. this.headers[name] = valueList;
  132. }
  133. else
  134. {
  135. valueList.Clear();
  136. }
  137. valueList.Add(val);
  138. }
  139. }
  140. /**
  141. * Set an additional header entry. The current value(s) will continue to exist together
  142. * with the new one. Adding a null value has no effect.
  143. *
  144. * @param name the name of the header entry.
  145. * @param value the value of the header entry.
  146. */
  147. public void AddHeader(string name, string val)
  148. {
  149. if (val == null || name == null)
  150. return;
  151. IList valueList = (IList)headers[name];
  152. if (valueList == null)
  153. {
  154. valueList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
  155. this.headers[name] = valueList;
  156. }
  157. valueList.Add(val);
  158. }
  159. /**
  160. * Reset the headers to only contain a Version string (if one is present).
  161. */
  162. public void ResetHeaders()
  163. {
  164. IList versions = (IList)headers[HeaderVersion];
  165. headers.Clear();
  166. if (versions != null)
  167. {
  168. headers[HeaderVersion] = versions;
  169. }
  170. }
  171. /**
  172. * Start a clear text signed message.
  173. * @param hashAlgorithm
  174. */
  175. public void BeginClearText(
  176. HashAlgorithmTag hashAlgorithm)
  177. {
  178. string hash;
  179. switch (hashAlgorithm)
  180. {
  181. case HashAlgorithmTag.Sha1:
  182. hash = "SHA1";
  183. break;
  184. case HashAlgorithmTag.Sha256:
  185. hash = "SHA256";
  186. break;
  187. case HashAlgorithmTag.Sha384:
  188. hash = "SHA384";
  189. break;
  190. case HashAlgorithmTag.Sha512:
  191. hash = "SHA512";
  192. break;
  193. case HashAlgorithmTag.MD2:
  194. hash = "MD2";
  195. break;
  196. case HashAlgorithmTag.MD5:
  197. hash = "MD5";
  198. break;
  199. case HashAlgorithmTag.RipeMD160:
  200. hash = "RIPEMD160";
  201. break;
  202. default:
  203. throw new IOException("unknown hash algorithm tag in beginClearText: " + hashAlgorithm);
  204. }
  205. DoWrite("-----BEGIN PGP SIGNED MESSAGE-----" + nl);
  206. DoWrite("Hash: " + hash + nl + nl);
  207. clearText = true;
  208. newLine = true;
  209. lastb = 0;
  210. }
  211. public void EndClearText()
  212. {
  213. clearText = false;
  214. }
  215. public override void WriteByte(
  216. byte b)
  217. {
  218. if (clearText)
  219. {
  220. outStream.WriteByte(b);
  221. if (newLine)
  222. {
  223. if (!(b == '\n' && lastb == '\r'))
  224. {
  225. newLine = false;
  226. }
  227. if (b == '-')
  228. {
  229. outStream.WriteByte((byte)' ');
  230. outStream.WriteByte((byte)'-'); // dash escape
  231. }
  232. }
  233. if (b == '\r' || (b == '\n' && lastb != '\r'))
  234. {
  235. newLine = true;
  236. }
  237. lastb = b;
  238. return;
  239. }
  240. if (start)
  241. {
  242. bool newPacket = (b & 0x40) != 0;
  243. int tag;
  244. if (newPacket)
  245. {
  246. tag = b & 0x3f;
  247. }
  248. else
  249. {
  250. tag = (b & 0x3f) >> 2;
  251. }
  252. switch ((PacketTag)tag)
  253. {
  254. case PacketTag.PublicKey:
  255. type = "PUBLIC KEY BLOCK";
  256. break;
  257. case PacketTag.SecretKey:
  258. type = "PRIVATE KEY BLOCK";
  259. break;
  260. case PacketTag.Signature:
  261. type = "SIGNATURE";
  262. break;
  263. default:
  264. type = "MESSAGE";
  265. break;
  266. }
  267. DoWrite(headerStart + type + headerTail + nl);
  268. {
  269. IList versionHeaders = (IList)headers[HeaderVersion];
  270. if (versionHeaders != null)
  271. {
  272. WriteHeaderEntry(HeaderVersion, versionHeaders[0].ToString());
  273. }
  274. }
  275. foreach (DictionaryEntry de in headers)
  276. {
  277. string k = (string)de.Key;
  278. if (k != HeaderVersion)
  279. {
  280. IList values = (IList)de.Value;
  281. foreach (string v in values)
  282. {
  283. WriteHeaderEntry(k, v);
  284. }
  285. }
  286. }
  287. DoWrite(nl);
  288. start = false;
  289. }
  290. if (bufPtr == 3)
  291. {
  292. Encode(outStream, buf, bufPtr);
  293. bufPtr = 0;
  294. if ((++chunkCount & 0xf) == 0)
  295. {
  296. DoWrite(nl);
  297. }
  298. }
  299. crc.Update(b);
  300. buf[bufPtr++] = b & 0xff;
  301. }
  302. /**
  303. * <b>Note</b>: Close() does not close the underlying stream. So it is possible to write
  304. * multiple objects using armoring to a single stream.
  305. */
  306. #if PORTABLE || NETFX_CORE
  307. protected override void Dispose(bool disposing)
  308. {
  309. if (disposing)
  310. {
  311. if (type == null)
  312. return;
  313. DoClose();
  314. type = null;
  315. start = true;
  316. }
  317. base.Dispose(disposing);
  318. }
  319. #else
  320. public override void Close()
  321. {
  322. if (type == null)
  323. return;
  324. DoClose();
  325. type = null;
  326. start = true;
  327. base.Close();
  328. }
  329. #endif
  330. private void DoClose()
  331. {
  332. if (bufPtr > 0)
  333. {
  334. Encode(outStream, buf, bufPtr);
  335. }
  336. DoWrite(nl + '=');
  337. int crcV = crc.Value;
  338. buf[0] = ((crcV >> 16) & 0xff);
  339. buf[1] = ((crcV >> 8) & 0xff);
  340. buf[2] = (crcV & 0xff);
  341. Encode(outStream, buf, 3);
  342. DoWrite(nl);
  343. DoWrite(footerStart);
  344. DoWrite(type);
  345. DoWrite(footerTail);
  346. DoWrite(nl);
  347. outStream.Flush();
  348. }
  349. private void WriteHeaderEntry(
  350. string name,
  351. string v)
  352. {
  353. DoWrite(name + ": " + v + nl);
  354. }
  355. private void DoWrite(
  356. string s)
  357. {
  358. byte[] bs = Strings.ToAsciiByteArray(s);
  359. outStream.Write(bs, 0, bs.Length);
  360. }
  361. }
  362. }
  363. #pragma warning restore
  364. #endif