DerData.cs 13 KB

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