This is a C Program to implement Vigenere Cipher. Implement a Vigenère cypher, both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. If your program handles non-alphabetic characters in another way, make a note of it.
Here is source code of the C Program to Implement the Vigenere Cypher. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void upper_case(char *src) {
while (*src != '\0') {
if (islower(*src))
*src &= ~0x20;
src++;
}
}
char* encipher(const char *src, char *key, int is_encode) {
int i, klen, slen;
char *dest;
dest = strdup(src);
upper_case(dest);
upper_case(key);
/* strip out non-letters */
for (i = 0, slen = 0; dest[slen] != '\0'; slen++)
if (isupper(dest[slen]))
dest[i++] = dest[slen];
dest[slen = i] = '\0'; /* null pad it, make it safe to use */
klen = strlen(key);
for (i = 0; i < slen; i++) {
if (!isupper(dest[i]))
continue;
dest[i] = 'A' + (is_encode ? dest[i] - 'A' + key[i % klen] - 'A'
: dest[i] - key[i % klen] + 26) % 26;
}
return dest;
}
int main() {
const char *str = "Beware the Jabberwock, my son! The jaws that bite, "
"the claws that catch!";
const char *cod, *dec;
char key[] = "VIGENERECIPHER";
printf("Text: %s\n", str);
printf("key: %s\n", key);
cod = encipher(str, key, 1);
printf("Code: %s\n", cod);
dec = encipher(cod, key, 0);
printf("Back: %s\n", dec);
/* free(dec); free(cod); *//* nah */
return 0;
}
Output:
$ gcc VigenereCipher.c $ ./a.out Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch! key: VIGENERECIPHER Code: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY Back: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy C Books
- Apply for Computer Science Internship
- Practice BCA MCQs
- Buy Computer Science Books
- Watch Advanced C Programming Videos