-
Notifications
You must be signed in to change notification settings - Fork 3
/
Convert-CaesarCipher.ps1
98 lines (81 loc) · 2.97 KB
/
Convert-CaesarCipher.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<#
.SYNOPSIS
Practicing with functions just for fun. Convert-CaesarCipher encodes or decodes case-sensitive English strings based on the Caesar Cipher.
.DESCRIPTION
Practicing with functions just for fun. Convert-CaesarCipher encodes or decodes case-sensitive English strings based on the Caesar Cipher.
https://en.wikipedia.org/wiki/Caesar_cipher
.EXAMPLE
Convert-CaesarCipher -InputString "Hello World" -Shift 20
# Encode is the default.
# Returns: Byffi Qilfx
.EXAMPLE
"Hello World" | Convert-CaesarCipher -Shift 20
# Pipeline input is accepted.
# Returns: Byffi Qilfx
.EXAMPLE
Convert-CaesarCipher "Hello World" -Shift 20
# InputString is a positional parameter.
# Returns: Byffi Qilfx
.EXAMPLE
Convert-CaesarCipher -InputString "Hello World" -Shift 20 -Encode
# You can also specify Encode to avoid confusion.
# Returns: Byffi Qilfx
.EXAMPLE
Convert-CaesarCipher -InputString "Byffi Qilfx" -Shift 20 -Decode
# Returns: Hello World
.LINK
https://mikecrowley.us
#>
function Convert-CaesarCipher {
[CmdletBinding(DefaultParameterSetName = 'Encode')]
param (
[parameter(ParameterSetName = "Encode")][switch]$Encode,
[parameter(ParameterSetName = "Decode")][switch]$Decode,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0,
HelpMessage = "Please provide an input string containing only English letters spaces."
)]
[ValidateScript({
if ($_ -match '^[a-z ]+$') { $true } else { throw "Input must contain only English letters spaces." }
})]
[string]$InputString,
[Parameter(
Mandatory = $true,
HelpMessage = "Please provide a numerical Shift value."
)]
[int]$Shift
)
$LowerAlphabet = "abcdefghijklmnopqrstuvwxyz"
$UpperAlphabet = $LowerAlphabet.ToUpper()
$output = ""
foreach ($Char in $InputString.ToCharArray()) {
[string]$StringChar = $Char
if ($StringChar -eq " ") {
$output += " "
}
elseif ($StringChar.ToUpper() -ceq $StringChar) {
if ($Decode) {
$index = ($UpperAlphabet.IndexOf($StringChar) - $Shift) % $UpperAlphabet.Length
$output += $UpperAlphabet[$index]
}
else {
$index = ($UpperAlphabet.IndexOf($StringChar) + $Shift) % $UpperAlphabet.Length
$output += $UpperAlphabet[$index]
}
}
else {
if ($Decode) {
$index = ($LowerAlphabet.IndexOf($StringChar) - $Shift) % $LowerAlphabet.Length
$output += $LowerAlphabet[$index]
}
else {
$index = ($LowerAlphabet.IndexOf($StringChar) + $Shift) % $LowerAlphabet.Length
$output += $LowerAlphabet[$index]
}
}
}
return $output
}