You are on page 1of 22

Program 1

Aim: To design encipher and decipher blocks of data consisting of 64 bits under control of a 64 bit key by using the data encryption algorithm in C++ // Kraken Decryptor Source Code // By MHL and Greg, 2008 #include<windows.h> #include<stdio.h> #define ROR64(v, b) (((v) >> ((b))) | ((v) << (64 - (b)))) typedef struct MSG_HDR { unsigned char type[2]; unsigned short ver; int length; } MSG_HDR; typedef struct PACKET { unsigned int key0; unsigned int key4; int key8; MSG_HDR msg; int chksum; unsigned char data[1]; } PACKET; void decrypt_math(unsigned char * data, int key8, int ** keys) { int a = key8 * 2; int b, c, e; unsigned int d; int count = 2; PACKET * pckt = (PACKET *) data; do { b = (pckt->key0 << 4) + *(int *)&keys[2]; d = pckt->key0; c = (d >> 5) + *(int *)&keys[3]; pckt->key4 -= (b ^ (a + pckt->key0) ^ c); e = ((pckt->key4 >> 5) + *(int *)&keys[1]); b = ((pckt->key4 << 4) + *(int *)&keys[0]) ^ e; c = a + pckt->key4; a -= key8; pckt->key0 -= (b ^ c); } while (--count); } void decrypt(unsigned char * data, int len, int key0, int key4, int key8) { int keys[4]; unsigned char * ptr = data; keys[0] = key0; keys[1] = key4; keys[2] = ((key4 >> 0x13) & 0x1FFF) | (key0 << 0x0D); keys[3] = (key4 << 0xD) | ((key0 >> 0x13) & 0x1FFF); int idx = len / 8; int rem = len % 8; if (len >= 8) { do {
Page | 1

decrypt_math(ptr, key8, (int **)&keys); ptr += 8; } while (--idx); } if (rem > 0) { unsigned char *a = (unsigned char *) &key0; unsigned char *b = (unsigned char *) &key8; for (int i=0; i<rem; ++i) { ptr[i] ^= a[i] + b[-(i % 4) + 3]; } } } /* Pass the packet contents or HTTP POST payload */ void get_kraken(unsigned char * data, unsigned int len) { PACKET * hdr; MSG_HDR * msg; unsigned long long value_part = 0; int payload_key = 0; hdr msg = (PACKET *) data; = (MSG_HDR *) &hdr->msg;

/* Generate the payload key */ value_part = ROR64(((unsigned long long)hdr->key0<<32)|(unsigned long long)hdr->key4,13); payload_key = (value_part>>32)&0xFFFFFFFF; if (hdr->key8 != 0) { decrypt((unsigned char *)msg, 12, hdr->key0, hdr->key4, hdr->key8); if (msg->length != 0 && msg->length + 24 == len) { if (msg->type[0] == 0x2) /* server reply */ { value_part = ROR64(((unsigned long long)hdr->key0<<32)|(unsigned long long)hdr->key4,17); payload_key = (value_part>>32)&0xFFFFFFFF; } decrypt((unsigned char *)&hdr->data, msg->length, hdr->key0, hdr->key4, payload_key); } } }

Page | 2

Program 2
Aim: Write a program of RSA algorithm of public key encryption in C++. #include< stdio.h> #include< conio.h> int phi,M,n,e,d,C,FLAG; int check() { int i; for(i=3;e%i==0 && phi%i==0;i+2) { FLAG = 1; return; } FLAG = 0; } void encrypt() { int i; C = 1; for(i=0;i< e;i++) C=C*M%n; C = C%n; printf("\n\tEncrypted keyword : %d",C); } void decrypt() { int i; M = 1; for(i=0;i< d;i++) M=M*C%n; M = M%n; printf("\n\tDecrypted keyword : %d",M); } void main() { int p,q,s; clrscr(); printf("Enter Two Relatively Prime Numbers\t: "); scanf("%d%d",&p,&q); n = p*q; phi=(p-1)*(q-1); printf("\n\tF(n)\t= %d",phi); do { printf("\n\nEnter e\t: "); scanf("%d",&e); check();
Page | 3

}while(FLAG==1); d = 1; do { s = (d*e)%phi; d++; }while(s!=1); d = d-1; printf("\n\tPublic Key\t: {%d,%d}",e,n); printf("\n\tPrivate Key\t: {%d,%d}",d,n); printf("\n\nEnter The Plain Text\t: "); scanf("%d",&M); encrypt(); printf("\n\nEnter the Cipher text\t: "); scanf("%d",&C); decrypt(); getch(); }

