在上一篇咱們知道了,在不一樣的user account和workstations, 如何使用AES key去生成SecureString。咱們須要去保護好Key,以避免遭非法者解密數據保護。數組
在以前的例子中,我使用一個很是簡單的16-byte 數組存儲在腳本自己的主體。 這不是一個好的作法, 這和你密碼用明文表示本質上是同樣的。或者你能夠在一個隔離的腳本里提早生成一個key。
bash
做爲一個例子,我已經創建了一個小腳本生成一個隨機的16-byte數組。 我用System.Security.Cryptography.RNGCryptoServiceProvider 類隨機生成的數據來填充一個字節數組。dom
Creating AES key with random data and export to file
ide
$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 objectblog
$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 objectget
$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. 加域腳本it
$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"io
執行後系統提示須要重啓生效。class
2. 退域腳本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) Remove-Computer -UnjoinDomainCredential $MyCredential -PassThru -Verbose -Restart
將上面退域腳本另存爲"Unjoindomain.ps1",右鍵執行「Run with PowerShell」
執行完畢,會自動重啓,整個退域過程結束。