C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
vigenere.c
Go to the documentation of this file.
1/**
2 * @file vigenere.c
3 */
4
5#include "vigenere.h"
6#include <ctype.h>
7#include <string.h>
8
9static int key_shift(const char *key, size_t i) {
10 size_t klen = strlen(key);
11 if (klen == 0) return 0;
12 char k = key[i % klen];
13 if (!isalpha((unsigned char)k)) return 0;
14 return (int)(tolower((unsigned char)k) - 'a');
15}
16
17static void vigenere_apply(char *text, const char *key, int direction) {
18 if (!text || !key || strlen(key) == 0) return;
19
20 size_t key_index = 0;
21 for (size_t i = 0; text[i] != '\0'; i++) {
22 if (!isalpha((unsigned char)text[i])) continue;
23
24 int shift = key_shift(key, key_index) * direction;
25 char base = isupper((unsigned char)text[i]) ? 'A' : 'a';
26 int c = (text[i] - base + shift) % 26;
27 if (c < 0) c += 26;
28 text[i] = (char)(base + c);
29 key_index++;
30 }
31}
32
33void vigenere_encrypt(char *text, const char *key) { vigenere_apply(text, key, +1); }
34void vigenere_decrypt(char *text, const char *key) { vigenere_apply(text, key, -1); }
void vigenere_decrypt(char *text, const char *key)
Definition vigenere.c:34
void vigenere_encrypt(char *text, const char *key)
Definition vigenere.c:33
static int key_shift(const char *key, size_t i)
Definition vigenere.c:9
static void vigenere_apply(char *text, const char *key, int direction)
Definition vigenere.c:17
Vigenère cipher — polyalphabetic shift keyed by a string.