Friday 24 November 2017

C++ Program to Implement the One Time Pad Algorithm


Code:

#include    iostream
#include    vector
#include    stdlib.h
using namespace std;
void to_upper_case(vector& text, int len)
{
    for (int i = 0; i < len; i++)
    {
        if (text[i] >= 97 && text[i] <= 122)
            text[i] -= 32;
    }
}
void print_string(vector text, int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << (char) (text[i] + 65);
    }
    cout << endl;
    return;
}
size_t get_input(vector& msg)
{
    char a;
    while (1)
    {
        a = getchar();
        if (a == '\n')
            break;
        msg.push_back(a);
    }
    return msg.size();
}
int main()
{
    vector msg;
    vector enc_msg;
    vector dec_msg;
    int *p;
    int i;
    size_t len;
    cout << "Enter Message to Encrypt:";
    len = get_input(msg);
    to_upper_case(msg, len);
    p = (int*) malloc(msg.size() * sizeof(int));
    for (i = 0; i < len; i++)
    {
        p[i] = rand() % 26;
        if (msg[i] >= 65 && msg[i] <= 90)
            enc_msg.push_back((char) ((msg[i] - 65 + p[i]) % 26));
        else if (msg[i] >= 97 && msg[i] <= 122)
            enc_msg.push_back((char) ((msg[i] - 97 + p[i]) % 26));
        else
            enc_msg.push_back((char) msg[i]);
    }
    cout << "\nEncoded Message:";
    print_string(enc_msg, len);
    cout << "\nKey for decryption:\n";
    for (i = 0; i < len; i++)
    {
        cout << (char) (p[i] + 65);
    }
    cout << endl;
    cout << "\nDecrypted Message:";
    for (i = 0; i < len; i++)
    {
        if ((enc_msg[i] - p[i]) < 0)
            dec_msg.push_back((char) (enc_msg[i] - p[i] + 26));
        else if ((enc_msg[i] - p[i]) >= 0)
            dec_msg.push_back((char) (enc_msg[i] - p[i]));
        else
            dec_msg.push_back((char) enc_msg[i]);
    }
    print_string(dec_msg, len);
    return 0;
}


Output:

Enter Message to Encrypt: This is the demonstration of OTP algorithm
Encoded Message:IOYYaCEaTFPaOJPLSAKTVLKLTaPBaTGFaUICTENHGH

Key for decryption:
PHQGHUMEAYLNLFDXFIRCVSCXGGBWKFNQDUXWFNFOZV

Decrypted Message:THISZIS]THETDEMONSTRATION[OFWOTP^ALGORITHM

------------------
(program exited with code: 0)
Press return to continue


More C++ Programs:
















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...