Our Single Key Encryption code in C++.
Single Key Encryption Class Header File:
#pragma once
#include "BigInteger.h"
#include <string>
#include <vector>
using namespace std;
class SoleKeyEncryption
{
public:
SoleKeyEncryption();
virtual ~SoleKeyEncryption();
vector<string> encodeWord(vector<char>, vector<char>);
string decodeWord(vector<string>, vector<char>);
};
Single Key Encryption Class File:
#include "stdafx.h"
#include "SoleKeyEncryption.h"
SoleKeyEncryption::SoleKeyEncryption()
{
}
vector<string> SoleKeyEncryption::encodeWord(vector<char> msg, vector<char> key) {
// encoding eqn { Tn = 3^n-1(2t1 + 1) - 1 } - please use your own eqn
// 2
vector<string> encryption = {};
int n, t1;
string h, Tn;
stringstream x;
for (size_t i = 0; i < msg.size(); i++) {
// get unicode of this character as t1
t1 = (int) msg[i];
// get next key digit as n
h = "";
h += key[i % (key.size() - 1)];
x << hex << h;
x >> n;
x.clear();
// use recurrence series equation to encrypt & save in base 16
Tn = BigInteger::division(BigInteger::subtraction(BigInteger::multiplication(
BigInteger::exponentialPower("3", n - 1), to_string(2 * t1 + 1)), "1"), "2");
encryption.push_back(BigInteger::decToHex(Tn));
}
return encryption;
}
string SoleKeyEncryption::decodeWord(vector<string> code, vector<char> key) {
// decoding eqn { t1 = 3^1-n(2Tn + 1) - 1 }
// 2
string decryption = "", h, t1, Tn;
int n;
stringstream x;
for (size_t i = 0; i < code.size(); i++) {
Tn = BigInteger::hexToDec(code[i]);
// get next key digit as n
h = "";
h += key[i % (key.size() - 1)];
x << hex << h;
x >> n;
x.clear();
// use recurrence series equation to decrypt
t1 = BigInteger::division(BigInteger::subtraction(BigInteger::division(
to_string(2 * stoi(Tn) + 1), BigInteger::exponentialPower("3", n - 1)), "1"), "2");
decryption += (char)stoi(t1);
}
return decryption;
}
SoleKeyEncryption::~SoleKeyEncryption()
{
}
Main Class:
#include "stdafx.h"
#include "SoleKeyEncryption.h"
#include <iostream>
using namespace std;
int main()
{
vector<char> message = { 'm', 'e', 'r', 'r', 'y', ' ', 'x', 'm', 'a', 's' };
vector<char> key = { 'A', '5', 'F', 'B', '1', '7', 'C', '4', 'D', '8' }; // you might want to avoid zeroes
SoleKeyEncryption go_secure;
vector<string> encrypted = go_secure.encodeWord(message, key);
string disp = "";
for (string s : encrypted) {
disp += s + "; ";
}
string msg = "";
for (char c : message) {
msg += c;
}
cout << "Message is '" << msg << "';\nEncrypted version is " << disp << endl;
string decrypted = go_secure.decodeWord(encrypted, key);
cout << "\n\nDecrypted version is '" << decrypted << "'.";
return 0;
}
Try it out!
Elegance (0.0)