How encrypt a string with XOR without include strange characters? - c++

The following code works fine, but i want that not include strange characters on encrypted string, like '\x03' for example. How to achieve this?
string XOR_Encryption(string toBeEncrypted, string sKey)
{
string sEncrypted(toBeEncrypted);
unsigned int iKey(sKey.length()), iIn(toBeEncrypted.length()), x(0);
for (unsigned int i = 0; i < iIn; i++)
{
sEncrypted[i] = toBeEncrypted[i] ^ sKey[x];
if (++x == iKey) { x = 0; }
}
return sEncrypted;
}
Usage:
string message = "gbpi";
string Key("Q4s4R4t");
string encrypted_message = XOR_Encryption(message, Key);
cout << "encoded: " << encrypted_message << endl;
string decryptedMessage = XOR_Encryption(encrypted_message, Key);
cout << "decoded: " << decryptedMessage << endl;

With reference to suggestion of #kelalaka, here is a solution using Hex encode:
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
string XOR_Encryption(string toBeEncrypted, string sKey)
{
string sEncrypted(toBeEncrypted);
unsigned int iKey(sKey.length()), iIn(toBeEncrypted.length()), x(0);
for (unsigned int i = 0; i < iIn; i++)
{
sEncrypted[i] = toBeEncrypted[i] ^ sKey[x];
if (++x == iKey) { x = 0; }
}
return sEncrypted;
}
void stream2hex(const string str, string& hexstr, bool capital = false)
{
hexstr.resize(str.size() * 2);
const size_t a = capital ? 'A' - 1 : 'a' - 1;
for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
{
hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
}
}
void hex2stream(const string hexstr, string& str)
{
str.resize((hexstr.size() + 1) / 2);
for (size_t i = 0, j = 0; i < str.size(); i++, j++)
{
str[i] = (hexstr[j] & '#' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
str[i] |= (hexstr[j] & '#' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string text = "text";
string Key("password");
string encrypted_message = XOR_Encryption(text, Key);
stream2hex(encrypted_message, encrypted_message, true);
cout << "encoded: " << encrypted_message << endl;
hex2stream(encrypted_message, encrypted_message);
string decryptedMessage = XOR_Encryption(encrypted_message, Key);
cout << "decoded: " << decryptedMessage << endl;
getch();
return 0;
}

Related

C++ full subtractor using hexadecimals

I have input such as:
10000000000000-1=
and
AAAAABBBBBCCCCCDDDDDEEEEEFFFFF-ABCDEF0123456789ABCDEF=
I need to convert the hexadecimal strings digit by digit into decimal and keep track if I need to borrow. I'm not sure how to adjust the value of operand 1 when a borrow occurs. Such as in the first line when you have to borrow 13 times.
Currently, I have
#include <iostream>
#include <fstream>
using namespace std;
string decimalToHex(int);
void subtraction(string, string)
int hexadecimalToDecimal(char hexVal);
int fullSubtractor(int tempOp1, int tempOp2)
int main()
{
ifstream myFile;
string l1, l2, l3, l4, l5, l6, l7, l8; //lines
string l1op1, l1op2, l2op1, l2op2, l3op1, l3op2, l4op1, l4op2, l5op1, l5op2, l6op1, l6op2, l7op1, l7op2, l8op1, l8op2; //parsed operators
myFile.open("data.txt");
if (myFile.is_open()) //check if file opened
{
cout << "File opened successfully. " << endl;
}
else
{
cerr << "File failed to open." << endl;
return 1;
}
while (!myFile.eof())
{
myFile >> l6 >> l7; //read in line by line
}
l6op1 = l6.substr(0, l6.find("-"));
l6op2 = l6.substr(l6.find("-") + 1);
l6op2 = l6op2.substr(0, l6op2.length() - 1);
std::string l6op2_zeros = std::string((l6op1.length()) - l6op2.length(), '0') + l6op2;
cout << l6; // << subtraction(l6op1, l6op2_zeros) << endl;
subtraction(l6op1, l6op2_zeros);
cout << endl;
l7op1 = l7.substr(0, l7.find("-"));
l7op2 = l7.substr(l7.find("-") + 1);
l7op2 = l7op2.substr(0, l7op2.length() - 1);
std::string l7op2_zeros = std::string((l7op1.length()) - l7op2.length(), '0') + l7op2; //appends zeros to front of second operand to make it same length as operand 1
cout << l7; // << subtraction(l7op1, l7op2) << endl;
subtraction(l7op1, l7op2_zeros);
cout << endl;
myFile.close();
return 0;
}
int fullSubtractor(int tempOp1, int tempOp2)
{
static int borrow;
int result = 0;
if ((tempOp1 < tempOp2) || ((tempOp1 == 0) && (borrow == 1)))
{
tempOp1 += 16;
result = tempOp1 - borrow - tempOp2;
borrow = 1;
}
else
{
result = tempOp1 - tempOp2;
borrow = 0;
}
return result;
}
void subtraction(string op1, string op2)
{
string result;
int tempDifference = 0, tempHex = 0;
int j = op2.length() - 1;
for (int i = op1.length() - 1; i >= 0; i--)
{
int temp1 = hexadecimalToDecimal(op1[i]);
int temp2 = hexadecimalToDecimal(op2[j]);
tempHex = fullSubtractor(temp1, temp2);
result = decimalToHex(tempHex) + result;
cout << result << " ";
j--;
}
cout << result << endl;
//return result;
}
int hexadecimalToDecimal(char hexVal)
{
int base = 1;
int dec_val = 0;
if (hexVal >= '0' && hexVal <= '9')
{
dec_val += (hexVal - 48) * base;
base *= 16;
}
else if (hexVal >= 'A' && hexVal <= 'F')
{
dec_val += (hexVal - 55) * base;
// incrementing base by power
base *= 16;
}
return dec_val;
}
string decimalToHex(int decNum)
{
stringstream ss;
ss << hex << decNum;
string hexNum(ss.str());
//cout << hexNum << endl;
return hexNum;
}

need help on debugging my c++ programming (text ascii manupulation)

I recently made a C++ program which encrypts texts based-on the vigenere cipher technique.
The encryption part works fine I think, but the decryption function doesn't seem to output the correct answer in some cases. I was hoping if anyone could have a look at code and tell me what's wrong with it.
CMD dialog:
Enter the key for encrytion:
magic
Enter message No. 1:
I love C programming
Message encrypted:
u rwxq i rdomzcymovi
Decrypted:
i love c pXogramming
Somehow it outputted "X" instead of "r" in this case.............
Here are the codes:
Secret.h:
#ifndef CPP_TUTORIALS_SECRET_H
#define CPP_TUTORIALS_SECRET_H
#include <iostream>
using namespace std;
class Secret {
private:
string message;
string key;
bool toEncrypt;
bool toDecrypt;
public:
bool isToDecrypt() const {
return toDecrypt;
}
Secret(const string &message = "", const string &key = "", bool toEncrypt = false);
~Secret();
void setToDecrypt(bool toDecrypt);
void encrypt();
void decrypt();
void display();
};
#endif //CPP_TUTORIALS_SECRET_H
Secret.cpp
#include "Secret.h"
Secret::Secret(const string &message, const string &key, bool toEncrypt) {
Secret::message = message;
Secret::key = key;
Secret::toEncrypt = toEncrypt;
}
Secret::~Secret(){
}
void Secret::setToDecrypt(bool toDecrypt) {
Secret::toDecrypt = toDecrypt;
}
void Secret::display() {
cout << message << endl;
}
void Secret::encrypt() {
if(toEncrypt) {
int keyAscii[key.length()];
int count = 0;
for(unsigned int i = 0; i < key.length(); i++) {
keyAscii[i] = key.at(i);
}
for(unsigned int i = 0; i < message.length(); i++) {
if (message.at(i) > 64 && message.at(i) < 91) {
message.at(i) = (char)((message.at(i) - 65 + (keyAscii[count] - 97)) % 26 + 97);
}
else if (message.at(i) > 96 && message.at(i) < 123) {
message.at(i) = (char)((message.at(i) - 97 + (keyAscii[count] - 97)) % 26 + 97);
}
else{
message.at(i) = message.at(i);
}
count++;
if(count == key.length()) {
count = 0;
}
}
}
}
void Secret::decrypt() {
if(toDecrypt) {
int keyAscii[key.length()];
int count = 0;
for(unsigned int i = 0; i < key.length(); i++) {
keyAscii[i] = key.at(i);
}
for(unsigned int i = 0; i < message.length(); i++) {
if (message.at(i) > 96 && message.at(i) < 123) {
message.at(i) = (char)((message.at(i) - 97) % 26 - (keyAscii[count] - 97) + 97);
}
else {
message.at(i) = message.at(i);
}
count++;
if (count == key.length()) {
count = 0;
}
}
}
}
main.cpp
#include <limits>
#include "Secret.h"
void calcMsgAmount(int &pArraySize);
void inputKey(string &key);
void encryptMsg(Secret &secret, string &msg, const string &key, bool toEncrypt, int index);
int main() {
int arraySize;
string key;
string msg;
calcMsgAmount(arraySize);
inputKey(key);
Secret secrets[arraySize];
for(int i = 0; i < arraySize; i++){
encryptMsg(secrets[i], msg, key, true, i);
}
cout << endl << "Message encrypted: " << endl;
for(Secret i: secrets){
i.display();
i.setToDecrypt(true);
if(i.isToDecrypt()){
i.decrypt();
cout << endl << "Decrypted: " << endl;
i.display();
}
cout << endl << endl;
}
return 0;
}
void calcMsgAmount(int &pArraySize) {
cout << "Enter the amount of messages you want to input: " << endl;
while(!(cin >> pArraySize)){
cout << endl << "There's something really wrong with your input, please enter again." << endl;
cout << "Enter the amount of messages you want to input: " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
void inputKey(string &key){
cout << "Enter the key for encrytion: " << endl;
cin.ignore();
getline(cin, key);
}
void encryptMsg(Secret &secret, string &msg, const string &key, bool toEncrypt, int index){
cout << "Enter message No. " << index + 1 << ": " << endl;
getline(cin, msg);
secret = Secret(msg, key, toEncrypt);
secret.encrypt();
}
Many thanks
accroding to wikipedia the decrypt routine of Vigenere Cipher is
(C - K) mod 26
what you wrote in Secret::decrypt() is
message.at(i) = (char)((message.at(i) - 97) % 26 - (keyAscii[count] - 97) + 97);
which is C % 26 - K.
I changed the line to
message.at(i) = (char)((26 + (message.at(i) - 97) - (keyAscii[count] - 97)) % 26 + 97);
it seems to be correct. I haven't really understood why the first 26 is necessary, but without it the code doesn't work (something with % and negative numbers)
P.S. as for debugging part, you might have noticed that whong letters appear as wrong capital letters which have smaller ascii code, so you decrypt routine has negative numbers in it. After which you check your code against Wikipedia :)
The problem comes in the decrypt from two problems:
the first is that the calculation should be symetric from the the encryp, i.e. the modulo 26 for message - key (as already pointed out by effenok)
the second is that in the decrypt you can at char level, message-key can be negative, which might not give you the expected results modulo 26 (for example -2 % 26 is -2 so that you'll be out of the alphabetic range that you expect). The easy trick is to add 26 before doing the modulo, which makes sure it's done on a positive number.
Here slightly more compact functions, making the difference between uppercase and lowercase :
void Secret::encrypt() {
if(toEncrypt) {
for(unsigned int i = 0; i < message.length(); i++) {
if(isalpha(message[i])){
char start = isupper(message[i]) ? 'A' : 'a';
message[i] = (message[i] - start + (tolower(key[i%key.length()]) - 'a') + 26) % 26 + start;
}
}
}
}
void Secret::decrypt() {
if(toDecrypt) {
for(unsigned int i = 0; i < message.length(); i++) {
if (isalpha(message[i]) ){
char start = isupper(message[i]) ? 'A':'a';
message[i] = (message[i] - start - (tolower(key[i%key.length()]) - 'a') + 26) % 26 + start;
}
}
}
}

C++: Change of base function (i.e. hex to octal, decimal, etc.) - Output slightly off for hex values

I need to create a generic function that changes from any starting base, to any final base. I have everything down, except my original function took (and takes) an int value for the number that it converts to another base. I decided to just overload the function. I am Ok with changing between every base, but am slightly off when using my new function to take in a string hex value.
The code below should output 1235 for both functions. It does for the first one, but for the second, I am currently getting 1347. Decimal to Hex works fine - It's just the overloaded function (Hex to anything else) that is slightly off.
Thanks.
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num);
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s);
int main()
{
stack<int> myStack;
string hexNum = "4D3";
switchBasesFunction(myStack, 8, 10, 2323);
cout << endl << endl;
switchBasesFunction(myStack, 16, 10, hexNum);
return 0;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num)
{
int totalVal = 0;
string s = to_string(num);
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s)
{
int totalVal = 0;
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
Sorry, but I'm having issues understanding your code, so I thought I'd simplify it.
Here's the algorithm / code (untested):
void convert_to_base(const std::string& original_value,
unsigned int original_base,
std::string& final_value_str,
unsigned int final_base)
{
static const std::string digit_str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ((original_base > digit_str.length()) || (final_base > digit_str.length())
{
std::cerr << "Base value exceeds limit of " << digit_str.length() << ".\n";
return;
}
// Parse string from right to left, smallest value to largest.
// Convert to decimal.
unsigned int original_number = 0;
unsigned int digit_value = 0;
int index = 0;
for (index = original_value.length(); index > 0; --index)
{
std::string::size_type posn = digit_str.find(original_value[index];
if (posn == std::string::npos)
{
cerr << "unsupported digit encountered: " << original_value[index] << ".\n";
return;
}
digit_value = posn;
original_number = original_number * original_base + digit_value;
}
// Convert to a string of digits in the final base.
while (original_number != 0)
{
digit_value = original_number % final_base;
final_value_str.insert(0, 1, digit_str[digit_value]);
original_number = original_number / final_base;
}
}
*Warning: code not tested via compiler.**

C++ Anagram Maker Error

I have been trying to make an anagram maker, using a textBox (encryption_text) for input, which the text is "Hello World", and the output textBox (encrypted_text) which receives the text:
"ellllloooo
WWWWWWooooooorrrrrrrrllllllllldddddddddd".
I also have a textBox called 'anag_used', which should record the used number/location in the string to encrypt.
Have I over complicated it, or is there an error?
Thanks :)
Here is my code:
void anagram()
{
string toanagram = marshal_as<string>(encryption_text->Text);
string out;
int k;
System::String^ rndstr;
System::String^ ktostr;
ostringstream kstr;
anag_used->Clear();
for (int i = 0; i < toanagram.size(); ++i)
{
anag_used->Text += "\n";
int rnd = 0 + rand() % toanagram.size();
ostringstream rndtostr;
rndtostr << rnd;
rndstr = gcnew System::String(rndtostr.str().c_str());
for (int l = 0; l < i; ++l)
{
if (anag_used->Lines[l] == rndstr)
{
k = rnd;
kstr << k;
ktostr = gcnew System::String(kstr.str().c_str());
for (System::String^ j = anag_used->Lines[l]; j == ktostr; k = 0 + rand() % toanagram.size())
{
kstr << k;
ktostr = gcnew System::String(kstr.str().c_str());
if (anag_used->Lines[l] == ktostr)
{
//Do someting if you want
}
else
{
out += toanagram[k];
anag_used->Lines[l] = ktostr;
}
}
}
else
{
out += toanagram[i];
anag_used->Lines[i] = rndstr;
}
}
}
encrypted_text->Text = marshal_as<System::String^>(out);
}
EDIT: FOUND A MUCH SIMPLER WORKING CODE
#include <algorithm>
.
string toanagram = marshal_as<string>(encryption_text->Text);
sort(toanagram.begin(), toanagram.end());
encrypted_text->Text = marshal_as<System::String^>(toanagram);
This works for console, but you could implement it in C++/CLI quite easily
#include <iostream>
#include <sstream>
#include <vector>
#include <ctime>
void str_vect(std::vector<const char>* v, std::string& s)
{
for (int i = 0; i < s.length(); ++i)
{
v->push_back(s[i]);
}
}
int main()
{
for (;;)
{
std::cout << "Please enter the word / phrase\n";
std::string word;
std::getline(std::cin, word);
std::vector<const char> word_split;
str_vect(&word_split, word);
int sz = word_split.size();
std::string anagram;
for (int i = 0; i < sz; ++i)
{
srand(time(NULL));
int r = (rand() % (word_split.size() - 0)) + 0;
anagram += word_split[r];
word_split.erase((word_split.begin()) + r);
}
system("cls");
std::cout << "Please guess the anagrammed phrase / word - '" << anagram << "'\n";
int max_tries = 3;
int tries = max_tries;
for (int i = 0; i <= max_tries; ++i)
{
std::string guess;
std::getline(std::cin, guess);
if (guess != word)
{
tries--;
if (tries == 0)
{
std::cout << "You have ran out of tries. The answer was: " << word << "\n";
break;
}
std::cout << tries << ((tries == 1) ? " try" : " tries") << " left\n";
}
else
{
std::cout << "Correct!\n";
break;
}
}
}
}
#include <algorithm>
.
string toanagram = marshal_as<string>(encryption_text->Text);
sort(toanagram.begin(), toanagram.end());
encrypted_text->Text = marshal_as<System::String^>(toanagram);

Converting string of 1s and 0s into binary value

I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char * ptr;
long parsed = strtol("11110111", & ptr, 2);
printf("%lX\n", parsed);
return EXIT_SUCCESS;
}
For larger numbers, there as a long long version, strtoll.
You can use std::bitset (if then length of your bits is known at compile time)
Though with some program you could break it up into chunks and combine.
#include <bitset>
#include <iostream>
int main()
{
std::bitset<5> x(std::string("01011"));
std::cout << x << ":" << x.to_ulong() << std::endl;
}
You can use strtol
char string[] = "1101110100110100100000";
char * end;
long int value = strtol (string,&end,2);
You can use Boost Dynamic Bitset:
boost::dynamic_bitset<> x(std::string("01011"));
std::cout << x << ":" << x.to_ulong() << std::endl;
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}