How do you decipher the rail fence cipher with a simple method for beginners?

552 Views Asked by At

Here's the code for the encryption. First every second letter is set and then every other letter(input: abcdefgh; output: acegdfh). I can't figure out the decryption. I figured, seperating the encrypted text in two and alternately taking a letter from each would work. Any ideas for the code?

onEvent("button_encrypt", "click", function(encrypt) {
  var text = getText("text_input1"); 
  var encripted = "";
  var i = 0;
  while ((i < klartext.length)) {
    encrypted = encrypted + text.charAt(i);
    i = i + 2;
  }
  i = 1;
  while ((i < text.length)) {
    encrypted = encrypted + text.charAt(i);
    i = i + 2;
  }
  setText("text_input1", encrypted); 
});
1

There are 1 best solutions below

0
On

I like this encryption style. I mocked up the solution in a Code.org app for testing and such.

Encrypt First I cleaned up the encryption code a little. I found a couple variable names that got off slightly.

onEvent("button_encrypt", "click", function(encrypt) {
  var text = getText("text_input1"); 
  var encrypted = "";
  
  var i = 0;
  while (i < text.length) {
    encrypted = encrypted + text.charAt(i);
    i = i + 2;
  }
  
  i = 1;
  while (i < text.length) {
    encrypted = encrypted + text.charAt(i);
    i = i + 2;
  }
  //changed ID, do to design
  setText("resultLbl", encrypted); 
});

Decryption I tackled decryption by taking the encrypted data, splitting it in half, then pealing the front letter off each half, alternating back and forth.

onEvent("decryptBtn", "click", function(){
  var text = getText("text_input1"); 
  var decrypt = "";
  
  //break message in half
  var half1 = text.substring(0,text.length/2);
  var half2 = text.substring(text.length/2);

  //Loop through two variables. If one is longer will always be half1.
  //Could do this with two index variables, but I did it by shrinking words
  while(half1.length > 0){
    //add to solution
    decrypt = decrypt + half1.substring(0,1);
    //cut the letter off the encrypted string once used
    half1 = half1.substring(1);
    
    //Repeat for half2
    //If protects from edge case of one more letter in half1
    if(half2.length > 0){
      decrypt = decrypt + half2.substring(0,1);
      half2 = half2.substring(1);
    }
  }
  
  setText("resultLbl", decrypt);
});