Powershell实现加密解密文本文件方法实例

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Powershell实现加密解密文本文件方法实例脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

适用于Powershell3.0及以后版本。
假设你需要给文件加密,下面教你如何给自己的文件加密:

$Path = "$env:temp\secret.txt"
$Secret = 'Hello World!'
$Passphrase = 'Some secret key'
 
$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 'Enter the secret pass phrase'
 
$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 -ErrorAction Stop
 
 $cred = New-Object -tyPEName System.Management.Automation.PSCredential('dummy', $decryptedTextSecureString)
 $decryptedText = $cred.GetNetworkCredential().Password
}
catch
{
 $decryptedText = '(wrong key)'
}
"The decrypted secret text: $decryptedText"

脚本宝典总结

以上是脚本宝典为你收集整理的Powershell实现加密解密文本文件方法实例全部内容,希望文章能够帮你解决Powershell实现加密解密文本文件方法实例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。