Author Topic: Belaso(Vigenere) Cipher  (Read 2483 times)

0 Members and 1 Guest are viewing this topic.

Offline Neea

  • Peasant
  • *
  • Posts: 83
  • Cookies: 19
  • Laboris Gloria Ludi
    • View Profile
Belaso(Vigenere) Cipher
« on: October 03, 2013, 09:35:29 pm »
The Belaso cipher is a classic cipher that uses as key a word and encrypts plain text by dividing it in blocks the size of the key, and adding to each position of the alphabet corresponding to the letter in the block , the position in the alphabet of the letter of the key that shares the same index(comparing the plaintext block and key text)


This was an exercise to get back into programming. It turned out a fun mix of windows forms, C# and C lol.


First variant: Using ASCII code. This one respects a 26 english letter alphabet, from A to Z.


Code: (cpp) [Select]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        string plainTxt, key;
        StringBuilder encrText = new StringBuilder();
        StringBuilder decrText = new StringBuilder();
        public Form1()
        {
            InitializeComponent();
        }
        public String decryption()
        {
            plainTxt = plainText.Text.ToUpper();
            key = keyText.Text;
            int ksize = key.Length;
            int msize = plainTxt.Length;
            char[] txt = plainTxt.ToCharArray();


            for (int i = 0; i < msize; i++)
            {
                char decr = txt[i] - getShift(key, i) < 65 ? (char)((txt[i] - getShift(key, i)) + 27) : (char)((txt[i] - getShift(key, i)) - 1);
                decrText.Append(decr);
            }
            return decrText.ToString();
        }


        public String encryption()
        {
            plainTxt = plainText.Text.ToUpper();
            key = keyText.Text.ToUpper();
            int ksize = key.Length;
            int msize = plainTxt.Length;
            if (ksize > msize) { return "Key size must be smaller than plaintext size"; }
            char[] txt = plainTxt.ToCharArray();


            for (int i = 0; i < msize; i++)
            {
                char encr = txt[i] + getShift(key, i) > 90 ? (char)((txt[i]+ getShift(key,i))- 26) : (char)((txt[i] + getShift(key, i))+1);
                encrText.Append(encr);
            }
            return encrText.ToString();
        }
        private int getShift(string key, int i)
        {
            char[] k = key.ToCharArray();
            int temp = i%key.Length;
            return ((int)key[temp]) - 65;
        }


        private void encrButton_Click(object sender, EventArgs e)
        {
            String encrypted = encryption();
            resultBox.Clear();
            resultBox.AppendText(encrypted);
        }


        private void decrButton_Click(object sender, EventArgs e)
        {
            String decrypted = decryption();
            resultBox.Clear();
            resultBox.AppendText(decrypted);
        }
    }
}





Second variant: Using a predefined 27 char alphabet, including space. This was more fun to write since my C# knowledge is definitely not the best and there were issues that actually raised some 20mins and cig break to think about lol In the end my C knowledge beats my C# lol.


Code: (cpp) [Select]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace BelasoCipher2
{
    public partial class Form1 : Form
    {
        string alpha = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string plainTxt, cdkey;
        public Form1()
        {
            InitializeComponent();
        }
        //Return integer values to plaintext
        public String convertS(List<int> intCrypt)
        {
            int size = intCrypt.Count;
            StringBuilder rez= new StringBuilder();
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < 27; j++)
                {
                    if (intCrypt[i] == j) //if integer value = position add letter to string
                        rez.Append(alpha[j]);
                }
            }
            return rez.ToString();
        }


        //Modulo function for Z classes
        private int mod(int x, int m)
        {
            int r = x % m;
            return r < 0 ? r + m : r;
        }
        //Encryption/decryption algorithm based on integer values of alphabet/key/plaintext
        private string decriEncryAlg(int n){
            plainTxt = ptextBox.Text.ToUpper();
            cdkey = keyBox.Text.ToUpper();
            int size = plainTxt.Length;
            String result;
            List<int> kLi = new List<int>();
            List<int> pLi = new List<int>();
            List<int> resList = new List<int>();
            int klen = cdkey.Length;
            if (klen > size) { return "Key size must be smaller than plaintext size"; }
            kLi = keyCode(cdkey); // get integer position value in the alphabet of key
            pLi = divideString(plainTxt, klen); //get integer position value in the alphabet of plaintext
            int pLiSize = pLi.Count;
            int temp = 0;
            int index = 0;
            while (temp <= pLiSize) // going on chunks of key size up to integer value of plaintext list size
            {
                for (int i = 0; i < klen; i++)
                {
                    if (index >= pLiSize) //If index >= size then return the result of encr/decr
                    {
                        result = convertS(resList);


                        return result;
                    }
                    int tempAux;
                    if(n == 0) tempAux = pLi[index]+kLi[i]; //if 0 then encryption
                    else tempAux = pLi[index]-kLi[i]; //else decryption
                    resList.Add(mod(tempAux, 27));
                    index++;
                }
                temp += klen;
            }
            result = convertS(resList);


            return result;
        }


        public string decryption()
        {
            string result = decriEncryAlg(1);
            return result;
        }


        public string encryption()
        {
            string result = decriEncryAlg(0);
            return result;
         
        }
        //Get integer values according to alphabet of key word
        public List<int> keyCode(string key)
        {
            List<int> list = new List<int>();
            int len = key.Length;
            for (int i = 0; i < len; i++)
            {
                for (int j = 0; j < 27; j++)
                {
                    if (key[i].Equals(alpha[j])) list.Add(j);
                }
            }
            return list;               
        }
        //Divide plaintext in chunks <=the size of key word and get their integer value from the alphabet
        public List<int> divideString(string s, int k)
        {
            List<int> list = new List<int>();
            int size = plainTxt.Length;
            int temp = 0, ke=k;
            StringBuilder aux = new StringBuilder();
            do
            {
                for (int z = temp; z < ke; z++)
                {
                    if (z >= size) break;
                    aux.Append(plainTxt[z]);
                } 
                for (int i = temp; i < ke; i++)
                {
                    if (i >= size) return list;
                    for (int j = 0; j < 27; j++)
                    {
                        if (aux[i].Equals(alpha[j])) list.Add(j);
                    }
                }
                temp = temp + k;
                ke += ke;
            } while (temp <= size+k);
            return list;
        }


        private void encButton_Click(object sender, EventArgs e)
        {
            String encrypted = encryption();
            textBox3.Clear();
            textBox3.AppendText(encrypted);
        }


        private void decrButton_Click(object sender, EventArgs e)
        {
            String decrypted = decryption();
            textBox3.Clear();
            textBox3.AppendText(decrypted);
        }
    }
}


