Simple Encryption Algorithms

Here are a couple simple encryption programming examples.  Obviously these are full of exploits so you wouldn't want to use them seriously, but they are great for teaching students about the basic idea of encryption.

Here's a simple implementation of ROT13 in c++:


#include 

using namespace std;

int main(){
    int data;
    cout << "Enter Message to ROT13: " << endl;
    while(cin && cin.peek() != EOF){
	data = cin.get();
	if(data >= 'A' && data <= 'Z'){
	    data = ((data - 'A') + 13) % 26 + 'A';
	}else if(data >= 'a' && data <= 'z'){
	    data = ((data - 'a') + 13) % 26 + 'a';
	}
	cout << char(data);
    }
}

Download: rot13.cxx

Here's a simple encryption algorithm which uses C++'s basic rand() function to XOR data:


#include 
#include 

using namespace std;

void set_passwd();
void encrypt_decrypt(ifstream&, ofstream&);

int main(){
    char ifile[100];
    char ofile[100];
    cout << "Input file to encrypt/decrypt: ";
    cin >> ifile;
    cout << "Input output file name: ";
    cin >> ofile;
    ifstream in(ifile);
    ofstream out(ofile);
    set_passwd();
    encrypt_decrypt(in, out);
}

void set_passwd(){
    char passwd[100];
    long seed = 0;
    int shift = 0;
    cout << "Enter Password (100 chars max): ";
    cin >> passwd;
    for(int i = 0; i < 100 && passwd[i] != 0; i++){
        seed ^= passwd[i] << shift;
	shift = (shift + 8)%32;
    }
    srand(seed);
}

void encrypt_decrypt(ifstream& in, ofstream &out){
    int data;
    while(in.peek() != EOF){
	data = in.get();
	out << char(data^int(rand()));
    }
}

Download: simpleencrypt.cxx