Powershell实现加密解密文本文件方法实例
更新时间:2015年04月11日 09:28:53 投稿:junjie
这篇文章主要介绍了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小技巧之使用Get-ChildItem得到指定扩展名文件
本文主要描述了使用Get-ChildItem得到指定扩展名文件的方法以及示例,并介绍了Get-ChildItem混合使用参数的问题,有需要的朋友可以参考下2014-09-09
探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
我们经常在程序设计中用到的数组,同样在脚本中很常用。本节就详细介绍一下数组,以及哈希表在PowerShell中的使用2012-12-12


最新评论