« Last Edit: October 03, 2013, 09:38:06 pm by Neea »
<!--Here be Cthulhu -->

Offline ArkPhaze

  • Peasant
  • *
  • Posts: 136
  • Cookies: 20
  • null terminated
    • View Profile
Re: Belaso(Vigenere) Cipher
« Reply #1 on: November 01, 2013, 02:18:48 am »
Not bad. Lol, your code tags list the code as C++ even though this is C#, but why not make your functions a bit more generic by allowing parameters to be passed? The first point behind a method is to break up the code, the second is to allow it to be manipulable.  ;)

Here is my method of the Vigenere Cipher in C++:
Code: (cpp) [Select]
void vigenere_encrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
int j = 0;
for (size_t i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] += key[j] - 'A';
if (s[i] > 'Z') s[i] += -'Z' + 'A' - 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}

void vigenere_decrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
int j = 0;
for (size_t i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] = s[i] >= key[j] ?
s[i] - key[j] + 'A' :
'A' + ('Z' - key[j] + s[i] - 'A') + 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}

edit: My C# implementation with demo usage:
Code: (csharp) [Select]
static void VigenereEncrypt(ref StringBuilder s, string key)
{
for (int i = 0; i < s.Length; i++) s[i] = Char.ToUpper(s[i]);
key = key.ToUpper();
int j = 0;
for (int i = 0; i < s.Length; i++)
{
if (Char.IsLetter(s[i]))
{
s[i] = (char)(s[i] + key[j] - 'A');
if (s[i] > 'Z') s[i] = (char)(s[i] - 'Z' + 'A' - 1);
}
j = j + 1 == key.Length ? 0 : j + 1;
}
}

static void VigenereDecrypt(ref StringBuilder s, string key)
{
for (int i = 0; i < s.Length; i++) s[i] = Char.ToUpper(s[i]);
key = key.ToUpper();
int j = 0;
for (int i = 0; i < s.Length; i++)
{
if (Char.IsLetter(s[i]))
{
s[i] = s[i] >= key[j] ?
  (char)(s[i] - key[j] + 'A') :
  (char)('A' + ('Z' - key[j] + s[i] - 'A') + 1);
}
j = j + 1 == key.Length ? 0 : j + 1;
}
}

public static void MainMethod()
{
StringBuilder s = new StringBuilder("ArkPhaze");
const string key = "KeyData";
VigenereEncrypt(ref s, key);
Console.WriteLine(s);
VigenereDecrypt(ref s, key);
Console.WriteLine(s);
}

Numeric values in the key will screw up the encryption, and thus the decryption however. Only use letters. I could've thrown an exception in that case, but I'll leave it up to you as to what you want to do with that.
« Last Edit: November 01, 2013, 02:54:34 am by ArkPhaze »
sig=: ArkPhaze

[ J/ASM/.NET/C/C++ - Software Engineer ]

Offline Neea

  • Peasant
  • *
  • Posts: 83
  • Cookies: 19
  • Laboris Gloria Ludi
    • View Profile
Re: Belaso(Vigenere) Cipher
« Reply #2 on: November 01, 2013, 06:50:02 am »
Not bad :) I really didn't think it that way +1 for the idea. Definitely improved the complexity :)
<!--Here be Cthulhu -->