我想在 Powershell 中加密密码以将其保存到文件中。 ConvertTo-SecureString
使用当前凭据来加密和解密字符串。
我想用本地机器 key (可能是 SYSTEM 帐户凭据)对其进行加密,以便同一台计算机上的每个用户名都可以使用密码。
我希望该字符串在其他计算机上无法解密。
最佳答案
可以使用 [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
}
关于powershell - 使用Powershell中的机器 key 加密字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46400234/