Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

121 linhas
5.5 KiB

  1. /* Copyright (C) 2008-2016 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. * THE SOFTWARE.
  20. */
  21. using System;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Runtime.InteropServices;
  25. using System.Security;
  26. namespace Alphaleonis.Win32.Filesystem
  27. {
  28. public static partial class File
  29. {
  30. #region Public Methods
  31. /// <summary>Decrypts a file that was encrypted by the current account using the Encrypt method.</summary>
  32. /// <param name="path">A path that describes a file to decrypt.</param>
  33. [SecurityCritical]
  34. public static void Decrypt(string path)
  35. {
  36. EncryptDecryptFileCore(false, path, false, PathFormat.RelativePath);
  37. }
  38. /// <summary>[AlphaFS] Decrypts a file that was encrypted by the current account using the Encrypt method.</summary>
  39. /// <param name="path">A path that describes a file to decrypt.</param>
  40. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  41. [SecurityCritical]
  42. public static void Decrypt(string path, PathFormat pathFormat)
  43. {
  44. EncryptDecryptFileCore(false, path, false, pathFormat);
  45. }
  46. /// <summary>Encrypts a file so that only the account used to encrypt the file can decrypt it.</summary>
  47. /// <param name="path">A path that describes a file to encrypt.</param>
  48. [SecurityCritical]
  49. public static void Encrypt(string path)
  50. {
  51. EncryptDecryptFileCore(false, path, true, PathFormat.RelativePath);
  52. }
  53. /// <summary>[AlphaFS] Encrypts a file so that only the account used to encrypt the file can decrypt it.</summary>
  54. /// <param name="path">A path that describes a file to encrypt.</param>
  55. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  56. [SecurityCritical]
  57. public static void Encrypt(string path, PathFormat pathFormat)
  58. {
  59. EncryptDecryptFileCore(false, path, true, pathFormat);
  60. }
  61. #endregion
  62. #region Internal Methods
  63. /// <summary>Decrypts/encrypts a file or directory so that only the account used to encrypt the file can decrypt it.</summary>
  64. /// <exception cref="NotSupportedException"/>
  65. /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
  66. /// <param name="path">A path that describes a file to encrypt.</param>
  67. /// <param name="encrypt"><see langword="true"/> encrypt, <see langword="false"/> decrypt.</param>
  68. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  69. [SecurityCritical]
  70. internal static void EncryptDecryptFileCore(bool isFolder, string path, bool encrypt, PathFormat pathFormat)
  71. {
  72. string pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
  73. // Reset file/directory attributes.
  74. // MSDN: If lpFileName specifies a read-only file, the function fails and GetLastError returns ERROR_FILE_READ_ONLY.
  75. SetAttributesCore(isFolder, null, pathLp, FileAttributes.Normal, PathFormat.LongFullPath);
  76. // EncryptFile() / DecryptFile()
  77. // In the ANSI version of this function, the name is limited to 248 characters.
  78. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
  79. // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
  80. if (!(encrypt
  81. ? NativeMethods.EncryptFile(pathLp)
  82. : NativeMethods.DecryptFile(pathLp, 0)))
  83. {
  84. int lastError = Marshal.GetLastWin32Error();
  85. switch ((uint)lastError)
  86. {
  87. case Win32Errors.ERROR_ACCESS_DENIED:
  88. string root = Path.GetPathRoot(pathLp, false);
  89. if (!string.Equals("NTFS", new DriveInfo(root).DriveFormat, StringComparison.OrdinalIgnoreCase))
  90. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "The drive does not support NTFS encryption: [{0}]", root));
  91. break;
  92. default:
  93. if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND && isFolder)
  94. lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND;
  95. NativeError.ThrowException(lastError, pathLp);
  96. break;
  97. }
  98. }
  99. }
  100. #endregion // Internal Methods
  101. }
  102. }