DerData.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  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 EXTERNAL = 0x08;
  19. //private const byte ENUMERATED = 0x0a;
  20. private const byte Sequence = 0x10;
  21. //private const byte SEQUENCEOF = 0x10; // for completeness
  22. //private const byte SET = 0x11;
  23. //private const byte SETOF = 0x11; // for completeness
  24. //private const byte NUMERICSTRING = 0x12;
  25. //private const byte PRINTABLESTRING = 0x13;
  26. //private const byte T61STRING = 0x14;
  27. //private const byte VIDEOTEXSTRING = 0x15;
  28. //private const byte IA5STRING = 0x16;
  29. //private const byte UTCTIME = 0x17;
  30. //private const byte GENERALIZEDTIME = 0x18;
  31. //private const byte GRAPHICSTRING = 0x19;
  32. //private const byte VISIBLESTRING = 0x1a;
  33. //private const byte GENERALSTRING = 0x1b;
  34. //private const byte UNIVERSALSTRING = 0x1c;
  35. //private const byte BMPSTRING = 0x1e;
  36. //private const byte UTF8STRING = 0x0c;
  37. //private const byte APPLICATION = 0x40;
  38. //private const byte TAGGED = 0x80;
  39. private readonly List<byte> _data;
  40. private int _readerIndex;
  41. private readonly int _lastIndex;
  42. /// <summary>
  43. /// Gets a value indicating whether end of data is reached.
  44. /// </summary>
  45. /// <value>
  46. /// <c>true</c> if end of data is reached; otherwise, <c>false</c>.
  47. /// </value>
  48. public bool IsEndOfData
  49. {
  50. get
  51. {
  52. return _readerIndex >= _lastIndex;
  53. }
  54. }
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="DerData"/> class.
  57. /// </summary>
  58. public DerData()
  59. {
  60. _data = new List<byte>();
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="DerData"/> class.
  64. /// </summary>
  65. /// <param name="data">DER encoded data.</param>
  66. public DerData(byte[] data)
  67. {
  68. _data = new List<byte>(data);
  69. var dataType = ReadByte();
  70. var length = ReadLength();
  71. _lastIndex = _readerIndex + length;
  72. }
  73. /// <summary>
  74. /// Encodes written data as DER byte array.
  75. /// </summary>
  76. /// <returns>DER Encoded array.</returns>
  77. public byte[] Encode()
  78. {
  79. var length = _data.Count();
  80. var lengthBytes = GetLength(length);
  81. _data.InsertRange(0, lengthBytes);
  82. _data.Insert(0, Constructed | Sequence);
  83. return _data.ToArray();
  84. }
  85. /// <summary>
  86. /// Reads next mpint data type from internal buffer.
  87. /// </summary>
  88. /// <returns>mpint read.</returns>
  89. public BigInteger ReadBigInteger()
  90. {
  91. var type = ReadByte();
  92. if (type != Integer)
  93. throw new InvalidOperationException("Invalid data type, INTEGER(02) is expected.");
  94. var length = ReadLength();
  95. var data = ReadBytes(length);
  96. #if TUNING
  97. return new BigInteger(data.Reverse());
  98. #else
  99. return new BigInteger(data.Reverse().ToArray());
  100. #endif
  101. }
  102. /// <summary>
  103. /// Reads next int data type from internal buffer.
  104. /// </summary>
  105. /// <returns>int read.</returns>
  106. public int ReadInteger()
  107. {
  108. var type = ReadByte();
  109. if (type != Integer)
  110. throw new InvalidOperationException("Invalid data type, INTEGER(02) is expected.");
  111. var length = ReadLength();
  112. var data = ReadBytes(length);
  113. if (length > 4)
  114. throw new InvalidOperationException("Integer type cannot occupy more then 4 bytes");
  115. var result = 0;
  116. var shift = (length - 1) * 8;
  117. for (var i = 0; i < length; i++)
  118. {
  119. result |= data[i] << shift;
  120. shift -= 8;
  121. }
  122. //return (int)(data[0] << 56 | data[1] << 48 | data[2] << 40 | data[3] << 32 | data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  123. return result;
  124. }
  125. /// <summary>
  126. /// Writes BOOLEAN data into internal buffer.
  127. /// </summary>
  128. /// <param name="data">UInt32 data to write.</param>
  129. public void Write(bool data)
  130. {
  131. _data.Add(Boolean);
  132. _data.Add(1);
  133. _data.Add((byte)(data ? 1 : 0));
  134. }
  135. /// <summary>
  136. /// Writes UInt32 data into internal buffer.
  137. /// </summary>
  138. /// <param name="data">UInt32 data to write.</param>
  139. public void Write(UInt32 data)
  140. {
  141. var bytes = data.GetBytes();
  142. _data.Add(Integer);
  143. var length = GetLength(bytes.Length);
  144. WriteBytes(length);
  145. WriteBytes(bytes);
  146. }
  147. /// <summary>
  148. /// Writes INTEGER data into internal buffer.
  149. /// </summary>
  150. /// <param name="data">BigInteger data to write.</param>
  151. public void Write(BigInteger data)
  152. {
  153. #if TUNING
  154. var bytes = data.ToByteArray().Reverse().ToList();
  155. #else
  156. var bytes = data.ToByteArray().Reverse().ToList();
  157. #endif
  158. _data.Add(Integer);
  159. var length = GetLength(bytes.Count);
  160. WriteBytes(length);
  161. WriteBytes(bytes);
  162. }
  163. /// <summary>
  164. /// Writes OCTETSTRING data into internal buffer.
  165. /// </summary>
  166. /// <param name="data">The data.</param>
  167. public void Write(byte[] data)
  168. {
  169. _data.Add(Octetstring);
  170. var length = GetLength(data.Length);
  171. WriteBytes(length);
  172. WriteBytes(data);
  173. }
  174. /// <summary>
  175. /// Writes OBJECTIDENTIFIER data into internal buffer.
  176. /// </summary>
  177. /// <param name="identifier">The identifier.</param>
  178. public void Write(ObjectIdentifier identifier)
  179. {
  180. var temp = new ulong[identifier.Identifiers.Length - 1];
  181. temp[0] = identifier.Identifiers[0] * 40 + identifier.Identifiers[1];
  182. Buffer.BlockCopy(identifier.Identifiers, 2 * sizeof(ulong), temp, 1 * sizeof(ulong), (identifier.Identifiers.Length - 2) * sizeof(ulong));
  183. //Array.Copy(identifier.Identifiers, 2, temp, 1, identifier.Identifiers.Length - 2);
  184. var bytes = new List<byte>();
  185. foreach (var subidentifier in temp)
  186. {
  187. var item = subidentifier;
  188. var buffer = new byte[8];
  189. var bufferIndex = buffer.Length - 1;
  190. var current = (byte)(item & 0x7F);
  191. do
  192. {
  193. buffer[bufferIndex] = current;
  194. if (bufferIndex < buffer.Length - 1)
  195. buffer[bufferIndex] |= 0x80;
  196. item >>= 7;
  197. current = (byte)(item & 0x7F);
  198. bufferIndex--;
  199. }
  200. while (current > 0);
  201. for (var i = bufferIndex + 1; i < buffer.Length; i++)
  202. {
  203. bytes.Add(buffer[i]);
  204. }
  205. }
  206. _data.Add(Objectidentifier);
  207. var length = GetLength(bytes.Count);
  208. WriteBytes(length);
  209. WriteBytes(bytes);
  210. }
  211. /// <summary>
  212. /// Writes NULL data into internal buffer.
  213. /// </summary>
  214. public void WriteNull()
  215. {
  216. _data.Add(Null);
  217. _data.Add(0);
  218. }
  219. /// <summary>
  220. /// Writes DerData data into internal buffer.
  221. /// </summary>
  222. /// <param name="data">DerData data to write.</param>
  223. public void Write(DerData data)
  224. {
  225. var bytes = data.Encode();
  226. _data.AddRange(bytes);
  227. }
  228. private static IEnumerable<byte> GetLength(int length)
  229. {
  230. if (length > 127)
  231. {
  232. var size = 1;
  233. var val = length;
  234. while ((val >>= 8) != 0)
  235. size++;
  236. var data = new byte[size];
  237. data[0] = (byte)(size | 0x80);
  238. for (int i = (size - 1) * 8, j = 1; i >= 0; i -= 8, j++)
  239. {
  240. data[j] = (byte)(length >> i);
  241. }
  242. return data;
  243. }
  244. return new[] {(byte) length};
  245. }
  246. private int ReadLength()
  247. {
  248. int length = ReadByte();
  249. if (length == 0x80)
  250. {
  251. throw new NotSupportedException("Indefinite-length encoding is not supported.");
  252. }
  253. if (length > 127)
  254. {
  255. var size = length & 0x7f;
  256. // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
  257. if (size > 4)
  258. throw new InvalidOperationException(string.Format("DER length is '{0}' and cannot be more than 4 bytes.", size));
  259. length = 0;
  260. for (var i = 0; i < size; i++)
  261. {
  262. int next = ReadByte();
  263. length = (length << 8) + next;
  264. }
  265. if (length < 0)
  266. throw new InvalidOperationException("Corrupted data - negative length found");
  267. //if (length >= limit) // after all we must have read at least 1 byte
  268. // throw new IOException("Corrupted stream - out of bounds length found");
  269. }
  270. return length;
  271. }
  272. private void WriteBytes(IEnumerable<byte> data)
  273. {
  274. _data.AddRange(data);
  275. }
  276. private byte ReadByte()
  277. {
  278. if (_readerIndex > _data.Count)
  279. throw new InvalidOperationException("Read out of boundaries.");
  280. return _data[_readerIndex++];
  281. }
  282. private byte[] ReadBytes(int length)
  283. {
  284. if (_readerIndex + length > _data.Count)
  285. throw new InvalidOperationException("Read out of boundaries.");
  286. var result = new byte[length];
  287. _data.CopyTo(_readerIndex, result, 0, length);
  288. _readerIndex += length;
  289. return result;
  290. }
  291. }
  292. }