22858 total geeks with 3297 solutions
Recent challengers:
best bread maker
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
sefo
anilg, new comments are deleted automaticall y because of some abuse recently
anilg
this is plain wierd. I submitted comments twice to article 950, and they dont seem to be there. Something wrong with the comment code?
CodeX
shout-boxes in general are old + the staff thing happened to everyone after an issue 2 months ago
anilg
/me is no longer staff :(
anilg
Also, osix's shoutbox predated twitter. Heh.

Donate
Donate and help us fund new challenges
Donate!
Due Date: Sep 30
September Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Washington Supremes
deliver death
sentence to betting
site
Google faces
antitrust
investigation in
Texas
It"s alive! Duke
Nukem Forever
breaks out of
vapour trail
Ubuntu "Maverick
Meerkat" erects own
App Store
Doctor Who goes to
the Proms
Unity ? iPhone code
swap approved by
Jobs (for now)
Nigerian man gets
12 years for $1.3m
419 scam
Oz school in
homosexual
kookaburra rumpus
All the week"s
Reg Hardware
reviews
Gordon Brown joins
World Wide Web
Foundation
Slashdot
NASA Preps
Closest-Ever Sun
Mission
Software (and
Appropriate Input
Device) For a
Toddler?
Brazil Considering
Legalizing File
Sharing
Game Publishers
Using Stealth P2P
Clients
Winnie-the-Pooh
Parodied In
Wookie-the-Chew
2010 May Be the
First Year YouTube
Turns a Profit
VISA Pulls Plug On
ePassporte, Porn
Webmasters
New and Old
Experiments Combine
To Help the Search
For Life On Mars
NVIDIA Announces
New Line of
Fermi-Based Mobile
Chips
Where Does Dell Go
After Losing 3Par?
Article viewer

MonoAlphabetic Substitution Cipher : Part 5 of a Series



Written by:typedeaF
Published by:Nightscript
Published on:2004-07-16 15:41:40
Topic:C
Search OSI about C.More articles by typedeaF.
 viewed 18278 times send this article printer friendly

Digg this!
    Rate this article :
MonoAlphabetic Substitution Cipher written in C.
Ok, I almost made the mistake of bypassing this cipher. By simply remapping the letters of the alphabet you can create a cipher text with 26! possible keys. Nice.

#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <stdlib.h>
#include <ctype.h>
 
int CheckArgs(int argc, char *argv[])
{
      unsigned char *prog = argv[0];
 
      if(argc != 3)
      {
            fprintf(stdout, "ERROR: %s requires plain and cipher file arguements.n", prog);
            return 0;
      }
      else
            return 1;
}
 
unsigned int GetFileLen(FILE *fp)
{
      unsigned int len = 0;
 
      fseek(fp, 0L, SEEK_END);
      len = ftell(fp);
      fseek(fp, 0L, SEEK_SET);
 
      return len;
}
 
int main(int argc, char *argv[])
{
      FILE *infile;
      FILE *outfile;
      unsigned char key[26];
      unsigned char *data;
      unsigned int datalen;
      unsigned int i = 0;
      unsigned int j = 0;
      unsigned int temp = 0;
 
      printf("nMonoAplhabetic Substitution Cipher by typedeaF @ www.osix.netn");
      if(!CheckArgs(argc, argv))
      {
            return EXIT_FAILURE;
      }
 
      if((infile = fopen(argv[1], "rb")) == NULL)
      {
            fclose(infile);
            printf("ERROR: %s could not open %s for reading.n", argv[0], argv[1]);
            return EXIT_FAILURE;
      }
 
      if((outfile = fopen(argv[2], "wb")) == NULL)
      {
            fclose(infile), fclose(outfile);
            printf("ERROR: %s could not open %s for writing.n", argv[0], argv[2]);
            return EXIT_FAILURE;
      }
 
      if((keyfile = fopen("key.txt", "wb")) == NULL)
      {
            fclose(infile), fclose(outfile);
            printf("ERROR: %s could not open keyfile for writing.n", argv[0], argv[2]);
            return EXIT_FAILURE;
      }
            
 
      datalen = GetFileLen(infile);
      if((data = malloc(datalen)) == NULL)
      {
            fclose(infile), fclose(outfile), free(data);
            printf("ERROR: Insuffecient Memoryn");
            return EXIT_FAILURE;
      }
      
      if(!fread(data, datalen, 1, infile))
      {
            fclose(infile), fclose(outfile), free(data);
            printf("ERROR: read error.n");
            return EXIT_FAILURE;
      }
 
      /* initilize key */
      for(i = 0; i < 26; i++)
      {
            key[i] = i + 'a';
      }
 
      srand((unsigned)time(NULL));
      
      /* shuffle the key */
      for(i = 0; i < 26; i++)
      {
            j = (unsigned int)((26) * (rand() / ((double)RAND_MAX + 1.0)));
            temp = key[i];
            key[i] = key[j];
            key[j] = temp;
      }
      
      /* save the key */
      for(i = 0; i < 26; i++)
            putc(key[i], keyfile);
 
      printf("nProcessing");
 
      for(i = 0;(unsigned int)i < datalen; i++)
      {
            printf(".");
            fflush(stdout);
            if(isalpha(data[i]))
                  fputc(key[tolower(data[i])-'a'], outfile);
            else
                  fputc(data[i], outfile);
      }
      printf("nDONE");
      fclose(infile), fclose(outfile), free(data);
 
      return EXIT_SUCCESS;
}


Alright this is a Monoalphabetic Substitution Cipher program. I ALMOST skipped doing this one because it appeared to be very weak. Open closer observation I realized that in fact it is stronger than a Shift Cipher (like my rot13 example) and an 8-bit XOR Cipher. Both of those Ciphers could be brute forced using less than 256 possibilities. MASC works by remapping the alphabet to a different char. Example being, you map 'a' to 'e' and 'b' to 'y' etc. This appeared to be simple to decrypt to me until I realized that there were at LEAST 26! possibilities and at most 256!.

The later two ciphers can be done in minutes. Starting from the top I am trying to slowly get the programs more complex and more functional. The first almost 20 lines of main once again handle file opening. This time we broke one part of this procedure out to a function that simply checks the command line arguments and reports to main the validity of them. The next function we encounter is once also common to all previous examples, it is the routine used to find the length of a file using fseek() and ftell().

Normally I don’t make something a function unless I used it twice, however the next cipher we build will use it more than once. The length of the file is returned to filelen. The filelen is used to determine the size of the buffer we will hold the data in. I have made extra effort to include error checking in all applicable routines, making the program much larger. After the buffer is created we read the plain text into the buffer using fread(). Now we start the cryptology routines. An array large enough to hold 'a' = 'z' is created and initialized linearly. Next the array is shuffled fairly randomly using srand() and rand(). Notice how the shuffle/swap function keeps within the range of 26. There was no good reason I made the swap like this other than it was the first idea that came to mind and worked :) Ok now we have a pretty mixed up alphabet to use as out key.

