SecBuffer.cs 2.3 KB

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