简体   繁体   中英

Simple JavaScript encryption function

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM