SecBuffer.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. public enum SecBufferType : uint
  13. {
  14. SECBUFFER_EMPTY = 0,
  15. SECBUFFER_DATA = 1,
  16. SECBUFFER_TOKEN = 2
  17. }
  18. [StructLayout(LayoutKind.Sequential)]
  19. public struct SecBuffer : IDisposable
  20. {
  21. public uint cbBuffer; // Specifies the size, in bytes, of the buffer pointed to by the pvBuffer member.
  22. public uint BufferType;
  23. public IntPtr pvBuffer; // A pointer to a buffer.
  24. public SecBuffer(int bufferSize)
  25. {
  26. cbBuffer = (uint)bufferSize;
  27. BufferType = (uint)SecBufferType.SECBUFFER_TOKEN;
  28. pvBuffer = Marshal.AllocHGlobal(bufferSize);
  29. }
  30. public SecBuffer(byte[] secBufferBytes)
  31. {
  32. cbBuffer = (uint)secBufferBytes.Length;
  33. BufferType = (uint)SecBufferType.SECBUFFER_TOKEN;
  34. pvBuffer = Marshal.AllocHGlobal(secBufferBytes.Length);
  35. Marshal.Copy(secBufferBytes, 0, pvBuffer, secBufferBytes.Length);
  36. }
  37. public SecBuffer(byte[] secBufferBytes, SecBufferType bufferType)
  38. {
  39. cbBuffer = (uint)secBufferBytes.Length;
  40. BufferType = (uint)bufferType;
  41. pvBuffer = Marshal.AllocHGlobal(secBufferBytes.Length);
  42. Marshal.Copy(secBufferBytes, 0, pvBuffer, secBufferBytes.Length);
  43. }
  44. public void Dispose()
  45. {
  46. if (pvBuffer != IntPtr.Zero)
  47. {
  48. Marshal.FreeHGlobal(pvBuffer);
  49. pvBuffer = IntPtr.Zero;
  50. }
  51. }
  52. public byte[] GetBufferBytes()
  53. {
  54. byte[] buffer = null;
  55. if (cbBuffer > 0)
  56. {
  57. buffer = new byte[cbBuffer];
  58. Marshal.Copy(pvBuffer, buffer, 0, (int)cbBuffer);
  59. }
  60. return buffer;
  61. }
  62. }
  63. }