Simple ASCII Encryption and Decryption Tool

This is a simple tool play with ASCII to encrypt or decrypt input text.
Wrote this for a demo purpose and fun.

playascii

How to “Encryption”? -> Start with a plaintext character, followed by the ascii value in hex of the next character.

The code is kind of self-explain and there is no tricky part actually.
Tested compile with:

g++ -o playascii playascii.cpp -std=c++11
/*
 * playascii.cpp
 * Simple demo program play with ASCII
 * Copyleft 2015 Linus.
 * 08/25/2015
 */

#include 
#include 
#include  

using std::cin;
using std::cout;
using std::endl;
using std::string;

void printUsage() {
	cout << "Usage:\n"
		 << "To decrypt: playascii -d \"ciphertext_here\"\n"
		 << "To encrypt: playascii -e \"plaintext_here\"\n";
}

/* function to convert single char to char array in hex */
char* chartohex(char c, char* buf) {
	int i = 1;
	while (c > 0 && i >= 0) {
		buf[i] = c % 16;
		c /= 16;
		i--;
	}
	for (i=0; i<2; i++) {
		if (buf[i] <= 9) {
			buf[i] += 48; //'0'
		} else {
			buf[i] += 87; //'A' - 10
		}
	}
	return buf;
}

/* decode function */
bool decode(const string& in, string& out) {
	int len = in.length();
	int i = 0;
	while (i < len) {
		while (in[i] == 20) { //skip space
			i++;
		}
		out += in[i]; //plain text
		i++;
		while (in[i] == 20) { //skip space
			i++;
		}
		if (i == len-1) {
			return false;
		}
		if (i+1 < len) {
			char c;
			try {
				c = std::stoi(in.substr(i,2),nullptr,16);
			} catch (const std::invalid_argument& ia) {
				return false;
			}
			out += c;
			i += 2;
		}
	}
	return true;
}

/* encode function */
bool encode(const string& in, string& out) {
	int len = in.length();
	for (int i=0; i
			

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.