DPAPI 密钥保护方案说明

适用场景:系统部署在客户本地服务器,需要在本地保存服务器密钥、密码等敏感信息,且不希望这些信息以明文形式存在、不希望被轻易拷走到其他机器解密。

一、DPAPI 是什么

DPAPI(Data Protection API)是 Windows 操作系统自带的加密接口,.NET 中通过 System.Security.Cryptography.ProtectedData 直接调用,无需额外安装任何依赖。

它的核心特性:

一句话:密文只能在加密它的那台机器上解开,拷到别的机器就是一堆废数据。

二、核心原理:两种绑定范围

DPAPI 加密时可以选择加密密钥的绑定范围:

范围绑定对象谁能解密
CurrentUser这台机器 + 当前 Windows 用户只有同一台机器、同一个登录用户
LocalMachine仅这台机器(不区分用户)同一台机器上的所有用户都能解
using System.Security.Cryptography;
using System.Text;

// 绑"机器 + 用户"(更严格)
byte[] cipher1 = ProtectedData.Protect(
    Encoding.UTF8.GetBytes("要保护的密钥"),
    null,
    DataProtectionScope.CurrentUser);

// 绑"机器"(略宽松,机器上任何用户可解)
byte[] cipher2 = ProtectedData.Protect(
    Encoding.UTF8.GetBytes("要保护的密钥"),
    null,
    DataProtectionScope.LocalMachine);

建议:如果你的系统以 Windows 服务运行(服务账户固定),用 LocalMachine 更省心,避免"换用户导致解不开";如果对用户隔离有要求,用 CurrentUser。

三、适用前提与限制

DPAPI 非常适合,但也要清楚它的边界:

适合:

不适合 / 注意事项:

  1. 换机器、重装系统、换用户 → 密文全部失效,需要重新加密;
  2. 不能跨机器解密 —— 你无法在开发机上加密好再拷给客户,因为客户机器解不开;
  3. 加密必须在目标客户机器上执行。

四、完整实现代码

1. 工具类(封装加解密)

using System;
using System.Security.Cryptography;
using System.Text;

namespace VolPro.WebApi
{
    /// <summary>
    /// 基于 Windows DPAPI 的敏感信息加解密工具。
    /// 密文绑定本机(及可选用户),换机器无法解密。
    /// </summary>
    public static class DpapiHelper
    {
        private static readonly DataProtectionScope Scope = DataProtectionScope.CurrentUser;

        /// <summary>加密:明文 → Base64 密文(可安全写入配置文件)。</summary>
        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                return plainText;

            byte[] plain = Encoding.UTF8.GetBytes(plainText);
            byte[] cipher = ProtectedData.Protect(plain, null, Scope);
            return Convert.ToBase64String(cipher);
        }

        /// <summary>解密:Base64 密文 → 明文。</summary>
        public static string Decrypt(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
                return cipherText;

            byte[] cipher = Convert.FromBase64String(cipherText);
            byte[] plain = ProtectedData.Unprotect(cipher, null, Scope);
            return Encoding.UTF8.GetString(plain);
        }
    }
}

2. 加密(在客户机器上执行一次)

string plain = "我的服务器密钥";
string cipher = DpapiHelper.Encrypt(plain);
// 把 cipher 写入配置文件,例如 appsettings.json

3. 解密(程序运行时读取)

string cipher = "从配置文件读出来的密文";
string key = DpapiHelper.Decrypt(cipher);
// 用 key 去访问你们的服务

五、配置文件集成方案

appsettings.json(存密文,不存明文)

{
  "Secrets": {
    "ApiKey": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...(加密后的 Base64)",
    "DbPassword": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA..."
  }
}

读取时解密

public class SecretService
{
    private readonly IConfiguration _config;

    public SecretService(IConfiguration config) => _config = config;

    public string ApiKey => DpapiHelper.Decrypt(_config["Secrets:ApiKey"]!);
    public string DbPassword => DpapiHelper.Decrypt(_config["Secrets:DbPassword"]!);
}

六、部署流程(关键)

因为 DPAPI 密文绑机器,正确部署流程必须是"在客户机器上加密":

  1. 交付时,配置文件里的敏感项留空或填占位符;
  2. 提供一个初始化工具(命令行小工具,或程序内置"首次初始化"功能):

- 在客户机器上运行;

- 输入真实密钥明文;

- 工具用 DPAPI 加密,把密文写进配置文件;

  1. 主程序启动时读取密文并解密使用;
  2. 之后该机器上程序正常运行,密文无法被拷到别处解密。
注意:DPAPI 绑定的是"机器 + 用户"。如果程序以 Windows 服务运行,加密和解密必须使用同一个服务账户,否则解不开。建议服务固定账户 + LocalMachine 范围。

七、DPAPI 的局限与补充

DPAPI 解决的是"密钥不在代码里明文存在、且绑死机器",但它不是万能的,要结合其他措施:

问题DPAPI 能否解决补充措施
密钥在代码里明文✅ 能(密文外置 + 运行解密)—
密文被拷到别的机器✅ 能(绑机器解不开)—
代码被反编译❌ 不能代码混淆、加壳
运行时内存中的密钥被抓取❌ 不能缩短密钥使用窗口、及时清内存
密钥泄露后的损失控制❌ 不能每客户独立密钥、可吊销轮换

八、环境说明

九、常见问题

Q1:为什么换台机器就解不开?

因为加密密钥由 Windows 绑定在"机器 + 用户"上,别的机器没有这把密钥,自然解不开——这正是我们要的保护效果。

Q2:我能在开发机上加密好,拷到客户机器用吗?

不能。密文绑定了你开发机的密钥,客户机器解不开。必须在客户机器上执行加密。

Q3:重装系统后密文还能用吗?

不能。系统重装会重新生成机器的加密密钥,旧密文失效,需要重新加密。

Q4:CurrentUser 和 LocalMachine 怎么选?

程序以 Windows 服务(固定服务账户)运行 → 选 LocalMachine;需要用户级隔离 → 选 CurrentUser。加密和解密两端必须用同一个范围、同一个账户。