monoalphabetic cipher code in c

Solutions on MaxInterview for monoalphabetic cipher code in c by the best coders in the world

showing results for - "monoalphabetic cipher code in c"
Clea
25 Nov 2020
1//Monoalphabetic cipher
2#include <stdio.h>
3#include <string.h>
4#include <malloc.h>
5
6char *keycipher(char t[], int tl, char k[], int kl, int a)
7{
8    char *ct = malloc(tl);
9    char newaz[26] = {0};
10    int orgaz[26] = {0};
11
12    int c = 0;
13    for (int i = 0; i < kl; i++)
14    {
15        int kc = k[i] - 97;
16        if (orgaz[kc] == 0)
17        {
18            orgaz[kc] = c;
19            newaz[c++] = kc + 97;
20        }
21    }
22    for (int i = 0; i < 26; i++)
23    {
24        if (orgaz[i] == 0)
25        {
26            orgaz[i] = c;
27            newaz[c++] = i + 97;
28        }
29    }
30
31    c = 0;
32    for (int i = 0; i < tl; i++)
33    {
34        if (a == 0)
35        {
36            ct[c++] = (t[i] == 32) ? 32 : newaz[t[i] - 97];
37        }
38        else
39        {
40            ct[c++] = (t[i] == 32) ? 32 : orgaz[t[i] - 97] + 97;
41        }
42    }
43    ct[tl] = '\0';
44    return ct;
45}
46
47int main()
48{
49    printf("\nMonoalphabetic Cipher\n");
50    int ch = 0;
51    while (ch != 3)
52    {
53        printf("\n\n1.Encrypt\n2.Decrypt\n3.Exit");
54        printf("\nSelect Option: ");
55        scanf("%d", &ch);
56        switch (ch)
57        {
58        case 1:
59        {
60            char pt[50], key[50];
61            printf("\nEnter plain text: ");
62            scanf(" %[^\n]%*c", pt);
63            printf("\nEnter the keyword: ");
64            scanf(" %[^\n]%*c", key);
65            printf("\nCipher Text: %s", keycipher(pt, strlen(pt), key, strlen(key), 0));
66            break;
67        }
68        case 2:
69        {
70            char ct[50], key[50];
71            printf("\nEnter cipher text: ");
72            scanf(" %[^\n]%*c", ct);
73            printf("\nEnter the keyword: ");
74            scanf(" %[^\n]%*c", key);
75            printf("\nOriginal Text: %s", keycipher(ct, strlen(ct), key, strlen(key), 1));
76            break;
77        }
78        case 3:
79            return 0;
80        default:
81            printf("\nInvalid Choice!");
82        }
83    }
84    return 0;
85}