|
-
Oct 12th, 2006, 10:31 PM
#1
Thread Starter
Frenzied Member
ROT13 (Javascript)
Here is an implementation of ROT13, a kind of weak encryption scheme, in javascript.
Code:
function encodeROT13(){
var frm = document.forms[0];
var strencode;
var strencoderet;
var basenum;
strencode = frm.txtEncode.value;
strencoderet = "";
for(i = 0; i < strencode.length; i++){
if( (strencode.charCodeAt(i) >= 97 && strencode.charCodeAt(i) <= 122 ) ||
(strencode.charCodeAt(i) >= 65 && strencode.charCodeAt(i) <= 90 )) {
basenum = (strencode.charCodeAt(i) > 90)? 97 : 65;
strencoderet += String.fromCharCode( ((strencode.charCodeAt(i) - basenum + 14) % 26 ) + basenum )
} else {
strencoderet += strencode.charAt(i);
}
}
frm.txtEncodeRet.value = strencoderet;
}
function decodeROT13(){
var frm = document.forms[0];
var strdecode;
var strdecoderet;
var basenum;
strdecode = frm.txtDecode.value;
strdecoderet = "";
for(i = 0; i < strdecode.length; i++){
if( (strdecode.charCodeAt(i) >= 97 && strdecode.charCodeAt(i) <= 122 ) ||
(strdecode.charCodeAt(i) >= 65 && strdecode.charCodeAt(i) <= 90 )) {
basenum = (strdecode.charCodeAt(i) > 90)? 97 : 65;
if (((strdecode.charCodeAt(i) - basenum - 13)) % 26 > 0) {
strdecoderet += String.fromCharCode( ((strdecode.charCodeAt(i) - basenum - 14) % 26 ) + basenum )
} else {
strdecoderet += String.fromCharCode( strdecode.charCodeAt(i) + 12 )
}
} else {
strdecoderet += strdecode.charAt(i);
}
}
frm.txtDecodeRet.value = strdecoderet;
}
I believe that it can be further enhanced to be more efficient. Can anyone give me ideas?
-
Oct 13th, 2006, 09:26 AM
#2
Re: ROT13 (Javascript)
I don't use Javascript much, but I notice (in both functions) that you repeatedly use strencode.charCodeAt(i) within your loops.
I would assume that this takes time to execute each time, so a more efficient way would be to store the value to a variable, then use the variable instead or re-calculating, eg:
Code:
var currCharCode;
for(i = 0; i < strencode.length; i++){
currCharCode = strencode.charCodeAt(i);
if( (currCharCode >= 97 && currCharCode <= 122 ) ||
(currCharCode >= 65 && currCharCode <= 90 )) {
basenum = (currCharCode > 90)? 97 : 65;
strencoderet += String.fromCharCode( ((currCharCode - basenum + 14) % 26 ) + basenum )
} else {
strencoderet += strencode.charAt(i);
}
}
-
Oct 13th, 2006, 10:49 PM
#3
Thread Starter
Frenzied Member
Re: ROT13 (Javascript)
Hehehe, this was the the language most handy at the time. 
thanks for the ideas SI.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|