-
Notifications
You must be signed in to change notification settings - Fork 5
/
vigenere.c
69 lines (61 loc) · 1.64 KB
/
vigenere.c
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
// CrypTools - GitHub
// Tuesday, 14 August 2018
// Vignerere Cipher to encrypt text
/*****
Compile:
$ make
Use:
$ ./vigenere KEYARRAY < file.txt
Note that the KEYARRAY should only be composed of alphabetical lowercase and uppercase letters.
*****/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MINCAP 65
#define MAXCAP 90
#define MINLOW 97
#define MAXLOW 122
void encode (int shiftNumber, char letter);
int getFirstLetter (char letter);
// Takes an int and a file containing text to encrypt
int main (int argc, char *argv[]) {
int shift = 0;
int c = 0;
// set key
char *key = argv[1];
int keyLength = strlen(key);
int keyIndex = 0;
int currentLetter = 0;
while ((c = getchar()) != EOF) {
currentLetter = key[keyIndex % keyLength];
shift = (currentLetter - getFirstLetter(currentLetter));
keyIndex++;
encode(shift, c);
}
printf("\n");
return EXIT_SUCCESS;
}
/* takes a character and increments it by shift */
void encode (int shift, char letter) {
int numAscii = letter;
int firstLetter = getFirstLetter(letter);
if ((firstLetter == 65) || (firstLetter == 97)) {
numAscii -= (firstLetter - shift);
numAscii = (numAscii % 26);
numAscii += firstLetter;
putchar(numAscii);
}
}
int getFirstLetter (char letter) {
int numAscii = letter;
int firstLetter;
if (numAscii >= MINCAP && numAscii <= MAXCAP) {
firstLetter = MINCAP;
} else if (numAscii >= MINLOW && numAscii <= MAXLOW) {
firstLetter = MINLOW;
} else {
putchar(letter);
firstLetter = 1;
}
return firstLetter;
}