windows - 以加密形式存储文本并在 powershell 脚本中使用而不向其他用户泄露?

标签 windows powershell scripting

我想对要在不同 PowerShell 脚本中使用的文本进行加密,而不会影响其安全性,因为其他用户将使用包含该文本的脚本。基本上,我想向所有人隐藏该文本,并使用它,而不会对使用该特定文本的所有 PowerShell 脚本产生任何麻烦。文本可以存储在文件中,以便在不同的脚本中使用。我尝试过基本的事情,例如:

$text = Read-Host "Enter the text" -AsSecureString

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($text)

$Plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host "Text is: " $PlainText

但问题是,如果您在同一台计算机上,很容易找到它。我需要一些万无一失的方法(如果有的话)。这是我的第一个问题,所以请忽略我的错误(如果有)。

最佳答案

在您的情况下,您需要一个特定的 key 来加密字符串。

用于设置 key :

function Set-Key {
param([string]$string)
$length = $string.length
$pad = 32-$length
if (($length -lt 16) -or ($length -gt 32)) {Throw "String must be between 16 and 32 characters"}
$encoding = New-Object System.Text.ASCIIEncoding
$bytes = $encoding.GetBytes($string + "0" * $pad)
return $bytes
}

用于设置加密数据:

function Set-EncryptedData {
param($key,[string]$plainText)
$securestring = new-object System.Security.SecureString
$chars = $plainText.toCharArray()
foreach ($char in $chars) {$secureString.AppendChar($char)}
$encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key
return $encryptedData
}

用于解密数据:

function Get-EncryptedData {
param($key,$data)
$data | ConvertTo-SecureString -key $key |
ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))}
}

使用方法:

$plainText = "Some Super Secret Password"
$key = Set-Key "AGoodKeyThatNoOneElseWillKnow"
$encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext
$encryptedTextThatIcouldSaveToFile  ## - sample output 507964ed3a197b26969adead0212743c378a478c64007c477efbb21be5748670a7543cb21135ec324e37f80f66d17c76c4a75f6783de126658bce09ef19d50da
$DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key $key
$DecryptedText

引用链接:Encrypting & Decrypting Strings with PS

希望有帮助。

关于windows - 以加密形式存储文本并在 powershell 脚本中使用而不向其他用户泄露?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801713/

相关文章:

windows - Windows服务自动部署-工具

windows - Batch Then此时出乎意料

windows - bat 文件、函数和插入符号

json - 在PowerShell中了解NewtonSoft

linux - 计算文件中的特定单词

windows - easyphp .htaccess 规则

powershell - 运行pester测试时如何使管道中的输出出现在控制台上?

linux - Shell 脚本支持——不同 URL 上的多个 nslookups

linux - 如何在脚本中运行 gcc 命令来执行 main.c

windows - Powershell 检索作业给出 "cannot index into null array error"