Opinionitis Encryption

I’m going to be posting some entries with the following cipher: only letter characters are going to be encoded. Suppose you’re given a block of text, an array of characters indexed from 0 to N where each value of from 0 to 25 (26 English letters). Then, to encrypt, I’ll take the value of a[0] and add it to a[1]. Now a[0] + a[1] may be greater than 25 so I take modulo 26.

for (int i = 1; i < N; i++) a[i] = (a[i] + a[i-1]) % 26

The decoding is straightforward. So, to make it totally easy, below is the quick C++ source code of this cipher. I will use the text encrypted with it throughout this blog.

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

void decrypt(){
    ifstream inFile(“input.txt”);
    ofstream outFile(“out.txt”);
    int c = 0;
    int offset = 0;
    while (!inFile.eof()){
        string s;
        getline(inFile, s);
        for (int i = 0; i < s.length(); i++){
            if (isalpha(s[i])){
                if (s[i] >= 97 && s[i] <= 122){
                    offset = 97;
                } else {
                    offset = 65;
                }
                
                int si = s[i];
                
                si -= offset;
                int t  = si;
                si = (si + 26 – c) % 26;
                c = t;
                s[i] = (char) ( si + offset );
            }
        }
        outFile << s << endl;
        
    }
    
    inFile.close();
    outFile.close();
}

void encrypt(){
    ifstream inFile(“input.txt”);
    ofstream outFile(“out.txt”);
    int c = 0;
    int offset = 0;
    while (!inFile.eof()){
        string s;
        getline(inFile, s);
        for (int i = 0; i < s.length(); i++){
            if (isalpha(s[i])){
                if (s[i] >= 97 && s[i] <= 122){
                    offset = 97;
                } else {
                    offset = 65;
                }
                int si = (int) s[i];
                si -= offset;
                si = ( si+ c) % 26;
                c = si;
                s[i] = (char) ( si + offset );
            }
        }
        outFile << s << endl;
        
    }    
    inFile.close();
    outFile.close();
}

int main(){
    encrypt();
    decrypt();

    return(0);
}

Advertisements

~ by Monsi.Terdex on December 21, 2012.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Normal Boy

Nothing out of the ordinary

Data Engineering Blog

Compare different philosophies, approaches and tools for Analytics.

%d bloggers like this: