DerEncodingHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* Copyright (C) 2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using Utilities;
  10. namespace SMBLibrary.Authentication
  11. {
  12. public enum DerEncodingTag : byte
  13. {
  14. ByteArray = 0x04,
  15. ObjectIdentifier = 0x06,
  16. Enum = 0x0A,
  17. Sequence = 0x30,
  18. }
  19. public class DerEncodingHelper
  20. {
  21. public static int ReadLength(byte[] buffer, ref int offset)
  22. {
  23. int length = ByteReader.ReadByte(buffer, ref offset);
  24. if (length >= 0x80)
  25. {
  26. int lengthFieldSize = (length & 0x7F);
  27. byte[] lengthField = ByteReader.ReadBytes(buffer, ref offset, lengthFieldSize);
  28. length = 0;
  29. foreach (byte value in lengthField)
  30. {
  31. length *= 256;
  32. length += value;
  33. }
  34. }
  35. return length;
  36. }
  37. public static void WriteLength(byte[] buffer, ref int offset, int length)
  38. {
  39. if (length >= 0x80)
  40. {
  41. List<byte> values = new List<byte>();
  42. do
  43. {
  44. byte value = (byte)(length % 256);
  45. values.Add(value);
  46. length = value / 256;
  47. }
  48. while (length > 0);
  49. values.Reverse();
  50. byte[] lengthField = values.ToArray();
  51. ByteWriter.WriteByte(buffer, ref offset, (byte)(0x80 | lengthField.Length));
  52. ByteWriter.WriteBytes(buffer, ref offset, lengthField);
  53. }
  54. else
  55. {
  56. ByteWriter.WriteByte(buffer, ref offset, (byte)length);
  57. }
  58. }
  59. public static int GetLengthFieldSize(int length)
  60. {
  61. if (length >= 0x80)
  62. {
  63. int result = 1;
  64. do
  65. {
  66. length = length / 256;
  67. result++;
  68. }
  69. while(length > 0);
  70. return result;
  71. }
  72. else
  73. {
  74. return 1;
  75. }
  76. }
  77. }
  78. }