DerData.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Renci.SshNet.Common
  4. {
  5. /// <summary>
  6. /// Base class for DER encoded data.
  7. /// </summary>
  8. public class DerData
  9. {
  10. private const byte Constructed = 0x20;
  11. private const byte Boolean = 0x01;
  12. private const byte Integer = 0x02;
  13. private const byte BITSTRING = 0x03;
  14. private const byte Octetstring = 0x04;
  15. private const byte Null = 0x05;
  16. private const byte Objectidentifier = 0x06;
  17. private const byte Sequence = 0x10;
  18. private readonly List<byte> _data;
  19. private readonly int _lastIndex;
  20. private int _readerIndex;
  21. /// <summary>
  22. /// Gets a value indicating whether end of data is reached.
  23. /// </summary>
  24. /// <value>
  25. /// <see langword="true"/> if end of data is reached; otherwise, <see langword="false"/>.
  26. /// </value>
  27. public bool IsEndOfData
  28. {
  29. get
  30. {
  31. return _readerIndex >= _lastIndex;
  32. }
  33. }
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="DerData"/> class.
  36. /// </summary>
  37. public DerData()
  38. {
  39. _data = new List<byte>();
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="DerData"/> class.
  43. /// </summary>
  44. /// <param name="data">DER encoded data.</param>
  45. /// <param name="construct">its a construct.</param>
  46. public DerData(byte[] data, bool construct = false)
  47. {
  48. _data = new List<byte>(data);
  49. if (construct)
  50. {
  51. _lastIndex = _readerIndex + data.Length;
  52. }
  53. else
  54. {
  55. _ = ReadByte(); // skip dataType
  56. var length = ReadLength();
  57. _lastIndex = _readerIndex + length;
  58. }
  59. }
  60. /// <summary>
  61. /// Encodes written data as DER byte array.
  62. /// </summary>
  63. /// <returns>DER Encoded array.</returns>
  64. public byte[] Encode()
  65. {
  66. var length = _data.Count;
  67. var lengthBytes = GetLength(length);
  68. _data.InsertRange(0, lengthBytes);
  69. _data.Insert(0, Constructed | Sequence);
  70. return _data.ToArray();
  71. }
  72. /// <summary>
  73. /// Reads next mpint data type from internal buffer.
  74. /// </summary>
  75. /// <returns>mpint read.</returns>
  76. public BigInteger ReadBigInteger()
  77. {
  78. var type = ReadByte();
  79. if (type != Integer)
  80. {
  81. throw new InvalidOperationException(string.Format("Invalid data type, INTEGER(02) is expected, but was {0}", type.ToString("X2")));
  82. }
  83. var length = ReadLength();
  84. var data = ReadBytes(length);
  85. return new BigInteger(data.Reverse());
  86. }
  87. /// <summary>
  88. /// Reads next int data type from internal buffer.
  89. /// </summary>
  90. /// <returns>int read.</returns>
  91. public int ReadInteger()
  92. {
  93. var type = ReadByte();
  94. if (type != Integer)
  95. {
  96. throw new InvalidOperationException(string.Format("Invalid data type, INTEGER(02) is expected, but was {0}", type.ToString("X2")));
  97. }
  98. var length = ReadLength();
  99. var data = ReadBytes(length);
  100. if (length > 4)
  101. {
  102. throw new InvalidOperationException("Integer type cannot occupy more then 4 bytes");
  103. }
  104. var result = 0;
  105. var shift = (length - 1) * 8;
  106. for (var i = 0; i < length; i++)
  107. {
  108. result |= data[i] << shift;
  109. shift -= 8;
  110. }
  111. return result;
  112. }
  113. /// <summary>
  114. /// Reads next octetstring data type from internal buffer.
  115. /// </summary>
  116. /// <returns>data read.</returns>
  117. public byte[] ReadOctetString()
  118. {
  119. var type = ReadByte();
  120. if (type != Octetstring)
  121. {
  122. throw new InvalidOperationException(string.Format("Invalid data type, OCTETSTRING(04) is expected, but was {0}", type.ToString("X2")));
  123. }
  124. var length = ReadLength();
  125. var data = ReadBytes(length);
  126. return data;
  127. }
  128. /// <summary>
  129. /// Reads next bitstring data type from internal buffer.
  130. /// </summary>
  131. /// <returns>data read.</returns>
  132. public byte[] ReadBitString()
  133. {
  134. var type = ReadByte();
  135. if (type != BITSTRING)
  136. {
  137. throw new InvalidOperationException(string.Format("Invalid data type, BITSTRING(03) is expected, but was {0}", type.ToString("X2")));
  138. }
  139. var length = ReadLength();
  140. var data = ReadBytes(length);
  141. return data;
  142. }
  143. /// <summary>
  144. /// Reads next object data type from internal buffer.
  145. /// </summary>
  146. /// <returns>data read.</returns>
  147. public byte[] ReadObject()
  148. {
  149. var type = ReadByte();
  150. if (type != Objectidentifier)
  151. {
  152. throw new InvalidOperationException(string.Format("Invalid data type, OBJECT(06) is expected, but was {0}", type.ToString("X2")));
  153. }
  154. var length = ReadLength();
  155. var data = ReadBytes(length);
  156. return data;
  157. }
  158. /// <summary>
  159. /// Writes BOOLEAN data into internal buffer.
  160. /// </summary>
  161. /// <param name="data">UInt32 data to write.</param>
  162. public void Write(bool data)
  163. {
  164. _data.Add(Boolean);
  165. _data.Add(1);
  166. _data.Add((byte)(data ? 1 : 0));
  167. }
  168. /// <summary>
  169. /// Writes UInt32 data into internal buffer.
  170. /// </summary>
  171. /// <param name="data">UInt32 data to write.</param>
  172. public void Write(uint data)
  173. {
  174. var bytes = Pack.UInt32ToBigEndian(data);
  175. _data.Add(Integer);
  176. var length = GetLength(bytes.Length);
  177. WriteBytes(length);
  178. WriteBytes(bytes);
  179. }
  180. /// <summary>
  181. /// Writes INTEGER data into internal buffer.
  182. /// </summary>
  183. /// <param name="data">BigInteger data to write.</param>
  184. public void Write(BigInteger data)
  185. {
  186. var bytes = data.ToByteArray().Reverse();
  187. _data.Add(Integer);
  188. var length = GetLength(bytes.Length);
  189. WriteBytes(length);
  190. WriteBytes(bytes);
  191. }
  192. /// <summary>
  193. /// Writes OCTETSTRING data into internal buffer.
  194. /// </summary>
  195. /// <param name="data">The data.</param>
  196. public void Write(byte[] data)
  197. {
  198. _data.Add(Octetstring);
  199. var length = GetLength(data.Length);
  200. WriteBytes(length);
  201. WriteBytes(data);
  202. }
  203. /// <summary>
  204. /// Writes OBJECTIDENTIFIER data into internal buffer.
  205. /// </summary>
  206. /// <param name="identifier">The identifier.</param>
  207. public void Write(ObjectIdentifier identifier)
  208. {
  209. var temp = new ulong[identifier.Identifiers.Length - 1];
  210. temp[0] = (identifier.Identifiers[0] * 40) + identifier.Identifiers[1];
  211. Buffer.BlockCopy(identifier.Identifiers, 2 * sizeof(ulong), temp, 1 * sizeof(ulong), (identifier.Identifiers.Length - 2) * sizeof(ulong));
  212. var bytes = new List<byte>();
  213. foreach (var subidentifier in temp)
  214. {
  215. var item = subidentifier;
  216. var buffer = new byte[8];
  217. var bufferIndex = buffer.Length - 1;
  218. var current = (byte)(item & 0x7F);
  219. do
  220. {
  221. buffer[bufferIndex] = current;
  222. if (bufferIndex < buffer.Length - 1)
  223. {
  224. buffer[bufferIndex] |= 0x80;
  225. }
  226. item >>= 7;
  227. current = (byte)(item & 0x7F);
  228. bufferIndex--;
  229. }
  230. while (current > 0);
  231. for (var i = bufferIndex + 1; i < buffer.Length; i++)
  232. {
  233. bytes.Add(buffer[i]);
  234. }
  235. }
  236. _data.Add(Objectidentifier);
  237. var length = GetLength(bytes.Count);
  238. WriteBytes(length);
  239. WriteBytes(bytes);
  240. }
  241. /// <summary>
  242. /// Writes DerData data into internal buffer.
  243. /// </summary>
  244. /// <param name="data">DerData data to write.</param>
  245. public void Write(DerData data)
  246. {
  247. var bytes = data.Encode();
  248. _data.AddRange(bytes);
  249. }
  250. /// <summary>
  251. /// Writes BITSTRING data into internal buffer.
  252. /// </summary>
  253. /// <param name="data">The data.</param>
  254. public void WriteBitstring(byte[] data)
  255. {
  256. _data.Add(BITSTRING);
  257. var length = GetLength(data.Length);
  258. WriteBytes(length);
  259. WriteBytes(data);
  260. }
  261. /// <summary>
  262. /// Writes OBJECTIDENTIFIER data into internal buffer.
  263. /// </summary>
  264. /// <param name="bytes">The bytes.</param>
  265. public void WriteObjectIdentifier(byte[] bytes)
  266. {
  267. _data.Add(Objectidentifier);
  268. var length = GetLength(bytes.Length);
  269. WriteBytes(length);
  270. WriteBytes(bytes);
  271. }
  272. /// <summary>
  273. /// Writes NULL data into internal buffer.
  274. /// </summary>
  275. public void WriteNull()
  276. {
  277. _data.Add(Null);
  278. _data.Add(0);
  279. }
  280. private static byte[] GetLength(int length)
  281. {
  282. if (length > 127)
  283. {
  284. var size = 1;
  285. var val = length;
  286. while ((val >>= 8) != 0)
  287. {
  288. size++;
  289. }
  290. var data = new byte[size];
  291. data[0] = (byte)(size | 0x80);
  292. for (int i = (size - 1) * 8, j = 1; i >= 0; i -= 8, j++)
  293. {
  294. data[j] = (byte)(length >> i);
  295. }
  296. return data;
  297. }
  298. return new[] { (byte) length };
  299. }
  300. /// <summary>
  301. /// Gets Data Length.
  302. /// </summary>
  303. /// <returns>
  304. /// The length.
  305. /// </returns>
  306. public int ReadLength()
  307. {
  308. int length = ReadByte();
  309. if (length == 0x80)
  310. {
  311. throw new NotSupportedException("Indefinite-length encoding is not supported.");
  312. }
  313. if (length > 127)
  314. {
  315. var size = length & 0x7f;
  316. // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
  317. if (size > 4)
  318. {
  319. throw new InvalidOperationException(string.Format("DER length is '{0}' and cannot be more than 4 bytes.", size));
  320. }
  321. length = 0;
  322. for (var i = 0; i < size; i++)
  323. {
  324. int next = ReadByte();
  325. length = (length << 8) + next;
  326. }
  327. if (length < 0)
  328. {
  329. throw new InvalidOperationException("Corrupted data - negative length found");
  330. }
  331. }
  332. return length;
  333. }
  334. /// <summary>
  335. /// Write Byte data into internal buffer.
  336. /// </summary>
  337. /// <param name="data">The data to write.</param>
  338. public void WriteBytes(IEnumerable<byte> data)
  339. {
  340. _data.AddRange(data);
  341. }
  342. /// <summary>
  343. /// Reads Byte data into internal buffer.
  344. /// </summary>
  345. /// <returns>
  346. /// The data read.
  347. /// </returns>
  348. public byte ReadByte()
  349. {
  350. if (_readerIndex > _data.Count)
  351. {
  352. throw new InvalidOperationException("Read out of boundaries.");
  353. }
  354. return _data[_readerIndex++];
  355. }
  356. /// <summary>
  357. /// Reads lengths Bytes data into internal buffer.
  358. /// </summary>
  359. /// <returns>
  360. /// The data read.
  361. /// </returns>
  362. /// <param name="length">amount of data to read.</param>
  363. public byte[] ReadBytes(int length)
  364. {
  365. if (_readerIndex + length > _data.Count)
  366. {
  367. throw new InvalidOperationException("Read out of boundaries.");
  368. }
  369. var result = new byte[length];
  370. _data.CopyTo(_readerIndex, result, 0, length);
  371. _readerIndex += length;
  372. return result;
  373. }
  374. }
  375. }