forked from AllAlgorithms/c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar_cipher.c
68 lines (56 loc) · 1.54 KB
/
caesar_cipher.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* caesarCipher(int, char*, char);
int main () {
char text[] = "Hello World! ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *encryptedText;
char *decryptedText;
encryptedText = caesarCipher(1, text, 'e');
decryptedText = caesarCipher(1, encryptedText, 'd');
printf("Plain text: %s\n", text);
printf("Encrypted text with key 1: %s\n", encryptedText);
printf("Decrypted text: %s\n", decryptedText);
free(encryptedText);
return 0;
}
char* caesarCipher(int key, char *text, char opt) {
char alphabet[26];
int offset = 65;
int textSize = strlen(text);
int i = 0;
char *outputText = malloc(textSize+1);
char oldCharacter;
char newCharacter;
char upperChar;
if (!outputText)
exit(1);
// if decrypting text
if (opt == 'd')
key = -key;
// create alphabet
for (i = 0; i < 26; i++) {
alphabet[i] = offset + i;
}
// caesar cipher
for (i = 0; i < textSize; i++) {
if (isalpha(text[i])) {
// convert text to uppercase
upperChar = toupper(text[i]);
// gets index of the old character in alphabet array
oldCharacter = upperChar - offset;
// finds shifted index
newCharacter = (oldCharacter + key) % 26;
if (newCharacter < 0)
newCharacter += 26;
// add character to output text
outputText[i] = alphabet[newCharacter];
} else {
// if character isn't in the alphabet, add it
outputText[i] = text[i];
}
}
outputText[textSize] = '\0';
return outputText;
}