Header Ads Widget

Ticker

6/recent/ticker-posts

To Implement Polyalphabetic cipher encryption-decryption

 Program: 

Vigenere Cipher Code:- 

#include <stdio.h>

#include <string.h>

int main()
{

    char msg[] = "IAMLAMBORGHINILOVER";

    char key[] = "MONEY";

    int msgLen = strlen(msg), keyLen = strlen(key), i, j;

    char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
    for (i = 0, j = 0; i < msgLen; ++i, ++j)
    {

        if (j == keyLen)

            j = 0;

        newKey[i] = key[j];
    }

    newKey[i] = '\0';

    for (i = 0; i < msgLen; ++i)

        encryptedMsg[i] = ((msg[i] + newKey[i]) % 26) + 'A';

    encryptedMsg[i] = '\0';

    for (i = 0; i < msgLen; ++i)

        decryptedMsg[i] = (((encryptedMsg[i] - newKey[i]) + 26) % 26) + 'A';
    decryptedMsg[i] = '\0';

    printf("Original Message: %s", msg);

    printf("\nKey: %s", key);

    printf("\nNew Generated Key: %s", newKey);

    printf("\nEncrypted Message: %s", encryptedMsg);

    printf("\nDecrypted Message: %s", decryptedMsg);

    return 0;
}

Output:


Autokey Cipher:- 


#include <stdio.h>

#include <string.h>

void encrypt(char *plaintext, char *key)
{

    int i, j;

    int key_length = strlen(key);

    int plaintext_length = strlen(plaintext);

    char new_key[plaintext_length];

    for (i = 0; i < plaintext_length; i++)
    {

        if (i < key_length)
        {

            new_key[i] = key[i];
        }
        else
        {

            new_key[i] = plaintext[i - key_length];
        }
    }

    for (i = 0; i < plaintext_length; i++)
    {

        plaintext[i] = (plaintext[i] + new_key[i]) % 26 + 'A';
    }
}

void decrypt(char *ciphertext, char *key)
{

    int i, j;

    int key_length = strlen(key);

    int ciphertext_length = strlen(ciphertext);

    char new_key[ciphertext_length];

    for (i = 0; i < ciphertext_length; i++)
    {

        if (i < key_length)
        {

            new_key[i] = key[i];
        }
        else
        {

            new_key[i] = ciphertext[i - key_length];
        }
    }

    for (i = 0; i < ciphertext_length; i++)
    {

        ciphertext[i] = (ciphertext[i] - new_key[i] + 26) % 26 + 'A';
    }
}

int main()
{

    char plaintext[] = "HELLOWORLD";

    char key[] = "HELLO";

    encrypt(plaintext, key);

    printf("Encrypted text: %s\n", plaintext);

    decrypt(plaintext, key);

    printf("Decrypted text: %s\n", plaintext);

    return 0;
}


Post a Comment

0 Comments