Jump to content

Programming Challange: Ceaser Cipher

majorawsome

Well, I have been learning Cryptology in my math class, and I have been trying to make a program that deciphers the Ceaser cipher I realized how this program has been a challange for me. I then thought, hey, why not make this the first Challange on the Forum? So now I am making a challange.

 

But first, what is the Ceaser cipher? It is when you take a string of characters and shift them left or right. So if you have a  string "abcd" and shift right 1, it will be "bcde". Also take a look at this link for a better explanation http://www.cs.trincoll.edu/~crypto/historical/caesar.html

 

Challange: Create a program that Deciphers and Ciphers a string of characters.

 

How to Answer: Attach a picture of the program and the code.

 

 

Do you want to know what grinds my gears?
The old forum.

Link to comment
Share on other sites

Link to post
Share on other sites

Here's my solution, written in pure C code.

 

I wrote this code assuming the messages only consist of spaces and lowercases. It works quite well, even if it does not check the input for accuracy - I intentionally skipped those parts so that you can concentrate on the main decoding/encoding logic:

#include <stdlib.h>#include <stdio.h>#include <string.h>int main(int argc, char **argv){    printf("Action: ");    char action[10];    fgets(action, 10, stdin);    char str[1000];    if(!strcmp(action, "encipher\n"))    {        printf("Enter string to encipher (max. 999 letters & only lowercases):\n");        fgets(str, 1000, stdin);        int shiftValue = 0;        printf("Enter shift value: ");        scanf("%d", &shiftValue);        if(shiftValue > 0)        {            for(int i = 0; str[i]; ++i)            {                if(str[i] == ' ' || str[i] == '\n')                    continue;                str[i] += shiftValue;                while(str[i] > 'z')                {                    str[i] = 'a' + (str[i] - 'z');                }            }        }        else if(shiftValue < 0)        {            for(int i = 0; str[i]; ++i)            {                if(str[i] == ' ' || str[i] == '\n')                    continue;                str[i] -= shiftValue;                while(str[i] < 'a')                {                    str[i] = 'z' - ('a' - str[i]);                }            }        }        printf("Enciphered message: \n%s", str);    }    else if(!strcmp(action, "decipher\n"))    {        printf("Enter string to decipher (max. 999 letters & only lowercases):\n");        fgets(str, 1000, stdin);        int shiftValue = 0;        printf("Enter shift value: ");        scanf("%d", &shiftValue);        if(shiftValue < 0)        {            for(int i = 0; str[i]; ++i)            {                if(str[i] == ' ' || str[i] == '\n')                    continue;                str[i] += shiftValue;                while(str[i] > 'z')                {                    str[i] = 'a' + (str[i] - 'z');                }            }        }        else if(shiftValue > 0)        {            for(int i = 0; str[i]; ++i)            {                if(str[i] == ' ' || str[i] == '\n')                    continue;                str[i] -= shiftValue;                while(str[i] < 'a')                {                    str[i] = 'z' - ('a' - str[i]);                }            }        }        printf("Enciphered message: \n%s", str);    }    else    {        printf("Invalid command!\n");        exit(-1);    }    return 0;}

I found this much more readable than a picture of the code. But here is a picture of the application running in the console: http://oi42.tinypic.com/2qsb1w9.jpg

Link to comment
Share on other sites

Link to post
Share on other sites

choice = input("Choose an action:\r\n 1: Encipher\r\n 2: Decipher\r\n")while (choice != "1" and choice != "2"):    choice = input("Please choose a valid action:\r\n 1: Encipher\r\n\ 2: Decipher\r\n")if choice == '1':    string = input("\r\nEnter a string to encipher (lowercase):\r\n")else:    string = input("\r\nEnter a string to decipher (lowercase):\r\n")shift = int(input("\r\nEnter shift value: "))newstr = ''if choice == '1':    for char in string:        newstr += chr((ord(char) - ord('a') + shift)  % 26 + ord('a'))else:    for char in string:        newstr += chr((ord(char) - ord('a') - shift)  % 26 + ord('a'))print("\r\nMessage:\r\n" + newstr)

