在Powershell中使用机器密钥加密字符串?

iTa*_*ayb 3 powershell cryptography password-encryption powershell-5.0

我想在Powershell中加密密码以将其保存到文件中。在ConvertTo-SecureString使用当前的凭据进行加密和解密的字符串。

我想使用本地计算机密钥(可能是SYSTEM帐户凭据)对其进行加密,以便同一台计算机上的每个用户名都可以使用该密码。

我希望该字符串在其他计算机上不可解密。

iTa*_*ayb 5

可以将[Security.Cryptography.ProtectedData]::Protect函数与[Security.Cryptography.DataProtectionScope]::LocalMachine实体一起使用。

代码示例:

Function Encrypt-WithMachineKey($s) {
    Add-Type -AssemblyName System.Security

    $bytes = [System.Text.Encoding]::Unicode.GetBytes($s)
    $SecureStr = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine)
    $SecureStrBase64 = [System.Convert]::ToBase64String($SecureStr)
    return $SecureStrBase64
}

Function Decrypt-WithMachineKey($s) {
    Add-Type -AssemblyName System.Security

    $SecureStr = [System.Convert]::FromBase64String($s)
    $bytes = [Security.Cryptography.ProtectedData]::Unprotect($SecureStr, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine)
    $Password = [System.Text.Encoding]::Unicode.GetString($bytes)
    return $Password
}
Run Code Online (Sandbox Code Playgroud)

  • 好的发现这个,有点旧但信息丰富:https://support.microsoft.com/en-us/help/309408/how-to-troubleshoot-the-data-protection-api-dpapi 也值得注意使用的风险DPAPI:https://www.harmj0y.net/blog/redteaming/operational-guidance-for-offensive-user-dpapi-abuse/ (2认同)