Caeser Shift Decipher/Encipher in JavaScript

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

Caeser Shift Decipher/Encipher in JavaScript

Post by jalvarg on Thu Dec 12, 2013 6:06 pm
([msg=78466]see Caeser Shift Decipher/Encipher in JavaScript[/msg])

I'm reading The Code Book by Simon Singh and it has a small Caesar Shift exercise so I decided to make a program to decipher it. For me it works fine, its a straight forward function that uses arrays. I'd like to know of other means of achieving the same end, maybe objects, or some advice on advanced mathematical techniques...anything really. Heres my code:

Code: Select all
var alpha = ["a","b","c","d","e","f","g","h","i","j","k",
            "l","m","n","o","p","q","r","s","t","u","v","w","x",
            "y", "z"];

cipherText = []; // storage for message

function clearArray(){ // clears storage after every use within cShift
    cipherText = [];
    return cipherText;
}

function cShift(word, shift){ // creates Caesar shift from original text and sends to cipherText
    //console.log("The word is - " + word + "\n");
    for(var s = 0; s < word.length; s++){
        for(var a = 0; a < alpha.length; a++){
            if(word[s] === alpha[a]){
                var newLetterPosition = a + shift;
                if(newLetterPosition > (alpha.length-1)){
                    var cLetterPosition = newLetterPosition - (alpha.length);
                    //console.log(cLetterPosition + " - " + alpha[cLetterPosition] + "\n");
                    cipherText += alpha[cLetterPosition];
                } else {
                    //console.log(newLetterPosition + " - " + alpha[newLetterPosition] + "\n");
                    cipherText += alpha[newLetterPosition];
                }
            }
        }
        if(word[s] === " "){
        cipherText += " ";
        }
    }

}

function makeClean(array){ // stringifies array of strings to single string
    var clean = array.toString();
    console.log(clean);
}

function runThrough(plainText){ // runs throw and prints all possible shifts.
    for(var c = 0; c < 26; c++){
        console.log(c + ": ");
        clearArray();
        cShift(plainText, c);
        makeClean(cipherText);
        console.log("\n");
    }
}

function checkShift(plainText, num){ // checks out a single specified shift and prints it.
    clearArray();
    cShift(plainText, num);
    makeClean(cipherText);
    console.log(num + ": " + "\n");
}

// Examples of decoded messages -
//checkShift("mhily lza xbpzxbl mvyabuhl hwwpbz jshbkpbz jhljbz kpjabt hyjhubt lza ulbayvu", 19);
//runThrough("mhily lza xbpzxbl mvyabuhl hwwpbz jshbkpbz jhljbz kpjabt hyjhubt lza ulbayvu");
//runThrough("qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald");
jalvarg
New User
New User
 
Posts: 3
Joined: Tue Nov 26, 2013 12:33 pm
Blog: View Blog (0)


Re: Caeser Shift Decipher/Encipher in JavaScript

Post by 0phidian on Fri Dec 13, 2013 6:32 pm
([msg=78484]see Re: Caeser Shift Decipher/Encipher in JavaScript[/msg])

An alternative to using arrays would be adding or subtracting the ascii values of the characters in the cipher text by the shift value. For instance in c++ the following sets the value of x to 'b'.
Code: Select all
char x = 'a' + 1;

Or in javascript it would look something like this
Code: Select all
String.fromCharCode(c.charCodeAt(0) + 1);
User avatar
0phidian
Poster
Poster
 
Posts: 270
Joined: Sat Jun 16, 2012 7:04 pm
Blog: View Blog (0)


Re: Caeser Shift Decipher/Encipher in JavaScript

Post by fashizzlepop on Fri Dec 13, 2013 8:05 pm
([msg=78489]see Re: Caeser Shift Decipher/Encipher in JavaScript[/msg])

In this case, you'd also have to be careful to make sure to avoid random ascii chars you don't want to include.
The glass is neither half-full nor half-empty; it's merely twice as big as it needs to be.
User avatar
fashizzlepop
Developer
Developer
 
Posts: 2303
Joined: Sat May 24, 2008 1:20 pm
Blog: View Blog (0)


Re: Caeser Shift Decipher/Encipher in JavaScript

Post by -Ninjex- on Sat Dec 14, 2013 10:17 am
([msg=78495]see Re: Caeser Shift Decipher/Encipher in JavaScript[/msg])

Reminds me of a program I made a while back.
This was programmed in Ruby to knock some rust off. I should update this to work via CLI but I'm too lazy.
Code: Select all
#!/usr/bin/ruby
prompt, option, @matches = "> ", "", Array.new

def enc(s, n)
  return s.gsub(/[^ ]/){|x| (x[0].ord + n).chr}
end

def dec(s, n)
  return s.gsub(/[^ ]/){|x| (x[0].ord - n).chr}
end

def search(str, shift)
  f = File.open("dict.txt")
  f.each do |line|
    if enc(line.strip, shift) == str
      @matches.push(shift)
    end
end
end

def crack(s)
  words = s.split(' ')
  words.each do |x|
    for i in (0..25)
      search(x, i)
    end
  end
  puts "<==========>"
  @matches.uniq.each do |x|
    puts "POSSIBLE SHIFT VALUES"
    puts "Shift Value: #{x}:"
    puts dec(s, x.to_i)
    puts "<==========>"
  end
end

while option != "q"
  print "Options [e]ncrypt, [d]ecipher], [c]rack, [q]uit: "
  option = gets.chomp
  if option == "e"
    puts "Enter string:"; print prompt
    s = gets.chomp
    puts "Enter Shift Value:"; print prompt
    n = gets.chomp.to_i
    cipher = enc(s, n)
    puts cipher
  elsif option == "d"
    puts "Enter Encrypted String:"; print prompt
    s = gets.chomp
    puts "Enter Shift value:"; print prompt
    n = gets.chomp.to_i
    text = dec(s, n)
    puts text
  elsif option == "c"
    puts "Enter string:"; print prompt
    s = gets.chomp
    crack(s)
  elsif option == "q" then puts "Good bye!"
  else
    puts "Invalid Option #{option}"
    puts "use \"e\" to encrypt a string"
    puts "use \"d\" to decode a string"
    puts "use \"c\" to attempt to crack a shift value"
    puts "use \"q\" to quit"
  end
end

If you want to use the shift cracking option, I hard coded the dictionary path (again because I am lazy and sloppy sometimes) so you will need a file named dict.txt in the same dir as the script before running. The method works by taking each word in the encrypted string and comparing it to the dictionary word that we will add shift values of 1-26 to. If we get a match, the current shift could be a possible match.

Screenshot

Of course this isn't bulletproof, as some ASCII values can easily be extended out of range, amongst tons of other flaws. Once again, laziness has my heart with this.
If you're not willing to learn, no one can help you. If you're determined to learn, no one can stop you.⠠⠵
The absence of evidence is not evidence of absence.
I can explain it for you, but I can't understand it for you.
User avatar
-Ninjex-
Addict
Addict
 
Posts: 1308
Joined: Sun Sep 02, 2012 8:02 pm
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests