You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nushell中如何实现PowerShell的安全凭据存储与恢复?

在Nushell中实现类似PowerShell的加密凭据存储

Nushell目前没有内置的Get-Credential/Export-Clixml等效命令,但可以结合Windows DPAPI(和PowerShell使用的加密机制一致)与Nushell的特性实现相同的安全存储效果,具体步骤如下:

存储凭据

执行以下Nushell命令,将用户名和密码加密后保存到文件:

# 获取用户名和安全输入的密码
let username = read "输入用户名: "
let password = read --secure "输入密码: "

# 将密码转为字节数组,用DPAPI加密(仅当前用户可解密)
let encrypted_pwd = (
    [System.Text.Encoding]::UTF8.GetBytes($password)
    | [System.Security.Cryptography.ProtectedData]::Protect($in, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
    | [System.Convert]::ToBase64String($in)
)

# 将凭据保存为JSON文件
{ username: $username, encrypted_password: $encrypted_pwd } | save --indent 2 mycredentials.json

恢复凭据

执行以下命令读取并解密凭据:

# 读取保存的凭据文件
let cred_data = load mycredentials.json

# 解密密码
let password = (
    [System.Convert]::FromBase64String($cred_data.encrypted_password)
    | [System.Security.Cryptography.ProtectedData]::Unprotect($in, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
    | [System.Text.Encoding]::UTF8.GetString($in)
)

# 构建凭据对象(可按需使用)
let cred = { username: $cred_data.username, password: $password }

安全性说明

  • 该实现使用Windows DPAPI加密,和PowerShell的Export-Clixml机制完全一致:加密后的密码仅能在同一机器的同一用户账户下解密,文件被盗或其他用户/机器无法读取明文密码。
  • 若需跨平台支持(Linux/macOS),可替换DPAPI为对应系统的密钥环工具(如Linux的libsecret、macOS的security命令),但加密逻辑需要调整。

内容的提问来源于stack exchange,提问作者Alejandro Bermúdez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:57:05