Answers for "monoalphabetic cipher code in c"

C
0

monoalphabetic cipher code in c

//Monoalphabetic cipher
#include <stdio.h>
#include <string.h>
#include <malloc.h>

char *keycipher(char t[], int tl, char k[], int kl, int a)
{
    char *ct = malloc(tl);
    char newaz[26] = {0};
    int orgaz[26] = {0};

    int c = 0;
    for (int i = 0; i < kl; i++)
    {
        int kc = k[i] - 97;
        if (orgaz[kc] == 0)
        {
            orgaz[kc] = c;
            newaz[c++] = kc + 97;
        }
    }
    for (int i = 0; i < 26; i++)
    {
        if (orgaz[i] == 0)
        {
            orgaz[i] = c;
            newaz[c++] = i + 97;
        }
    }

    c = 0;
    for (int i = 0; i < tl; i++)
    {
        if (a == 0)
        {
            ct[c++] = (t[i] == 32) ? 32 : newaz[t[i] - 97];
        }
        else
        {
            ct[c++] = (t[i] == 32) ? 32 : orgaz[t[i] - 97] + 97;
        }
    }
    ct[tl] = '\0';
    return ct;
}

int main()
{
    printf("\nMonoalphabetic Cipher\n");
    int ch = 0;
    while (ch != 3)
    {
        printf("\n\n1.Encrypt\n2.Decrypt\n3.Exit");
        printf("\nSelect Option: ");
        scanf("%d", &ch);
        switch (ch)
        {
        case 1:
        {
            char pt[50], key[50];
            printf("\nEnter plain text: ");
            scanf(" %[^\n]%*c", pt);
            printf("\nEnter the keyword: ");
            scanf(" %[^\n]%*c", key);
            printf("\nCipher Text: %s", keycipher(pt, strlen(pt), key, strlen(key), 0));
            break;
        }
        case 2:
        {
            char ct[50], key[50];
            printf("\nEnter cipher text: ");
            scanf(" %[^\n]%*c", ct);
            printf("\nEnter the keyword: ");
            scanf(" %[^\n]%*c", key);
            printf("\nOriginal Text: %s", keycipher(ct, strlen(ct), key, strlen(key), 1));
            break;
        }
        case 3:
            return 0;
        default:
            printf("\nInvalid Choice!");
        }
    }
    return 0;
}
Posted by: Guest on July-25-2021

Code answers related to "monoalphabetic cipher code in c"

Code answers related to "C"

Browse Popular Code Answers by Language