SecBufferDesc.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Copyright (C) 2014-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 System.Runtime.InteropServices;
  10. namespace SMBLibrary.Win32.Security
  11. {
  12. [StructLayout(LayoutKind.Sequential)]
  13. public struct SecBufferDesc : IDisposable
  14. {
  15. public const uint SECBUFFER_VERSION = 0;
  16. public uint ulVersion;
  17. public uint cBuffers; // Indicates the number of SecBuffer structures in the pBuffers array.
  18. public IntPtr pBuffers; // Pointer to an array of SecBuffer structures.
  19. public SecBufferDesc(SecBuffer buffer) : this(new SecBuffer[] { buffer })
  20. {
  21. }
  22. public SecBufferDesc(SecBuffer[] buffers)
  23. {
  24. int secBufferSize = Marshal.SizeOf(typeof(SecBuffer));
  25. ulVersion = SECBUFFER_VERSION;
  26. cBuffers = (uint)buffers.Length;
  27. pBuffers = Marshal.AllocHGlobal(buffers.Length * secBufferSize);
  28. IntPtr currentBuffer = pBuffers;
  29. for (int index = 0; index < buffers.Length; index++)
  30. {
  31. Marshal.StructureToPtr(buffers[index], currentBuffer, false);
  32. currentBuffer = new IntPtr(currentBuffer.ToInt64() + secBufferSize);
  33. }
  34. }
  35. public byte[] GetBufferBytes(int bufferIndex)
  36. {
  37. if (pBuffers == IntPtr.Zero)
  38. {
  39. throw new ObjectDisposedException("pBuffers");
  40. }
  41. int secBufferSize = Marshal.SizeOf(typeof(SecBuffer));
  42. IntPtr pBuffer = new IntPtr(pBuffers.ToInt64() + secBufferSize * bufferIndex);
  43. SecBuffer secBuffer = (SecBuffer)Marshal.PtrToStructure(pBuffer, typeof(SecBuffer));
  44. return secBuffer.GetBufferBytes();
  45. }
  46. public void Dispose()
  47. {
  48. if (pBuffers != IntPtr.Zero)
  49. {
  50. Marshal.FreeHGlobal(pBuffers);
  51. pBuffers = IntPtr.Zero;
  52. }
  53. }
  54. }
  55. }