<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
<SCRIPT language=JavaScript>
// encrypt/decrypt using a monoalphabetic cipher
function do_encrypt()
{
var key = document.cipher.key.value.toLowerCase();
// sanity check
if ( key.length != 26 )
{
window.alert("Key length is not 26 letters");
return;
}
// get the message to encrypt
var plaintext = document.cipher.plain.value.toLowerCase();
var ciphertext = "";
// encrypt it
for( var i=0; i<plaintext.length; i++ )
{
// get this character as ascii
var curchar = plaintext.charAt(i);
// is it a letter?
if ( curchar >='a' && curchar <= 'z' )
{
// yes, encrypt
// convert 'a'->0, 'b'->1, ... 'z'->25
var charpos = curchar.charCodeAt(0)-97;
// encrypt it
ciphertext += key.charAt(charpos);
}
else
{
// not a letter, leave it alone
ciphertext += curchar;
}
} // for i
document.cipher.enc.value = ciphertext;
}
function do_decrypt()
{
var key = document.cipher.key.value.toLowerCase();
// sanity check
if ( key.length != 26 )
{
window.alert("Key length is not 26 letters");
return;
}
// get the message to encrypt
var ciphertext = document.cipher.enc.value.toLowerCase();
var plaintext = "";
// encrypt it
for( var i=0; i<ciphertext.length; i++ )
{
// get this character as ascii
var curchar = ciphertext.charAt(i);
// is it a letter?
if ( curchar >='a' && curchar <= 'z' )
{
// yes, decrypt
// decrypt this letter
var charpos = key.indexOf( curchar );
// encrypt it
plaintext += String.fromCharCode( charpos+97 );
}
else
{
// not a letter, leave it alone
plaintext += curchar;
}
} // for i
document.cipher.plain.value = plaintext;
}
// generate a random key
function gen_key()
{
var key = new Array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z' );
var i,j;
for( i=0; i<25; i++ )
{
// swap this character with a random character
// generate a random position in the array
j = Math.floor( Math.random()*26 );
// do the swap
var t = key[i];
key[i] = key[j];
key[j] = t;
}
// give it to the user
document.cipher.key.value = key.join('');
}
</SCRIPT>
</HEAD>
<BODY>This page allows you to encrypt/decrypt using a monoalphabetic cipher.
Start by creating a key that maps each letter of the alphabet to a (possibly the
same) letter of the alphabet. A sample key might be:
<HR>
<P>
<FORM name=cipher>Key information:<BR><!-- input type="button" value="Generate Random Key" onClick="gen_key()" -->
<TABLE>
<TBODY>
<TR>
<TD>Key:</TD>
<TD><INPUT value=ISYVKJRUXEDZQMCTPLOFNBWGAH readOnly size=50
name=key></TD></TR>
<TR>
<TD>Plaintext:</TD>
<TD><INPUT size=50 name=plain></TD></TR>
<TR>
<TD>Ciphertext:</TD>
<TD><INPUT size=50 name=enc></TD></TR></TBODY></TABLE><INPUT onclick=do_encrypt() value=Encrypt type=button>
<INPUT onclick=do_decrypt() value=Decrypt type=button> </FORM><I></I> </P></BODY></HTML>