*************** OUTPUT ***************** Enter Two Relatively Prime Numbers : 7 17 F(n) = 96 Enter e : 5 Public Key : {5,119} Private Key : {77,119} Enter The Plain Text : 19 Encrypted keyword : 66 Enter the Cipher text : 66 Decrypted keyword : 19

Page | 4

Program 3
Aim: Write a program to implement data encryption standard algorithm using Java. import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import java.io.*; import java.security.spec.AlgorithmParameterSpec; import java.security.NoSuchAlgorithmException; public class DesEncrypt implements Serializable { private transient Cipher ecipher; private SecretKey key; // Buffer used to transport the bytes from one stream to another private transient byte[] buf = new byte[1024]; protected BPMSLogger bpmsLogger = BPMSLogger.getLogger(this.getClass().getName()); public DesEncrypt() { String confDir = ResourcePropertyManager.get("BPMSCONFIG_DIR"); try { // Initializing and Serializing key object. key = KeyGenerator.getInstance("DES").generateKey(); FileOutputStream out = new FileOutputStream(confDir+"/key.object"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeObject(key); s.flush(); s.close(); } catch (NoSuchAlgorithmException exc) { bpmsLogger.logSevere(exc.getMessage()); } catch (IOException e) { bpmsLogger.logSevere(e.getMessage()); } // Create an 8-byte initialization vector byte[] iv = new byte[]{ (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A }; AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv); try { ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // CBC requires an initialization vector ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); } catch (java.security.InvalidAlgorithmParameterException e) { bpmsLogger.logSevere(e.getMessage()); } catch (javax.crypto.NoSuchPaddingException e) { bpmsLogger.logSevere(e.getMessage()); } catch (java.security.NoSuchAlgorithmException e) { bpmsLogger.logSevere(e.getMessage()); } catch (java.security.InvalidKeyException e) { bpmsLogger.logSevere(e.getMessage()); }
Page | 5

} private void encrypt(InputStream in, OutputStream out) { try { // Bytes written to out will be encrypted out = new CipherOutputStream(out, ecipher); // Read in the cleartext bytes and write to out to encrypt int numRead = 0; while ((numRead = in.read(buf)) >= 0) { out.write(buf, 0, numRead); } out.flush(); out.close(); } catch (java.io.IOException e) { bpmsLogger.logSevere(e.getMessage()); } } public static void doEncryption(String source, String dest) { try { String confDir = ResourcePropertyManager.get("BPMSCONFIG_DIR"); // Create encrypter or decrypter class DesEncrypt encrypter = new DesEncrypt(); // Do the Encryption here... encrypter.encrypt(new FileInputStream(source), new FileOutputStream(confDir + dest)); System.out.println("Encryption completed. Please see the BPMS config dir."); } catch (Exception e) { e.printStackTrace(); } } }

Page | 6

Program 4
Aim: Write a program to generate a random number sequence for encryption using Java. package com.mindprod.example; import java.util.BitSet; import java.util.Random; public final class TestCollisionProbability { // ------------------------------ FIELDS -----------------------------private static final int MAX_TRIALS = 1000000; private static final int MIN_TRIALS = 100; private static final long APPROXIMATING_LIMIT_FOR_N = 100000000L; private static final long SIMULATING_LIMIT_FOR_M = 10000000L; private static final long SIMULATING_LIMIT_FOR_N = 1000000L; private static final Random wheel = new Random(); // -------------------------- STATIC METHODS -------------------------private static double calculateTheoreticalProbability( long n, long m ) { double probabilityOfNoCollision = 1.0d; // loop would fail utterly for n= Long.MAX_VALUE and would never // complete for very large n. for ( long i = 0; i < n; i++ ) { probabilityOfNoCollision *= ( double ) ( m - i ) / m; } return probabilityOfNoCollision; } private static void display( double probabilityOfNoCollision, String description, long n, long m ) { double probabilityOfCollision = 1.0d - probabilityOfNoCollision; System.out.println( "Generating n=" + n + " Strings of m=" + m + " possible Strings\n" + "that you could generate with " + description + ",\n" + "the probability of collision is " + probabilityOfCollision + "\n" + "where 0 is never, and 1 is always," ); if ( probabilityOfCollision <= 0.0 ) { System.out.println( "in other words, don't worry about collisions." ); } else if ( probabilityOfCollision >= 1.0 ) { System.out.println( "in other words, collisions will always happen." ); } else { System.out.println( "or one in " + 1 / probabilityOfCollision ); } } private static void displaySamples() System.out.println( "Sample random decimal string: " + Long.toString( wheel.nextLong() & Long.MAX_VALUE ) );
Page | 7

System.out.println( "Sample random hex string: " + Long.toHexString(wheel.nextLong() & Long.MAX_VALUE ) ); System.out.println( "Sample random alphabetic string: " + Long.toString( wheel.nextLong() & Long.MAX_VALUE,36 ) ); } private static double estimateTheoreticalProbability( long n, long m ) { System.out.println( "approximating..." ); return Math.pow( ( double ) ( m - n ) / m, n ); } private static double simulateActualProbability( long n, long m, int trials ) { assert trials >= MIN_TRIALS : "not enough trials"; assert trials <= MAX_TRIALS : "too many trials"; assert n <= SIMULATING_LIMIT_FOR_N : "n too large"; assert m <= SIMULATING_LIMIT_FOR_M : "m too large"; assert SIMULATING_LIMIT_FOR_N < Integer .MAX_VALUE : "SIMULATING_LIMIT_FOR_N too large."; assert SIMULATING_LIMIT_FOR_M < Integer .MAX_VALUE : "SIMULATING_LIMIT_FOR_M too large."; System.out.println( "\nSimulating " + trials + " trials of n=" + n + " numbers each in range 0 .. m=" + m + "." ); int m1 = ( int ) m; // will consume roughly m/8 bytes. BitSet b = new BitSet( m1 ); int collisions = 0; for ( int t = 0; t < trials; t++ ) { b.clear(); for ( int i = 0; i < n; i++ ) { int poss = wheel.nextInt( m1 ); if ( b.get( poss ) ) { // oops had a collision this trials. collisions++; break; } else { b.set( poss ); } } } return ( double ) ( trials - collisions ) / trials; } // --------------------------- main() method --------------------------public static void main( String[] args ) { // n = how many "unique" Strings you plan to generate
Page | 8

if ( args.length != 3 ) { throw new IllegalArgumentException( "You must have n, the number of generated Strings and m, the number of possible Strings, and t, the number of trials on the command line." ); } long n = Long.parseLong( args[ 0 ] ); long m = Long.parseLong( args[ 1 ] ); int trials = Integer.parseInt( args[ 2 ] ); if ( !( 0 < n && n < m ) ) { throw new IllegalArgumentException( "You must have 0 < n < m" ); } if ( !( MIN_TRIALS <= trials && trials <= MAX_TRIALS ) ) { throw new IllegalArgumentException( "Must have " + MIN_TRIALS + " <= trials <= " + MAX_TRIALS ); } // Show some typical random strings displaySamples(); double probabilityOfNoCollision; if ( n <= APPROXIMATING_LIMIT_FOR_N ) { probabilityOfNoCollision = calculateTheoreticalProbability( n, m ); } else { probabilityOfNoCollision = estimateTheoreticalProbability( n, m ); } display( probabilityOfNoCollision, "a true number generator", n, m ); if ( n <= SIMULATING_LIMIT_FOR_N && m <= SIMULATING_LIMIT_FOR_M ) { probabilityOfNoCollision = simulateActualProbability( n, m, trials ); display( probabilityOfNoCollision, "Sun's java.util.Random pseudo-random number generator", n, m ); } else { System.out.println( "The problem too big to simulate." ); } }// end main }

Program 5
Page | 9

Aim: Write a program to generate hash function using Java. import Java.util.*; import Java.lang.*; // x + 31x = x(31 + 1) = x + 31 + 31(x-1) public class Identical { public static void main(String[] args) { String s1 = new String("BB"); String s2 = new String("Aa"); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); } } ********************OUTPUT on my RedHat 6.2 box using the kaffe compiler.******************** [bash]$ javac Identical.java [bash]$ java Identical 2112 2112 [bash]$

Program 6
Page | 10

Aim: Write a program to implement the Blowfish algorithm using Java. import java.lang.*; import javax.crypto.spec.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import java.util.*; import java.io.*; public class Encrypt { Cipher _cipher; SecretKey key; Encrypt() { try { KeyGenerator keygen = KeyGenerator.getInstance("Blowfish"); key = keygen.generateKey(); _cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); } catch(Exception e) { System.out.println("Exception Occured : "+e); } } public String encrypt(String str) { try { _cipher.init(Cipher.ENCRYPT_MODE, key); // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = _cipher.doFinal(utf8); // Encode bytes to base64 to get a string return new sun.misc.BASE64Encoder().encode(enc); } catch (Exception e) { //System.out.println(e); } return null; } public String decrypt(String str) { try { _cipher.init(Cipher.DECRYPT_MODE, key); // Decode base64 to get bytes byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); // Decrypt byte[] utf8 = _cipher.doFinal(dec); // Decode using utf-8 return new String(utf8, "UTF8"); } catch (Exception e) { System.out.println(e); }
Page | 11

return null; } public static void main(String argv[]) // for execution as application { Encrypt encrytInstance = new Encrypt(); FileOutputStream encryptionDecryptionOutput; FileInputStream input; DataOutputStream out; DataInputStream in; /*----------------------For encrypting the text data file----------------------*/ try { input = new FileInputStream("myfile.txt"); in = new DataInputStream(input); encryptionDecryptionOutput = new FileOutputStream("EncryptionOutput"); out = new DataOutputStream(encryptionDecryptionOutput); while(in.available() != 0) { out.writeBytes(encrytInstance.encrypt(in.readLine())); } in.close(); out.close(); } catch(Exception e) { System.err.println("Error writing to file on Encryption"); } /*-------------------For decrypting the encrypted data file------------------*/ try { input = new FileInputStream("EncryptionOutput"); in = new DataInputStream(input); encryptionDecryptionOutput = new FileOutputStream("DecryptionOutput.txt"); out = new DataOutputStream(encryptionDecryptionOutput); while(in.available() != 0) { out.writeBytes(encrytInstance.decrypt(in.readLine())); } in.close(); out.close(); } catch(Exception e) { System.err.println("Error writing to file on Decryption"); } } }

Program 7
Page | 12

Aim: Design a public key cryptography using Java class Rsa07{ public static void main(String[] args){ long e;//encryption key long d;//decryption key long n = 14;//fixed divisor long c;//encrypted value long x;//decrypted value Vector base = new Vector(); Vector temp = new Vector(); System.out.println("n = " + n); System.out.println("Range for m: 0 to " + (n - 1)); System.out.println("Range for e: 0 to " + (n - 1)); System.out.println("Range for d: 0 to " + (n - 1)); for(long m = 1; m < n; m++) { for(e = 2; e < n; e++) { c = applyRSA(m,e,n); static long applyRSA(long val,long exp,long n) { long temp = val; for(int cnt = 0; cnt < (exp - 1); cnt++) { temp *= val; if(val >= (Long.MAX_VALUE/val - 1)) { System.out.println( "Arithmetic overflow probable."); System.out.println("Terminating program."); System.exit(1); } //end if } //end for loop //Compute the modulus of the modified input // value using n as a modulus divisor. return temp % n; } //end applyRSA for(d=2;d < n;d++) { x = applyRSA(c,d,n); if(x == m) { if(m == 1 && d != e) { base.add( "d:" + d + "-" + "e:" + e); } else if(d != e) { temp.add( "d:" + d + "-" + "e:" + e); } //end else } //end if(x == m) } //end for loop on d } //end for loop one if(m > 1){ andVectors(base,temp); }//end if //Initialize a new empty temp Vector for
Page | 13

// processing the next value of m. temp = new Vector(); }//end for loop on m static void andVectors( Vector base,Vector temp) { Iterator iter = base.iterator(); while(iter.hasNext()) { //Get next element from base. Object str = iter.next(); //Test to see if temp contains a matching // element. Remove the element from base // if there is no match. if(!temp.contains(str)) { iter.remove(); } //end if } //end while } //end andVectors System.out.println("Allowable keys"); Iterator iter = base.iterator(); while(iter.hasNext()) { String str = (String)iter.next(); System.out.println(str); } //end while } //end main BigInteger e; //encryption key BigInteger d; //decryption key BigInteger n = new BigInteger("77"); BigInteger c; //encrypted value BigInteger x; //decrypted value BigInteger bigOne = new BigInteger("1"); System.out.println("n = " + n); System.out.println("Range for m: 0 to " + (n.subtract(bigOne))); System.out.println("Range for e: 0 to " + (n.subtract(bigOne))); System.out.println("Range for d: 0 to " + (n.subtract(bigOne))); for(BigInteger m = new BigInteger("1"); m.compareTo(n) < 0; m = m.add(bigOne)) { for(e = new BigInteger("2"); e.compareTo(n) < 0; e = e.add(bigOne)) { c = applyRSA(m,e,n); class Rsa01 { public static void main(String[] args) { BigInteger p = new BigInteger("47"); BigInteger q = new BigInteger("59"); BigInteger n = p.multiply(q); BigInteger d = new BigInteger("157"); BigInteger e = new BigInteger("17"); String plainText = "ITS ALL GREEK TO ME";
Page | 14

String encodedText = ""; String cipherText = ""; String decipheredText = ""; String outputText = ""; System.out.println("p: " + p); System.out.println("q: " + q); System.out.println("n: " + n); System.out.println("d: " + d); System.out.println("e: " + e); Rsa01 obj = new Rsa01(); while(plainText.length()%4 != 0) { //Append a space character on the end plainText += " "; } //end while System.out.println( "plainText\n" + plainText); encodedText = obj.encode(plainText); System.out.println( "encodedText\n" + encodedText); String encode(String plainText) { byte[] textChars = plainText.getBytes(); String temp = ""; String encodedText = ""; //Build the encoded text string two numeric // characters at a time. Each plainText // character is converted to two numeric // characters according to the relationships // given above. for(int cnt = 0; cnt < plainText.length();cnt++) { temp = String.valueOf( textChars[cnt] - 'A' + 1); //Handle the special case of a space // character. if(temp.equals("-32")) temp = "00"; //Convert all single-character numeric // values to two characters with a leading // zero, as in 09. if(temp.length() < 2) temp = "0" + temp; encodedText += temp; } //end for loop return encodedText; } //end encode cipherText = obj.doRSA(encodedText,e,n); System.out.println( "cipherText\n" + cipherText);\ String doRSA(String inputString, BigInteger exp,BigInteger n) { BigInteger block; BigInteger output; String temp = ""; String outputString = ""; for(int cnt = 0; cnt < inputString.length(); cnt += 4)
Page | 15

{ temp = inputString.substring(cnt,cnt + 4); block = new BigInteger(temp); output = block.modPow(exp,n); temp = output.toString(); if(temp.length() == 3) { temp = "0" + temp; } else if(temp.length() == 2) { temp = "00" + temp; } else if(temp.length() == 1) { temp = "000" + temp; } //end else if outputString += temp; }//end for loop return outputString; }//end dorsa decipheredText = obj.doRSA(cipherText,d,n); System.out.println( "decipheredText\n" + decipheredText); outputText = obj.decode(decipheredText); System.out.println( "outputText\n" + outputText); }//end main

*******************Output********************** p: 19 q: 503 n: 9557 phi: 9036 e: 17 d: 7973 plainText 0123 89!@ abcd ABCD EF~encodedText 161718190024250132006566676800333435360037389413 cipherText 831382420004363732998462293181478621167049176719 decipheredText 161718190024250132006566676800333435360037389413 outputText 0123 89!@ abcd ABCD EF~-

Page | 16

Program 8
Aim: Generate a program to implement MD5 in C++. #include "stdafx.h" using namespace System; using namespace System::Security::Cryptography; using namespace System::Text; String^ getMD5String(String^ inputString) { array<Byte>^ byteArray = Encoding::ASCII->GetBytes(inputString); MD5CryptoServiceProvider^ md5provider = gcnew MD5CryptoServiceProvider(); array<Byte>^ byteArrayHash = md5provider->ComputeHash(byteArray); return BitConverter::ToString(byteArrayHash); } int main(array<System::String ^> ^args) { Console::WriteLine(getMD5("my string")); Console::ReadKey(); return 0; }

Page | 17

Program 9
Aim: Design a program to do following in C++

(i)
(i)

Encrypt a file / string

(ii)

Decrypt a file / string

Encrypt a file / string

#include <iostream.h> #include <stdlib.h> #include <fstream.h> #include <stdio.h> bool password(); void doCrypt(char *cool) { int cryp; //the main int this function uses char x; //to get the chars from the file ifstream in; //the input stream ofstream out; //the output stream in.open(cool); //opening the input file if(in.fail()){ //check if it's not there cout<<"Couldn't open the IN file\n"; //if it's not, print return; } cout<<"enter the OUT file name: "; //enter the output filename cin>>cool; //get it out.open(cool); //open the output file in.get(x); //get the first char of input if(in.eof()) //if read beyong end of file return; //quit while(x != EOF){//while x is not beyong End Of File cryp=x-0xFACA; //the crypting out<<(char)cryp; //print the crypted char in.get(x); //get another char if(in.eof()) //if read beyong end of file break; } in.close(); out.close(); return; } void deCrypt(char *daf) { int decr; //the main int char x; //the input char ifstream in; //input stream ofstream out; //output stream in.open(daf); //open the inout stream if(in.fail()){//see if it's not there cout<<"Error couldn't open the IN file\n";//print return; } cout<<"Enter the OUT file name: "; //ask for the out filename cin>>daf; out.open(daf); //open the outfile in.get(x); //get the input char if(in.eof()) //if read beyong end of file return;
Page | 18

while(x!=EOF){ //while x is not beyong end of file decr=x+0xFACA; //the dectypring out<<(char)decr; in.get(x); //get the next char if(in.eof()) //if read beyong the eon of file break; } return; } int main(void) { if (password()) cout << "Access Granted: \n"; else { cout << "You are not Authorized to use this program!\n"; system("pause"); return 0; } char *cool=new char[20];//the name pointer char nav; //"navigation char" cout << "*---------------------------------------------*\n"; cout << "| This is an encryption program. I'm not |\n"; cout << "| taking credit for this. This was a |\n"; cout << "| recent submission on planet-source-code |\n"; cout << "| I just added password protection to it. |\n"; cout << "*---------------------------------------------*\n\n"; system("pause"); cout << "\n\n"; cout << "Use \"m\" for the Menu\n";//print instructions while(true){ cin >> nav; switch(nav){ case 'm': cout << "COMMAND\tFUNCTION\n"; cout << "e \tencrypt\n" "d \tdecrypt\n" "m \t menu \n" "q case 'e': cout << "Enter the file name: \nExample: \"file\".txt\n"; cin >> cool; doCrypt(cool); break; case 'd': cout << "Enter the file name: "; cin >> cool; deCrypt(cool); break; case 'q': exit(0); break; default: cout << "I do not understand you!\n"; break; } } } bool password() { char string1[50]; cout << "Enter in the encryption password: \n"; gets(string1); if (strcmp(string1, "outlaw")) return 0; return 1; }

\t quit \n"; break;

Page | 19

(ii)

Decrypt a file / string

#include <iostream> #include <fstream> #include <string> using namespace std; string DeCrypto(string eText) { char ff = ' ', c1, c2, k; string dText; char hold[BUFSIZ] = {0}; for(int i = 0; i < eText.length() / 2; i++) { c1 = eText[2 * i]; c2 = eText[2 * i + 1]; if(c1 > c2) k = (char)((c1 - c2) + ff); else k = (char)((c2 + c1) - ff); hold[i] = k; } dText = hold; return dText; } int main ( void ) { fstream in("test.txt"); string a, b; while ( in.good() ) { getline ( in, a ); b = DeCrypto ( a ); cout<< b <<"\n"; } return 0; }

Page | 20

Program 10
Aim: Design a program with caesar cipher in C++ for Monoalphabetic substitution cipher. #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]);
Page | 21

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; }

Page | 22

You might also like