在上一篇我們知道了,在不同的user account和workstations, 如何使用AES key去生成SecureString。我們需要去保護好Key,以免遭非法者解密數據保護。
在之前的例子中,我使用一個非常簡單的16-byte 數組存儲在腳本本身的主體。 這不是一個好的做法, 這和你密碼用明文表示本質上是一樣的。或者你可以在一個隔離的腳本里提前生成一個key。
作爲一個例子,我已經建立了一個小腳本生成一個隨機的16-byte數組。 我用System.Security.Cryptography.RNGCryptoServiceProvider 類隨機生成的數據來填充一個字節數組。
Creating AES key with random data and export to file
$KeyFile = "\\SHSV2019\SharePath\AES.key" $Key = New-Object Byte[] 16 #You can use 16, 24, or 32 for AES [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key) $Key | Out-File $KeyFile
Creating SecureString object
$PasswordFile = "\\SHSV2019\SharePath\Password.txt" $KeyFile = "\\SHSV2019\SharePath\AES.key" $Key = Get-Content $KeyFile # $Password = "P@ssword" | ConvertTo-SecureString -AsPlainText -Force $Password | ConvertFrom-SecureString -Key $Key | Out-File $PasswordFile
Creating PSCredential object
$User = "contoso\jason" $PasswordFile = "\\SHSV2019\SharePath\Password.txt" $KeyFile = "\\SHSV2019\SharePath\AES.key" $Key = Get-Content $KeyFile $MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key)
1. 加域腳本
$User = "contoso\jason" $PasswordFile = "\\SHSV2019\SharePath\Password.txt" $KeyFile = "\\SHSV2019\SharePath\AES.key" $Key = Get-Content $KeyFile $MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key) Add-Computer -DomainName contoso.com -Credential $MyCredential
將上面的加域腳本另存爲"Joindomain.PS1"通過右鍵執行"Run with PowerShell"
執行後系統提示需要重啓生效。
2. 退域腳本
$User = "contoso\jason" $PasswordFile = "\\SHSV2019\SharePath\Password.txt" $KeyFile = "\\SHSV2019\SharePath\AES.key" $Key = Get-Content $KeyFile $MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key) Remove-Computer -UnjoinDomainCredential $MyCredential -PassThru -Verbose -Restart
將上面退域腳本另存爲"Unjoindomain.ps1",右鍵執行“Run with PowerShell”
執行完畢,會自動重啓,整個退域過程結束。