Written in Python 3, and a screenshot: http://i.imgur.com/ogZBUs1.png

 

Link to comment
Share on other sites

Link to post
Share on other sites

Man the difference in amount of code required between C and python becomes so apparent in the above two examples.

Not really, the formatting in the C++ code added 30+ lines that was just  '{' and '}'. it could also be compacted to the same size as the python code

CPU: i7 4770k | GPU: Sapphire 290 Tri-X OC | RAM: Corsair Vengeance LP 2x8GB | MTB: GA-Z87X-UD5HCOOLER: Noctua NH-D14 | PSU: Corsair 760i | CASE: Corsair 550D | DISPLAY:  BenQ XL2420TE


Firestrike scores - Graphics: 10781 Physics: 9448 Combined: 4289


"Nvidia, Fuck you" - Linus Torvald

Link to comment
Share on other sites

Link to post
Share on other sites

Not really, the formatting in the C++ code added 30+ lines that was just  '{' and '}'. it could also be compacted to the same size as the python code

 

Could cut it down to about 90-95 lines by removing some of the useless brackets.

Link to comment
Share on other sites

Link to post
Share on other sites

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Cryptology{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Hello, and welcome to an encryption/decryption program writtern in C# by Austin DeLauney");            Console.WriteLine("Enter 1 for encryption and 2 for decryption, and 3 for letter analysis");            int decision = Convert.ToInt32(Console.ReadLine());            switch (decision)            {                case 1:                    Console.WriteLine("Please enter the string to encode");                    string toEncode = Console.ReadLine();                    Encrypt e = new Encrypt(toEncode);                    break;                case 2:                    Console.WriteLine("Please enter the string to decode");                    string toDecode = Console.ReadLine();                    Decrypt d = new Decrypt(toDecode);                    break;                case 3:                    Console.WriteLine("Please enter the string to analyze");                    string toAnalyze = Console.ReadLine();                    Analyze a = new Analyze(toAnalyze);                    break;                default:                    Console.WriteLine("NOW RUNNING NOPE.EXE");                    for (int i = 0; i < 10000; i++)                        Console.WriteLine("NOPE");                    Console.Read();                    break;            }            Console.ReadLine();        }    }}

Program.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Cryptology{    class Encrypt    {        String PlainText = null;        Char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();        public Encrypt(String toEncrypt)        {            PlainText = toEncrypt;            Console.WriteLine("Enter 1 for Ceaser, 2 for Vigenere");            int decision = Convert.ToInt32(Console.ReadLine());            switch (decision)            {                case 1:                    Console.WriteLine("GIMME DAT KEY BRUH");                    char charKey = Convert.ToChar(Console.ReadLine());                    Console.WriteLine(CeaserEncipher(charKey));                    break;                case 2:                    Console.WriteLine("GIMME DAT KEY BRUH");                    String stringKey = Console.ReadLine();                    Console.WriteLine(VigenereEncipher(stringKey));                    break;            }            Console.ReadLine();        }        public String CeaserEncipher(char key)        {            StringBuilder sB = new StringBuilder();            //Console.WriteLine((int)(key));            int shift = key - 97;            foreach (var character in PlainText)            {                int val = character - 97;                int remander = (val + shift);                if (remander > ('z' - 97)) //On Overflow                    remander -= 26;                else if (remander < ('a' - 97)) //On Underflow                    remander += 26;                //Console.WriteLine(remander);                sB.Append(Alphabet[remander]);            }            return sB.ToString();        }        public Char CeaserEncipher(char key, int index)        {            //Console.WriteLine((key));            int shift = key - 97;            int val = PlainText[index] - 97;            int remander = (val + shift);            if (remander > ('z' - 97)) //On Overflow                remander -= 26;            else if (remander < ('a' - 97)) //On Underflow                remander += 26;            //Console.WriteLine(remander);            return (Alphabet[remander]);        }        public String VigenereEncipher(String key)        {            StringBuilder sB = new StringBuilder();            key = key.ToLower();            Char[] keyChar = key.ToCharArray();            for (int i = 0; i < PlainText.Length; i++)            {                int remander = i % key.Length;                //Console.WriteLine(keyChar[remander]);                sB.Append(CeaserEncipher(keyChar[remander], i));            }            return sB.ToString();        }    }}

Encrypt.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Cryptology{    class Decrypt    {        String CipherText = null;        Char[] CodeArray = null;        Char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();        public Decrypt (String s)        {            CipherText = s.ToLower();            CodeArray = CipherText.ToCharArray();            Console.WriteLine("Enter 1 for Brute Force Ceaser, 2 for Code Ceaser, 3 for Vigenere");            int decision = Convert.ToInt32(Console.ReadLine());            switch (decision)            {                case 1:                    CeaserDecipher();                    break;                case 2:                    Console.WriteLine("GIMME DAT KEY BRUH");                    char charKey = Convert.ToChar(Console.ReadLine());                    Console.WriteLine(CeaserDecipher(charKey));                    Console.ReadLine();                    break;                case 3:                    Console.WriteLine("GIMME DAT KEY BRUH");                    String stringKey = Console.ReadLine();                    VigenereDecipher(stringKey);                    break;            }        }        public void CeaserDecipher()        {            for (int i = 0; i < Alphabet.Length; i++)            {                Console.Write(Alphabet[Math.Abs(i)] + ": ");                foreach (var character in CipherText)                {                    int val = character - 97;                    int remander = (val - i);                    if (remander > ('z' - 97)) //On Overflow                        remander -= 26;                    else if (remander < ('a' - 97)) //On Underflow                        remander += 26;                    //Console.WriteLine(remander);                    Console.Write(Alphabet[remander]);                }                Console.WriteLine();            }            Console.Read();        }        public String CeaserDecipher(char key)        {            StringBuilder sB = new StringBuilder();            //Console.WriteLine((int)(key));            int shift = key - 97;            foreach (var character in CipherText)            {                int val = character - 97;                int remander = (val - shift);                if (remander > ('z' - 97)) //On Overflow                    remander -= 26;                else if (remander < ('a' - 97)) //On Underflow                    remander += 26;                //Console.WriteLine(remander);                sB.Append(Alphabet[remander]);            }            return sB.ToString();        }        public Char CeaserDecipher(char key, int index)        {            //Console.WriteLine((int)(key));            int shift = key - 97;            int val = CipherText[index] - 97;            int remander = (val - shift);            if (remander > ('z' - 97)) //On Overflow                remander -= 26;            else if (remander < ('a' - 97)) //On Underflow                remander += 26;            //Console.WriteLine(remander);            return (Alphabet[remander]);        }        public void VigenereDecipher(String key)        {            key = key.ToLower();            Char[] keyChar = key.ToCharArray();            for (int i = 0; i < keyChar.Length; i++)            {                keyChar[i] = (char)(keyChar[i]);                //Console.WriteLine(keyChar[i]);            }            for (int i = 0; i < CipherText.Length; i++)            {                int remander = i % key.Length;                //Console.WriteLine(keyChar[remander]);                Console.Write(CeaserDecipher(keyChar[remander], i));            }        }    }}

Decrypt.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Cryptology{    class Analyze    {        String Text = null;        Char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();        int Jump = 0;         public Analyze(string toAnalyze)        {            Text = toAnalyze.ToLower();            Console.WriteLine("Enter the numbers to skip");            Jump = Convert.ToInt32(Console.ReadLine());            PrintLetterOccurence();            Console.ReadLine();        }        private int[] countLetters(int jump, int startingPos)        {            int[] count = new int[26];            for (int i = startingPos; i < Text.Length; i += jump)            {                count[Text[i] - 97]++;            }           /* for (int i = 0; i < count.Length; i++)            {                Console.Write(Alphabet[i] + " ");                Console.WriteLine(count[i]);            }*/            return count;        }        public int[] LetterOccurence()        {            int[] occurence = new int[26];            foreach (var character in Text)            {                int remander = (character - 97);                occurence[remander]++;            }            return occurence;        }        public void PrintLetterOccurence()        {            for (int i = 0; i < Jump; i++)            {                int[] occurence = countLetters(Jump, i);                for (int i2 = 0; i2 < Alphabet.Length; i2++)                {                    Console.Write(Alphabet[i2] + ": ");                    Console.WriteLine(occurence[i2]);                }                Console.WriteLine();            }        }    }}

and Analyze.cs

 

This code is in C#, and the program Decrypts and Encrypts Ceaser, brute forces Ceaser and encrypts, decrypts Vigenere (DIfferent type of Ciphering I learned). It also includes an analyze class that analyzes the amount of letters in the string (For vigenere decryption)

Do you want to know what grinds my gears?
The old forum.

Link to comment
Share on other sites

Link to post
Share on other sites

867216c7ba07386c67ab752ea2ff592d.png

 

SRC

import java.awt.Container;import java.awt.Dimension;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;/** * @date September 11 2012 * @purpose A very simple encryption based off of ROT13 * @author matthewlanglois11 *  */public class SimpleEncryption {    /**     * The main method which initlizes the program.     *      * @param args     *            Any arguments passed to the program.     * @throws UnsupportedLookAndFeelException     * @throws IllegalAccessException     * @throws InstantiationException     * @throws ClassNotFoundException     */    public static void main(final String[] args) throws ClassNotFoundException,            InstantiationException, IllegalAccessException,            UnsupportedLookAndFeelException {        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());        //create an instance of the gui and set it visible        new GUI().setVisible(true);    }    //Max/Mins unicodes for chars A-Z and a-z    private static final int min_lower = 97;    private static final int max_lower = 122;    private static final int min_upper = 65;    private static final int max_upper = 90;    /**     *      *      * @param string The string to encrypt     * @param shift The amount to shift 1-25     * @return The encrypted string     */    public static String encrypt(String string, int shift) {        String encrypted = "";        for (char c : string.toCharArray()) {            if (Character.isLetter©) {                int abyte = ((int) c) + shift;                if (Character.isUpperCase©) {                    if (abyte > max_upper) {//wrap around the alphabet                        abyte = abyte -1 - max_upper + min_upper;                    }                } else {                    if (abyte > max_lower) {//wrap around the alphabet                        abyte = abyte -1 - max_lower + min_lower;                    }                }                encrypted += String.valueOf((char) abyte);            } else {                encrypted += String.valueOf©;            }        }        return encrypted;    }     /**     *     *     * @param string The string to decrypt     * @param shift The shift amount     * @return The decrypted string     */    public static String decrypt(String string, int shift) {        String decrypted = "";        for (char c : string.toCharArray()) {            if (Character.isLetter©) {                int abyte = ((int) c) - shift;                if (Character.isUpperCase©) {                    if (abyte < min_upper) {//wrap around the alphabet                        abyte = abyte + max_upper - min_upper + 1;                    }                } else {                    if (abyte < min_lower) {//wrap around the alphabet                        abyte = abyte + max_lower - min_lower + 1;                    }                }                decrypted += String.valueOf((char) abyte);            } else {                decrypted += String.valueOf©;            }        }        return decrypted;    }}class GUI extends JFrame {    /**     * Checks if a string is a valid integer.     *      * @param message     *            The string to parse.     * @return True if the string is a valid number; otherwise false.     */    public static boolean canParse(String message) {        try {            Integer.parseInt(message);        } catch (Exception e) {            return false;        }        return true;    }    private static final long serialVersionUID = 2053636315187421222L;    public GUI() {        initComponents();    }    private void decryptActionPerformed(final ActionEvent e) {        int amount = 13; // ROT 13 reference        if (canParse(this.amount.getText())) {            amount = Integer.parseInt(this.amount.getText());            if (amount > 25 || amount < 1) {                JOptionPane.showMessageDialog(this,                        "The amount to shift must be between 1-25");                return;            }        }        text.setText(SimpleEncryption.decrypt(encryption.getText(), amount));    }    private void encryptActionPerformed(final ActionEvent e) {        int amount = 13; // ROT 13 reference        if (canParse(this.amount.getText())) {            amount = Integer.parseInt(this.amount.getText());            if (amount > 25 || amount < 1) {                JOptionPane.showMessageDialog(this,                        "The amount to shift must be between 1-25");                return;            }        }        encryption.setText(SimpleEncryption.encrypt(text.getText(), amount));    }    /**     * Set up and add all of the components to the frame.     */    private void initComponents() {        encrypt = new JButton();        decrypt = new JButton();        encryption = new JTextField();        text = new JTextField();        amount = new JTextField();        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);        addWindowListener(new WindowAdapter() {            @Override            public void windowClosing(final WindowEvent e) {                System.exit(1);            }        });        setTitle("Simple Encryption Program by Matt");        final Container contentPane = getContentPane();        contentPane.setLayout(null);        this.setResizable(false);        decrypt.setText("Decrypt");        decrypt.addActionListener(new ActionListener() {            @Override            public void actionPerformed(final ActionEvent e) {                decryptActionPerformed(e);            }        });        contentPane.add(decrypt);        decrypt.setBounds(5, 105, 290, 20);        text.setText("Plain text...");        contentPane.add(text);        text.setBounds(5, 5, 290, 20);        amount.setText("ROT Amount...");        contentPane.add(amount);        amount.setBounds(5, 55, 290, 20);        encryption.setText("Encryption...");        contentPane.add(encryption);        encryption.setBounds(5, 30, 290, 20);        encrypt.setText("Encrypt");        contentPane.add(encrypt);        encrypt.setBounds(5, 80, 290, 20);        encrypt.addActionListener(new ActionListener() {            @Override            public void actionPerformed(final ActionEvent e) {                encryptActionPerformed(e);            }        });        contentPane.setPreferredSize(new Dimension(300, 130));        pack();    }    private JButton encrypt;    private JButton decrypt;    private JTextField text;    private JTextField encryption;    private JTextField amount;}

There are 10 types of people in this world, those who can read binary and those who can't.

There are 10 types of people in this world, those who can read hexadecimal and F the rest.

~Fletch

Link to comment
Share on other sites

Link to post
Share on other sites

A break from walls of text... I'm assuming valid input, since I believe if you make a script for yourself, you know the syntax. In a professional environment I would have documentation for everything :P

import sysout = ''for letr in sys.argv[2]:        if sys.argv[1] is 'e':                out+=chr(ord(letr) + int(sys.argv[3]))        elif sys.argv[1] is 'd':                out+=chr(ord(letr) - int(sys.argv[3]))        else:                print 'Usage for script:\n[e:d] [string] [offset] where \ne = encrypt, d = decrypt \nString = String to pass through \noffset = integer offest of chars'                quit()print out
Link to comment
Share on other sites

Link to post
Share on other sites

 

A break from walls of text... I'm assuming valid input, since I believe if you make a script for yourself, you know the syntax. In a professional environment I would have documentation for everything :P

import sysout = ''for letr in sys.argv[2]:        if sys.argv[1] is 'e':                out+=chr(ord(letr) + int(sys.argv[3]))        elif sys.argv[1] is 'd':                out+=chr(ord(letr) - int(sys.argv[3]))        else:                print 'Usage for script:\n[e:d] [string] [offset] where \ne = encrypt, d = decrypt \nString = String to pass through \noffset = integer offest of chars'                quit()print out

 

Is this Python 2?

Link to comment
Share on other sites

Link to post
Share on other sites

Is this Python 2?

 

Yes, ran in python2.7.2. Shouldn't differ too much for basic stuff like this.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×