Whatever is now in index 0, is what 'a' is mapped to. As you can see in a real program you might want save this key...cause if you want to decrypt it...you’ll sort of need it. Anyway, all we have left to so is to run thru the buffer and every time we encounter an alphabetic character, convert it to lower case and replace it with its key char. One could easily make this work for all 256 ASCII values, but here simplicity is more important so that you grasp the technique. Data is now encoded and written to a new file. The Key is also printed to a file called key.txt. This program was really fun to make because it is very similar to how more complex ciphers using s-boxes and such work. We will get to those soon enough.

Did you like this article? There are hundreds more.

Comments:
bb
2004-07-23 08:22:23
nice series typedeaf, ive enjoyed reading them, i did a few articles myself on data encryption using the .NET Framework

i've listed the urls here in case anyone is interested in the topic

http://www.osix.net/modules/article/?id=411
Rijndael Managed Encryption made easy in C#

http://www.osix.net/modules/article/?id=100
File Encryption in C#

http://www.osix.net/modules/article/?id=37
Source Code for .NET Encryption Algorithims

http://www.osix.net/modules/article/?id=36
.NET Framework Cryptography
massivefoot
2005-02-01 23:29:39
Hi, nice article, a good into to cryptography.

However, Alask is correct, monoalphabetics are extremely weak. Even transposition won't really increase the strength of the monoalphabetic substitution part of the cipher if the attack is based upon simple frequency analysis.

