Skip to content

Instantly share code, notes, and snippets.

@navin-mohan
Last active March 9, 2018 19:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navin-mohan/c2dd539bd265921bc68f76b1f371b4f3 to your computer and use it in GitHub Desktop.
Save navin-mohan/c2dd539bd265921bc68f76b1f371b4f3 to your computer and use it in GitHub Desktop.
Running key cipher implementation in C++
/*
The Running Key
----------------
The running key cryptographic algorithm is a classical cipher that uses a long key
such as random sentences from books to encrypt another message. It uses a table for
mapping the cipher text using the key and the plain-text.
get more info here
This is a simple implementation of the running key algorithm.
Author : Navin Mohan
e-mail: navinmohan81@gmail.com
Visit: http://www.coderew.com/c_implementation_of_runnig_key_cipher/
*/
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
using namespace std;
void encrypt(string&,string&,string&); // encryption function accepting plaintext key and ciphertext references
char getCipher(char p,char k); //the table mapping
void getKeyIndex(int &i,string &key); //to repeat the key sequentially
int main()
{
string plaintext,key,ciphertext;
cout << "Enter the text:";
getline(cin,plaintext);
cout << "Enter the key(should be longer than text):";
getline(cin,key);
key.erase(remove(key.begin(), key.end(), ' '), key.end()); // remove spaces from the key text
if (key.length() < plaintext.length()) return 1; // exit with status 1 if the key is shorter than plaintext
encrypt(plaintext,key,ciphertext);
cout << "\nEncrypted Text is:" <<endl;
cout << ciphertext << endl;
return 0;
}
void encrypt(string &plaintext,string &key,string &cipher)
{
string::iterator it1,it2; // string iterators
cipher = ""; // intitialize the ciphertext variable to NULL
for(it1 = key.begin(),it2 = plaintext.begin();it2 < plaintext.end();){
if (!isalpha(*it2)) { // omit the non alphabetic chars in plain text
it2++;
continue;
}
cipher += getCipher(tolower(*it2),tolower(*it1)); // get encrypted char
it1++;
it2++;
}
}
char getCipher(char p,char k)
{
int cipher;
cipher = p + k;
if (cipher >= 219) return (char) (cipher - 123);
return (char)(cipher-97);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment