Simple string encryption in .NET and Javascript
It sounds like you want an obfuscation or encoding, not encryption. Base64 encoding should work well here. The result will look nothing like an email address, and the encoding process is fast.
In C#, you can use:
string emailAddress = "[email protected]";
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(emailAddress));
And you can use this JavaScript function to decode it:
function Base64Decode(encoded) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
enc1 = keyStr.indexOf(encoded.charAt(i++));
enc2 = keyStr.indexOf(encoded.charAt(i++));
enc3 = keyStr.indexOf(encoded.charAt(i++));
enc4 = keyStr.indexOf(encoded.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
} while (i < encoded.length);
return output;
}
The C# application encodes the string [email protected]
into YWJjQGV4YW1wbGUuY29t
, and the JavaScript version will decode YWJjQGV4YW1wbGUuY29t
back into [email protected]
.
The System.Security.Cryptography has a bunch of symetric (and asymetric) encrytion algorithms ready to use. (For something super secure use aes)
You should be able to find matching Javascript implementation for most (here are a few aes implementations in JS)
- http://www.movable-type.co.uk/scripts/aes.html
- http://www.hanewin.net/encrypt/aes/aes.htm
Note: If you are planning to use private key based encryption then keep in mind, your web page is going to have the key embedded in it and that means that it all becomes kind of pointless cause anyone with access to the page can do the decryption, at best you would be making the life of the screen scrapers a little bit harder. If making screen scrapers life harder is your goal you could just use an obsfucation algorithm. Any trivial implementation would make very impractical for screen scrapers that do not have a javascript engine:
Eg.
function samObsfucated()
{
return("s" + "a" + "m" + "@" + "s" + "." + "com");
}
Then onload populate your email fields with the output of these functions.
Javascript encryption has a really good use case for software that stores passwords for users ala clipperz
What about a simple XOR Cipher?
These two implementations are fully compatible:
- Simple XOR Encryption (C#)
- JavaScript XOR Encryption