Powershell实现加密解密文本文件方法实例
适用于Powershell3.0及以后版本。
假设你需要给文件加密,下面教你如何给自己的文件加密:
$Path="$env:temp\secret.txt" $Secret='HelloWorld!' $Passphrase='Somesecretkey' $key=[Byte[]]($Passphrase.PadRight(24).Substring(0,24).ToCharArray()) $Secret| ConvertTo-SecureString-AsPlainText-Force| ConvertFrom-SecureString-Key$key| Out-File-FilePath$Path notepad$Path
当你需要解密出里面的内容,这时就需要最初的密码:
$Passphrase=Read-Host'Enterthesecretpassphrase'
$Path="$env:temp\secret.txt"
$key=[Byte[]]($Passphrase.PadRight(24).Substring(0,24).ToCharArray())
try
{
$decryptedTextSecureString=Get-Content-Path$Path-Raw|
ConvertTo-SecureString-Key$key-ErrorActionStop
$cred=New-Object-TypeNameSystem.Management.Automation.PSCredential('dummy',$decryptedTextSecureString)
$decryptedText=$cred.GetNetworkCredential().Password
}
catch
{
$decryptedText='(wrongkey)'
}
"Thedecryptedsecrettext:$decryptedText"
热门推荐
10 离职送别文案祝福语简短
11 工资涨高祝福语简短
12 孙子生日祝福语简短精辟
13 文案生日祝福语高级简短
14 中医经典祝福语大全简短
15 上级生日祝福语 简短独特
16 写春节祝福语简短的
17 中考祝福语给同学简短
18 送偶像生日祝福语简短