Has anyone published any articles on the site about code to break ciphers, rather than just decrypt them?
janus
2005-02-02 13:46:47
it's a good start, allthough security of this cipher is low:
-count frequenties
-order the letters from high to low
-compare with possible languages by performing a chi square test to determine the language.
-this gives a rough mapping to the key that gets better with increasing length. decripting the ciphertext with this key gives you a ciphertext with a "key that is close to the normal alphabet".
-Now attack this new ciphertext with doubles, triples ...
-
typedeaF
2005-04-07 19:39:08
Thanks for the positive critique and comments. It is appreciated and ofcourse correct.
I did this series many years ago and stopped at #5 when I realized that at some point, I was just regurgitating every other tutorial or book thats already out there.
I re-posted recently when I realized that the content was missing. If anyone really would be interesting in more lessons like this, let me know.
Im not even sure where to go from here anymore.

tF
Anonymous
2008-10-10 09:31:36
hi dose it really decryption cipher to plain
I'll try it
Anonymous
2009-07-14 13:42:58
Your work is great you should carry on your work with out stopping it, lots of people are waiting for this kind of stuff and as you explain in details is good to understand things, i was busy in establishing business for that i need unlimited domain hosting service package and along with this i need to post several emails so i need email domain hosting to keep running my business online because lots of my clients are online and want images of my work so i also going to get image hosting for this. but one thing i must say that lots of people need your service so you should carry on your work.
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
amisauv
Creating a Lexical Analyzer in C on Tue 9th Dec 11am
#include<stdio.h> #include<string.h> #include<conio.h> #include<ctype.h> /*************************************** ************************* Functions prototype. **************************************** *************************/ void Open_File(
amisauv
Controling digital circuit through computer on Tue 9th Dec 10am
this code access the lpt port.here only 4 of the total 8 pins are used but can be modified for full 8 pins.it has a complete GUI with mouse & keyboard interactive control panel.works well in win98, but not in winxp. #include<stdio.h> #include<conio.
amisauv
/* Computerised Electrical Equipment Control */ /* PC BASED DEVICE CONTROLLER * on Tue 9th Dec 10am
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { void tone(void); int p=0x0378; char ex={"Created By Mrc"}; int j; char ex1={"For Further Details & Improvements"}; int k; char ex2={"Contact : E-mail : anbudan
amisauv
Calendar Program on Tue 9th Dec 10am
This program prints Weekdays of specified date. It even prints calendar of a given year too. /*Ccalendar library*/ #include<stdio.h> #include<string.h> #include<conio.h> int getNumberOfDays(int month,int year) { switch(month) { case
amisauv
Calculator: on Tue 9th Dec 10am
#include"graphics.h" #include"dos.h" #include"stdio.h" #include"math.h" union REGS i,o; char text={ "7","8","9","*","4","5","6","/","1","2", "3","+","0","00",".","-","M","M+", "M-","+/-","MR","MC","x^2","sr","OFF","A C","CE","="}; int s=0,k=0,pass
amisauv
INFECTED CODES WRITTEN IN C\C++ on Tue 9th Dec 10am
This is a simple code that changes system time and date. It is written using c/c++ but can be easily converted to java. #include "stdio.h" #include "process.h" #include "dos.h" int main(void) { struct date new_date; struct date old_date; s
amisauv
A C programme which can print the file name it is kept in on Tue 9th Dec 9am
#include<stdio.h> main(){ printf(”the source file name is %s\n”,__FILE__); } actually __FILE__ is a macro which stands for the file name the programme is kept in and the compiler does the rest .. for you ..
amisauv
BOOTSECTOR EDITOR: on Tue 9th Dec 9am
Code : /*program to save the partion table of your hard disk for future use. it will save your partition table in a file partition.dat */ #include<stdio.h> #include<bios.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void main () {
amisauv
BLINKING STAR : on Tue 9th Dec 9am
#include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> void main() { int gdriver=DETECT,gmode; int i,x,y; initgraph(&gdriver,&gmode,"e: cgi"); while(!kbhit()) { x=random(640); y=random(480); setcolor
amisauv
// To print semicolons using C programming without using semicolons any where i on Tue 9th Dec 9am
// To print semicolons using C programming without using semicolons any where in the C code in program. // #include<stdio.h> #include<conio.h> void main() { char a; a=59; if(printf("%c",a)){} getch();

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
BSD sockets API by skrye

This is a test of your knowledge of the BSD socket interface
C Programming by keoki

This test is aimed at a C programmer that is at an intermediate level.


     
Your Ad Here
 
Copyright Open Source Institute, 2006