-
Notifications
You must be signed in to change notification settings - Fork 0
/
vignere_cipher.groovy
109 lines (84 loc) · 3.03 KB
/
vignere_cipher.groovy
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
99
100
101
102
103
104
105
106
107
108
109
class VigenereCipher {
private keyArray
private passPhrase
static void main(args) {
def mode = System.console().readLine 'Enter 1 for Encoding, Enter 2 for Decoding'
def wording
switch(mode) {
case "1":
println ("-------\nEncoding Mode\n-------")
wording = "Encoded"
break
case "2":
println ("-------\nDecoding Mode\n-------")
wording = "Decoded"
break
default:
println ("Invalid input, quitting...")
return
}
def plainText = System.console().readLine "Enter Plain Text to be ${wording}: "
def passPhrase = System.console().readLine 'Enter Pass Phrase: '
def hasSpaces = plainText.indexOf(" ")
println ("Plain Text: ${plainText}")
VigenereCipher cipher = new VigenereCipher(passPhrase)
def encodedText
if (mode == "1") {
encodedText = cipher.encrypt(plainText)
} else {
encodedText = cipher.decrypt(plainText)
}
if (hasSpaces) {
char[] encodedChars = encodedText.toCharArray()
encodedChars[hasSpaces] = ' '
encodedText = new String(encodedChars)
}
println ("${wording} Text: ${encodedText}")
}
VigenereCipher(passPhrase) {
this.passPhrase = passPhrase
int keylen = passPhrase.length()
int[] KeyArray = new int[keylen]
keyArray = stringToIntArray(passPhrase)
this.keyArray = keyArray
}
def encrypt(plainText) {
int[] encryptArray = stringToIntArray(plainText)
int[] encryptedLine = new int[plainText.length()]
for (int j = 0; j < plainText.length(); j++) {
encryptedLine[j] = (keyArray[j % passPhrase.length()] + encryptArray[j]) % 26;
}
plainText = intArraytoString(encryptedLine)
return plainText
}
def decrypt(cipherText) {
int[] decryptArray = stringToIntArray(cipherText)
int[] decryptedLine = new int[cipherText.length()]
for (int k = 0; k < cipherText.length(); k++) {
decryptedLine[k] = (decryptArray[k] - keyArray[k % passPhrase.length()] + 26) % 26
}
cipherText = intArraytoString(decryptedLine)
return cipherText
}
static int[] stringToIntArray(text) {
try{
int len = (text.length())
int[] intArray = new int[len]
for (int i = 0; i < len; i++){
intArray[i] = (text.charAt(i) - 97)
}
return intArray
} catch (Exception e) {
println("Error converting string to int: ${e.getMessage()}")
return null
}
}
static String intArraytoString(encodedText) {
int len = (encodedText.length)
char[] charString = new char[len]
for (int i = 0; i < len; i++) {
charString[i] = (char)(encodedText[i] + 97)
}
return new String(charString)
}
}