华域联盟 PowerShell Powershell实现加密解密文本文件方法实例

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实现加密解密文本文件方法实例

转载请保留出处和原文链接:https://www.cnhackhy.com/15069.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部