SecureString.Windows.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime;
  6. using System.Runtime.InteropServices;
  7. using System.Security.Cryptography;
  8. namespace System.Security
  9. {
  10. public sealed partial class SecureString
  11. {
  12. private static int GetAlignedByteSize(int length)
  13. {
  14. int byteSize = Math.Max(length, 1) * sizeof(char);
  15. const int blockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE;
  16. return ((byteSize + (blockSize - 1)) / blockSize) * blockSize;
  17. }
  18. private void ProtectMemory()
  19. {
  20. Debug.Assert(_buffer != null);
  21. Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
  22. if (_decryptedLength != 0 &&
  23. !_encrypted &&
  24. !Interop.Crypt32.CryptProtectMemory(_buffer, (uint)_buffer.ByteLength, Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
  25. {
  26. throw new CryptographicException(Marshal.GetLastWin32Error());
  27. }
  28. _encrypted = true;
  29. }
  30. private void UnprotectMemory()
  31. {
  32. Debug.Assert(_buffer != null);
  33. Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
  34. if (_decryptedLength != 0 &&
  35. _encrypted &&
  36. !Interop.Crypt32.CryptUnprotectMemory(_buffer, (uint)_buffer.ByteLength, Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
  37. {
  38. throw new CryptographicException(Marshal.GetLastWin32Error());
  39. }
  40. _encrypted = false;
  41. }
  42. }
  43. }