Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A complex encryption problem 1

Status
Not open for further replies.

Trope

Programmer
May 14, 2001
110
US
Among the simplest (and among the oldest) methods for encryption is the Caesar cipher:

if a letter in the plaintext is the Nth letter in the alphabet,replace it by the (N + K)th letter in the alphabet, where K is some fixed integer (Caesar used K = 3). For example, the table below shows how a message is encrypted using this method with K = 1:

Plaintext: ATTACK AT DAWN
Ciphertext:BUUBDLABUAEB X 0

( based on a 27 letter alphabet 1st char = space )

I am trying to code what they call the "Vigenere cipher", and I am sure it has been done a hundred times before in programming, but I want to do it myself.

It works similar to Caesar's method, but like this:

a small repeated key is used to determine the value of K for each letter. At each step, the key letter index is added to the plaintext letter index to determine the ciphertext letter index. Our sample plaintext,with the key ABC, is encrypted as follows:

Key:ABCABCABCABCAB
Plaintext:ATTACK AT DAWN
Ciphertext:BVWBENACWAFDX P

For example, the last letter of the ciphertext is P, the 16th letter of the alphabet, because the corresponding plaintext letter is N (the 14th letter),and the corresponding key letter is B (the 2nd letter).

Simple enough for our human brains, but JAVASCRIPT... yikes.

Here is what I have come up with, and for some reason it is not working - and I have no clue as to why.

Can anyone help??

<script type=&quot;text/javascript&quot;>
function convert(to, theVal){
if(to.upperCase() == 'char'){
return alphabet.charAt(theVal);
} else {
return alphabet.indexOf(theVal);
}
}

var str = &quot;JOHN&quot;;
var key = &quot;ABC&quot;;
var encryptedChars = new Array();
var alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;
var currKey = 0;

for(var i=0; i<key.length; i++){
keyChar = convert('Number', key.charAt(i));
}

for (var x=0; x<str.length; x++){
encryptedChars[x] = convert('Number', str.charAt(x) + keyChar[currentKey]);
if(currentKey<=keyChar.length){
currKey++;
} else {
currKey = 0;
}
}

alert(str + &quot; encrypted with key: &quot; + key + &quot; is: &quot; + encryptedChars.toString() );
</script>
 
Trope,

There are many errors in your source... nothing major, just simple things like defining a variable called &quot;currKey&quot;, but referring to it as &quot;currentKey&quot;... Using &quot;to.upperCase&quot; instead of &quot;to.toUpperCase&quot;... And your key loop seems to always work on the last character in the key before moving on to create the cipher...

Anyway - here's my take on your code, which seems to do the job (and you know I took my time over it, as I've even commented it ;o)


Code:
<script type=&quot;text/javascript&quot;>
var origStr = &quot;JOHN&quot;;
var encStr = &quot;&quot;;
var key = &quot;ABC&quot;;
var alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;

for (var x=0,i=0; x<origStr.length; x++)
{
	// get the number matching the current letter in original string
	var tempOrigNum = alphabet.indexOf(origStr.charAt(x).toUpperCase()) + 1;		// +1 makes number 1-26, instead of 0-25...

	// get the number matching the current letter in the key
	var keyNum = alphabet.indexOf(key.charAt(i)) + 1;

	// find new number, and make sure it fits within the letters of the alphabet (i.e. between 0 and 25)
	var newNum = tempOrigNum + keyNum;
	while (newNum > 26) newNum-=26;

	// build up the encrypted string
	encStr += alphabet.charAt(newNum-1);

	// loop around the key
	i++;
	if (i == key.length) i = 0;
}

alert('Start string: ' + origStr + '\nKey: ' + key + '\nEncrypted string: ' + encStr);
</script>

Hope this helps!

Dan
 
In my experience the trouble with Javascript is performance. I wrote my own algorythm and it worked fine but was no good for encrypting long messages...

Error: &quot;The script on this page has caused Internet Explorer to run slowly. Do you wish to exit?&quot;

If I left it running, it would eventually complete the task :/

Think a lot of effort has to be put into streamlining the RegExp :(

----------
I'm willing to trade custom scripts for... [see profile]
 
stormbind - I ran Dan's code on a 2500 character string and saw the result instantly. What kind of string lengths were you using with your code?

If you wanted to post your code, it might make a fun optimisation project for the weekend *grin*

Jeff
 
Dan, Your code worked terrific, and after studying it, I have seen where I went wrong. I got my original script to work finally - errors all over the place!! If I am not mistaken, I was basically on the same track as you ( I am a newbie js programmer ).

I ran your code on a text file approximately 4000 chars long, and it seemed to work just fine.

storm - i also would be interested to see what string you were using, as I too would like to 'optimize' it.

I'll post my answer to the question below in case anyone wants to have a look...

Thanks again!
Giovanni

Suppose that a Vigenere cipher with a two-character key is used to encrypt a relatively long message. Write a program to infer the key, based on the assumption that the frequency of occurrence of each character in odd positions should be roughly equal to the frequency of occurrence of each character in the even positions.
 
BTW I am not coming up with this stuff off the top of my head, I am reading an Ebook Called &quot;Mathematic Algorithms&quot; which you can have a look at:

- Mathematics - Algorithms.pdf

Is it me, or do you have to be Albert Einstein to understand some of these chapters??? Have a look at the chapter on file encryption - I have been studying this &quot;tree&quot; that they speak of, and studying, AND STUDYING, however, it just has not clicked in. When it does, I'll be back...
 
Here's a couple functions I made for encryption you might try:
__________________________________________________________________________________________________________________________________
<script>
String.prototype.encrypt = function(){
var chars=&quot;ABCGHIJDEFQRvwxSTU!V@W#X$Y%Z^c&(*d_e:fg)hi01234qrst5,678K[LM]N>OP9< '{\n\t\r};.-+=/\\abjklm|nopuy?zABCGHIJDEF&quot;;
var output=&quot;&quot;,theKey=arguments[0];
for(var i=0;i<this.length;i++){
output+=chars.indexOf(this.charAt(i))>-1 ? chars.charAt(chars.indexOf(this.charAt(i))+(theKey.charAt(i%theKey.length)-0)) : this.charAt(i);
}
return output;
}

String.prototype.unencrypt = function(){
var chars=&quot;ABCGHIJDEFQRvwxSTU!V@W#X$Y%Z^c&(*d_e:fg)hi01234qrst5,678K[LM]N>OP9< '{\n\t\r};.-+=/\\abjklm|nopuy?zABCGHIJDEF&quot;;
var output=&quot;&quot;,theKey=arguments[0];
for(var i=0;i<this.length;i++){
output+=chars.lastIndexOf(this.charAt(i))>-1 ? chars.charAt(chars.lastIndexOf(this.charAt(i))-(theKey.charAt(i%theKey.length)-0)) : this.charAt(i);
}
return output;
}

var str=&quot;This will be encrypted&quot;
var key=&quot;49872349&quot;
str=str.encrypt(key);
alert(str);
str=str.unencrypt(key);
alert(str);

</script>

Adam
while(ignorance==true){perpetuate(violence,fear,hatred);life--};
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top