移位密码循环功能

时间:2016-09-26 08:11:59

标签: powershell shift caesar-cipher

我想得到一些帮助来修改这个代码,使其成为循环解密函数,从密钥输出加密的消息(1-26)。我们最简单的方法是什么?另一个ForEach循环?

$key = Read-Host "Key value:" 
$msg = Read-Host "Enter Message"
Write-Host "Encrypted Message: " $msg -ForegroundColor "white"
$String = [char[]]$msg

$array = [char[]]$msg
foreach ($letter in $array)
{
    $nbr = [int[]][char]$letter
    if ($nbr -ge 65 -and $nbr -le 90) #UpperCase
    {
        [string]$Snbr = $nbr
        [int]$Nnbr = $Snbr 
        [int]$nkey = $key
        [int]$Enbr = $Nnbr - $nkey 
        if ($Enbr -gt 90) {$Enbr = $Enbr - 26}
        if ($Enbr -lt 65) {$Enbr = $Enbr + 26}
        [string]$ELetter = [char]$Enbr       
    }  

    if ($nbr -ge 97 -and $nbr -le 122) #LowerCase
    {
        [string]$Snbr = $nbr
        [int]$Nnbr = $Snbr 
        [int]$nkey = $key
        [int]$Enbr = $Nnbr - $nkey 
        if ($Enbr -gt 122) {$Enbr = $Enbr - 26}
        if ($Enbr -lt 97)  {$Enbr = $Enbr + 26}
        [string]$ELetter = [char]$Enbr       
    }    
    $EMsg = $EMsg + $ELetter    
}
Write-Host "PlainText: " $EMsg -ForegroundColor "white"

1 个答案:

答案 0 :(得分:0)

也许下一个评论代码存根可以提供帮助:

$String = [char[]]$msg
$EMsg = ''                     ### initialize `$EMsg` variable
$array = [char[]]$msg
foreach ($letter in $array)
{
    $ELetter = $letter         ### initialize `$ELetter` in advance for case that `$letter`
                               ### is not UpperCase nor LowerCase letter
    $nbr = [int[]][char]$letter
    if ($nbr -ge 65 -and $nbr -le 90) #UpperCase

...