0

I have a function which has to change characters from one array to the characters from another. It is kind of simple encryption. I have:

var plainArray = ['A','B','C',...,'Z'];
var cipherArray = ['a','b','c',...,'z'];
function rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)

already working. Now I have to write a function which will change given word into encrypted word.

function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet)
{
   var encryptedString = signalCharacter;
   //i is what will hold the results of the encrpytion until it can be appended to encryptedString
   var i;
   // rotate array to signal character position
   var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
   for (var count = 0; count < plainText.length; count++)
   {
       plainAlphabet = plainText.charAt(count);
       i = cipherAlphabet[plainAlphabet];
       encryptedString = encryptedString + rotateArray[i];
   }

   return encryptedString;
}

This function returns signal character and then a string of errors. Do you know what is wrong?

3
  • 6
    What are the errors? Commented May 21, 2011 at 10:33
  • 1
    What is rotateToPosition function? Commented May 21, 2011 at 13:35
  • What are you using this for? I ask this because having your encryption algorithm in JS for all to see, isn't very secure. You would be better off having the encryption take place on the server. Commented May 21, 2011 at 13:55

1 Answer 1

1

You are overwriting plainAlphabet with one character, thus discarding the alphabet. I guess that's not what you want.

However, you only posted the signature of rotateToPosition and not the actual code of it, so I cannot test my solution.

function encrypt(plainText, signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet) {
   var encryptedString = signalCharacter;
   //i is what will hold the results of the encrpytion until it can be appended to encryptedString
   var i;
   // rotate array to signal character position
   var rotateArray = rotateToPosition(signalCharacter, indexCharacter, plainAlphabet, cipherAlphabet);
   for (var count = 0; count < plainText.length; count++)
   {
       var plainLetter = plainText.charAt(count);
       i = cipherAlphabet[plainLetter];
       encryptedString = encryptedString + rotateArray[i];
   }

   return encryptedString;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I also think so. In JS most non-simple vars are by reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.