DerData.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. ReadByte(); // skip dataType
  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. return new BigInteger(data.Reverse());
  97. }
  98. /// <summary>
  99. /// Reads next int data type from internal buffer.
  100. /// </summary>
  101. /// <returns>int read.</returns>
  102. public int ReadInteger()
  103. {
  104. var type = ReadByte();
  105. if (type != Integer)
  106. throw new InvalidOperationException("Invalid data type, INTEGER(02) is expected.");
  107. var length = ReadLength();
  108. var data = ReadBytes(length);
  109. if (length > 4)
  110. throw new InvalidOperationException("Integer type cannot occupy more then 4 bytes");
  111. var result = 0;
  112. var shift = (length - 1) * 8;
  113. for (var i = 0; i < length; i++)
  114. {
  115. result |= data[i] << shift;
  116. shift -= 8;
  117. }
  118. //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]);
  119. return result;
  120. }
  121. /// <summary>
  122. /// Writes BOOLEAN data into internal buffer.
  123. /// </summary>
  124. /// <param name="data">UInt32 data to write.</param>
  125. public void Write(bool data)
  126. {
  127. _data.Add(Boolean);
  128. _data.Add(1);
  129. _data.Add((byte)(data ? 1 : 0));
  130. }
  131. /// <summary>
  132. /// Writes UInt32 data into internal buffer.
  133. /// </summary>
  134. /// <param name="data">UInt32 data to write.</param>
  135. public void Write(uint data)
  136. {
  137. var bytes = data.GetBytes();
  138. _data.Add(Integer);
  139. var length = GetLength(bytes.Length);
  140. WriteBytes(length);
  141. WriteBytes(bytes);
  142. }
  143. /// <summary>
  144. /// Writes INTEGER data into internal buffer.
  145. /// </summary>
  146. /// <param name="data">BigInteger data to write.</param>
  147. public void Write(BigInteger data)
  148. {
  149. var bytes = data.ToByteArray().Reverse();
  150. _data.Add(Integer);
  151. var length = GetLength(bytes.Length);
  152. WriteBytes(length);
  153. WriteBytes(bytes);
  154. }
  155. /// <summary>
  156. /// Writes OCTETSTRING data into internal buffer.
  157. /// </summary>
  158. /// <param name="data">The data.</param>
  159. public void Write(byte[] data)
  160. {
  161. _data.Add(Octetstring);
  162. var length = GetLength(data.Length);
  163. WriteBytes(length);
  164. WriteBytes(data);
  165. }
  166. /// <summary>
  167. /// Writes OBJECTIDENTIFIER data into internal buffer.
  168. /// </summary>
  169. /// <param name="identifier">The identifier.</param>
  170. public void Write(ObjectIdentifier identifier)
  171. {
  172. var temp = new ulong[identifier.Identifiers.Length - 1];
  173. temp[0] = identifier.Identifiers[0] * 40 + identifier.Identifiers[1];
  174. Buffer.BlockCopy(identifier.Identifiers, 2 * sizeof(ulong), temp, 1 * sizeof(ulong), (identifier.Identifiers.Length - 2) * sizeof(ulong));
  175. //Array.Copy(identifier.Identifiers, 2, temp, 1, identifier.Identifiers.Length - 2);
  176. var bytes = new List<byte>();
  177. foreach (var subidentifier in temp)
  178. {
  179. var item = subidentifier;
  180. var buffer = new byte[8];
  181. var bufferIndex = buffer.Length - 1;
  182. var current = (byte)(item & 0x7F);
  183. do
  184. {
  185. buffer[bufferIndex] = current;
  186. if (bufferIndex < buffer.Length - 1)
  187. buffer[bufferIndex] |= 0x80;
  188. item >>= 7;
  189. current = (byte)(item & 0x7F);
  190. bufferIndex--;
  191. }
  192. while (current > 0);
  193. for (var i = bufferIndex + 1; i < buffer.Length; i++)
  194. {
  195. bytes.Add(buffer[i]);
  196. }
  197. }
  198. _data.Add(Objectidentifier);
  199. var length = GetLength(bytes.Count);
  200. WriteBytes(length);
  201. WriteBytes(bytes);
  202. }
  203. /// <summary>
  204. /// Writes NULL data into internal buffer.
  205. /// </summary>
  206. public void WriteNull()
  207. {
  208. _data.Add(Null);
  209. _data.Add(0);
  210. }
  211. /// <summary>
  212. /// Writes DerData data into internal buffer.
  213. /// </summary>
  214. /// <param name="data">DerData data to write.</param>
  215. public void Write(DerData data)
  216. {
  217. var bytes = data.Encode();
  218. _data.AddRange(bytes);
  219. }
  220. private static IEnumerable<byte> GetLength(int length)
  221. {
  222. if (length > 127)
  223. {
  224. var size = 1;
  225. var val = length;
  226. while ((val >>= 8) != 0)
  227. size++;
  228. var data = new byte[size];
  229. data[0] = (byte)(size | 0x80);
  230. for (int i = (size - 1) * 8, j = 1; i >= 0; i -= 8, j++)
  231. {
  232. data[j] = (byte)(length >> i);
  233. }
  234. return data;
  235. }
  236. return new[] {(byte) length};
  237. }
  238. private int ReadLength()
  239. {
  240. int length = ReadByte();
  241. if (length == 0x80)
  242. {
  243. throw new NotSupportedException("Indefinite-length encoding is not supported.");
  244. }
  245. if (length > 127)
  246. {
  247. var size = length & 0x7f;
  248. // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
  249. if (size > 4)
  250. throw new InvalidOperationException(string.Format("DER length is '{0}' and cannot be more than 4 bytes.", size));
  251. length = 0;
  252. for (var i = 0; i < size; i++)
  253. {
  254. int next = ReadByte();
  255. length = (length << 8) + next;
  256. }
  257. if (length < 0)
  258. throw new InvalidOperationException("Corrupted data - negative length found");
  259. //if (length >= limit) // after all we must have read at least 1 byte
  260. // throw new IOException("Corrupted stream - out of bounds length found");
  261. }
  262. return length;
  263. }
  264. private void WriteBytes(IEnumerable<byte> data)
  265. {
  266. _data.AddRange(data);
  267. }
  268. private byte ReadByte()
  269. {
  270. if (_readerIndex > _data.Count)
  271. throw new InvalidOperationException("Read out of boundaries.");
  272. return _data[_readerIndex++];
  273. }
  274. private byte[] ReadBytes(int length)
  275. {
  276. if (_readerIndex + length > _data.Count)
  277. throw new InvalidOperationException("Read out of boundaries.");
  278. var result = new byte[length];
  279. _data.CopyTo(_readerIndex, result, 0, length);
  280. _readerIndex += length;
  281. return result;
  282. }
  283. }
  284. }