Visual Studio 如何加密 .pubxml.user 文件中的密码?

How does Visual Studio encrypt passwords in a .pubxml.user file?

当您告诉 Visual Studio 保存发布配置文件的密码时,它会在您的发布文件旁边创建一个 .pubxml.user 文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121. 
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <TimeStampOfAssociatedLegacyPublishXmlFile />
    <EncryptedPassword>AQAAANC[...]</EncryptedPassword>
  </PropertyGroup>
</Project>

Visual Studio 如何加密 EncryptedPassword 元素中的密码?我想解密它,因为我忘记了我的密码...现在它只是加密存储在这个文件中!

数据为DPAPI encrypted. DPAPI encrypted data starts hexadecimal with the byte sequence 0x01000000D08C9DDF0115D1118C7A00C04FC297EB or Base64 encoded with AQAAANCMnd8BFdERjHoAwE/Cl+, here

用C#解密classProtectedData or more precisely the static method ProtectedData.Unprotect can be used. If no value is known for the entropy s_aditionalEntropy, null should be tried. More information about this parameter can be found here

如果加密数据是Base64编码的,解密前必须先Base64解码:

using System.Security.Cryptography;

...
String encryptedDataB64 = "AQAAANCMnd8BFdERjHoAwE/Cl+...";
byte[] encryptedData = Convert.FromBase64String(encryptedDataB64); 

byte[] s_aditionalEntropy = null;
byte[] data = ProtectedData.Unprotect(encryptedData, s_aditionalEntropy, DataProtectionScope.CurrentUser); 

可以在链接的文档中找到更详细的示例。解密不限于 .NET,也可以使用其他语言,前提是存在相应的 DPAPI 包装器,例如在 Python 和 or in Java with Java DPAPI.

这是一个控制台程序,它获取解码数据的 Unicode 字符串表示形式:

using System;
using System.Security.Cryptography;

namespace ConsolePassDecrypter {
    class Program {
        static void Main(string[] args) {
            string encryptedPass = "AQAAANC[...]";
            var decryptedPassBytes = ProtectedData.Unprotect(Convert.FromBase64String(encryptedPass), null, DataProtectionScope.LocalMachine);
            Console.WriteLine("Decrypted pass: " + System.Text.Encoding.Unicode.GetString(decryptedPassBytes));
        }
    }
}