如何使用 DPAPI 加密敏感配置信息?

解读

国内 Windows 桌面项目(尤其是政府、金融、医疗内网)对“数据不出本机”有硬性合规要求。配置文件里若出现明文连接串、私钥、第三方 API Secret,等保测评直接亮红灯。DPAPI 是 Windows 自带的用户级或机器级加密设施,无需额外证书管理,也不依赖 SQL Server 的 TDE 或第三方库,在 VB.NET 面试里被频繁追问。面试官想确认三点:

  1. 知道 DPAPI 只能解决“存储”问题,不能解决“传输”问题;
  2. 能区分 CurrentUser 与 LocalMachine 作用域,并给出选型理由;
  3. 能把加解密流程封装成可复用的类,而不是在按钮事件里裸写两行代码。

知识点

  1. System.Security.Cryptography.ProtectedData 类,位于 System.Security.dll(.NET Framework 2.0+ 自带,无需 NuGet)。
  2. 枚举 DataProtectionScope:CurrentUser(只能由同一 Windows 账户解密)、LocalMachine(任何账户只要拥有机器令牌即可解密)。
  3. 熵 entropy:可选附加字节数组,防止同一台机器不同应用互相“撞库”解密;国内习惯用固定 GUID 字符串转字节,便于运维统一。
  4. 配置文件存放形式:常见做法是把密文 Base64 后写入 appSettings,再配套写一个“配置管理器”在程序启动时解密到内存,全程不落地明文。
  5. 权限与合规:LocalMachine 需管理员安装时写一次,普通运行时只读;CurrentUser 适合普通用户无管理员场景,但漫游配置文件会导致异地无法解密,需提前评估。
  6. 异常处理:DPAPI 依赖用户配置文件,若 ASP.NET 或计划任务用 LocalSystem 账户,会抛 CryptographicException,必须 catch 并给出降级提示。
  7. 与 CNG、AES 区别:DPAPI 是高层封装,密钥由操作系统托管,无法导出,适合“不想管密钥”的场景;若审计要求“密钥可备份”,需改用 RSA+CNG 或 HSM。

答案

下面给出可直接搬进简历项目的 VB.NET 完整示例,含注释与异常处理,面试时手写骨架即可。

' 1. 引入命名空间
Imports System.Security.Cryptography
Imports System.Text

''' <summary>
''' DPAPI 工具类,负责敏感配置加解密
''' </summary>
Public NotInheritable Class DpapiHelper
    ' 固定熵,防止不同应用间串扰;实际项目可放到安装参数或注册表
    Private Shared ReadOnly Entropy As Byte() = Encoding.UTF8.GetBytes("3FA8E3B1-4D92-4F3C-9C1D-7E4F3E2A1B00")

    ' 加密
    Public Shared Function Encrypt(plainText As String) As String
        If String.IsNullOrEmpty(plainText) Then Return String.Empty
        Dim plainBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
        Dim cipherBytes As Byte() = ProtectedData.Protect(plainBytes, Entropy, DataProtectionScope.CurrentUser)
        Return Convert.ToBase64String(cipherBytes)
    End Function

    ' 解密
    Public Shared Function Decrypt(cipherBase64 As String) As String
        If String.IsNullOrEmpty(cipherBase64) Then Return String.Empty
        Try
            Dim cipherBytes As Byte() = Convert.FromBase64String(cipherBase64)
            Dim plainBytes As Byte() = ProtectedData.Unprotect(cipherBytes, Entropy, DataProtectionScope.CurrentUser)
            Return Encoding.UTF8.GetString(plainBytes)
        Catch ex As CryptographicException
            ' 日志记录,返回空表示解密失败
            My.Application.Log.WriteException(ex)
            Return String.Empty
        End Try
    End Function
End Class

' 2. 使用示例(可放在 Sub Main 或 Form_Load)
Sub LoadConnectionString()
    Dim cipher As String = ConfigurationManager.AppSettings("DbCipher")
    Dim conn As String = DpapiHelper.Decrypt(cipher)
    If String.IsNullOrEmpty(conn) Then
        MessageBox.Show("配置解密失败,请确认当前用户权限")
        Environment.Exit(-1)
    End If
    ' 后续使用 conn 访问数据库
End Sub

' 3. 首次写入配置的工具(安装包或运维小工具)
Sub SaveConnectionString(plainConn As String)
    Dim cipher As String = DpapiHelper.Encrypt(plainConn)
    Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    config.AppSettings.Settings("DbCipher").Value = cipher
    config.Save(ConfigurationSaveMode.Modified)
End Sub

面试口述要点:

  • 用 ProtectedData.Protect/Unprotect 两行核心 API;
  • 必须加 try-catch CryptographicException,防止用户配置文件丢失;
  • Entropy 用固定 GUID,方便运维;
  • 选型 CurrentUser,解释“若用 LocalMachine 需管理员写一次,普通运行只读”;
  • 密文落地为 Base64,不污染 XML 格式;
  • 内存中保存明文,用完即弃,避免长时间驻留。

拓展思考

  1. 集群部署:Windows 服务在 50 台终端运行,用 LocalMachine 可避免“每台机不同用户”导致无法解密,但需安装程序以管理员身份提前写入;如何批量推送?可结合 MSI 自定义动作或域脚本。
  2. 密钥轮换:DPAPI 本身不支持“过期”,若合规要求一年一换,只能在年初由运维小工具重新加密一次并推送新配置文件;或者放弃 DPAPI,改用 Azure Key Vault + MSI。
  3. 与 REG_SZ 结合:有些甲方要求“配置写注册表”,可把 Base64 密文放 HKLM\SOFTWARE\MyApp,安装时写、运行时读,仍用同一套类。
  4. 与 ClickOnce 兼容:ClickOnce 每次升级会换目录,导致 entropy 文件路径变;此时 entropy 必须固定写死或放用户漫游目录,避免升级后解密失败。
  5. 审计留痕:DPAPI 调用本身不写 Windows 事件日志,若等保要求“谁何时解密”,需在 Decrypt 方法里手动写一条审计日志到本地 Windows 事件源,供 SOC 采集。