sábado, mayo 09, 2009

Encrypt/Decrypt String with Javascript


Encrypt/Decrypt string using Javascript, based in the PHP class and VB Code.

Copyrigth HACKPRO TM (C) 2008-2009


How to use:

$Security.Encrypt_Text(string, [utf8]);
$Security.Decrypt_Text(string, [utf8]);


/**
*********************************************************  
*    Reservados todos los derechos HACKPRO TM © 2005    *
*-------------------------------------------------------*
* Siéntase libre para usar esta clase en sus páginas,   *
* con tal de que TODOS los créditos permanecen intactos.*
* Sólo ladrones deshonrosos transmite el código que los *
* programadores REALES escriben con difícultad y libre- *
* mente lo comparten quitando los comentarios y diciendo*
* que ellos escribieron el código.                      *
*-------------------------------------------------------*
* Encrypts and Decrypts a chain.                        *
*-------------------------------------------------------*
*-------------------------------------------------------*
* Original in VB for:    Kelvin C. Perez.               *
* E-Mail:                kelvin_perez@msn.com           *
* WebSite:               http://home.coqui.net/punisher *
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++*
* Programmed in PHP for: Heriberto Mantilla Santamaría. *
* E-Mail:                heri_05-hms@mixmail.com        *
* WebSite:               www.geocities.com/hackprotm/   *
*-------------------------------------------------------*
* IMPORTANT NOTE                                        *
*-------------------------------------------------------*
* Feel free to use this class in your pages, provided   *
* ALL credits remain intact. Only dishonorable thieves  *
* download code that REAL programmers work hard to write*
* and freely share with their programming peers, then   *
* remove the comments and claim that they wrote the     *
* code.                                                 *
*-------------------------------------------------------*
*  @author Heriberto Mantilla Santamaría                *
*  @version 1.1                                         *
*********************************************************
*         All Rights Reserved HACKPRO TM © 2005         *
*********************************************************
*/

/**
* Portion of this code is the php.js
* ----------------------------------------------------------------------------------- 
* More info at: http://phpjs.org
* 
* This is version: 2.47
* php.js is copyright 2009 Kevin van Zonneveld.
* 
* Portions copyright Brett Zamir (http://brettz9.blogspot.com), Kevin van
* Zonneveld (http://kevin.vanzonneveld.net), Onno Marsman, Michael White
* (http://getsprink.com), Waldo Malqui Silva, Paulo Ricardo F. Santos, Jack,
* Philip Peterson, Jonas Raoni Soares Silva (http://www.jsfromhell.com), Ates
* Goral (http://magnetiq.com), Legaev Andrey, Martijn Wieringa, Nate,
* Philippe Baumann, Enrique Gonzalez, Webtoolkit.info
* (http://www.webtoolkit.info/), Ash Searle (http://hexmen.com/blog/), travc,
* Jani Hartikainen, Carlos R. L. Rodrigues (http://www.jsfromhell.com), d3x,
* Johnny Mast (http://www.phpvrouwen.nl), marrtins, Alex, Erkekjetter, Andrea
* Giammarchi (http://webreflection.blogspot.com), GeekFG
* (http://geekfg.blogspot.com), Mirek Slugen, Breaking Par Consulting Inc
* (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
* Ole Vrijenhoek, Josh Fraser
* (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
* Steven Levithan (http://blog.stevenlevithan.com), Public Domain
* (http://www.json.org/json2.js), Marc Palau, mdsjack
* (http://www.mdsjack.bo.it), David, Arpad Ray (mailto:arpad@php.net),
* Pellentesque Malesuada, Thunder.m, Aman Gupta, Tyler Akins
* (http://rumkin.com), Alfonso Jimenez (http://www.alfonsojimenez.com), Karol
* Kowalski, AJ, Caio Ariede (http://caioariede.com), Sakimori, gorthaur,
* Steve Hilder, john (http://www.jd-tech.net), David James, class_exists,
* noname, Steve Clay, T. Wild, Hyam Singer
* (http://www.impact-computing.com/), kenneth, Subhasis Deb, Pyerre, Felix
* Geisendoerfer (http://www.debuggable.com/felix), djmix, Jon Hohle, Douglas
* Crockford (http://javascript.crockford.com), mktime, sankai, Sanjoy Roy,
* 0m3r, Marco, Thiago Mata (http://thiagomata.blog.com), madipta, Gilbert,
* ger, Bryan Elliott, David Randall, Ozh, T0bsn, Tim Wiel, Peter-Paul Koch
* (http://www.quirksmode.org/js/beat.html), Bayron Guevara, MeEtc
* (http://yass.meetcweb.com), Brad Touesnard, XoraX (http://www.xorax.info),
* echo is bad, J A R, duncan, Paul, Linuxworld, Marc Jansen, Der Simon
* (http://innerdom.sourceforge.net/), Lincoln Ramsay, LH, Francesco, Slawomir
* Kaniecki, marc andreu, Eric Nagel, Bobby Drake, rezna, Mick@el, Pierre-Luc
* Paour, Martin Pool, Kirk Strobeck, Pul, Luke Godfrey, Christian Doebler,
* YUI Library:
* http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
* http://hacks.bluesmoon.info/strftime/strftime.js, penutbutterjelly, Gabriel
* Paderni, Blues (http://tech.bluesmoon.info/), Anton Ongson, Simon Willison
* (http://simonwillison.net), Kristof Coomans (SCK-CEN Belgian Nucleair
* Research Centre), Saulo Vallory, hitwork, Norman "zEh" Fuchs, sowberry,
* Yves Sucaet, Nick Callen, ejsanders, johnrembo, dptr1988, Pedro Tainha
* (http://www.pedrotainha.com), T.Wild, uestla, Valentina De Rosa,
* strcasecmp, strcmp, metjay, DxGx, Alexander Ermolaev
* (http://snippets.dzone.com/user/AlexanderErmolaev), ChaosNo1, Andreas,
* Garagoth, Manish, Cord, Matt Bradley, Robin, FremyCompany, Tim de Koning,
* taith, Victor, stensi, Arno, Nathan, nobbler, Mateusz "loonquawl" Zalega,
* ReverseSyntax, Jalal Berrami, Francois, Scott Cariss, Tod Gentille, baris
* ozdil, booeyOH, Cagri Ekin, Luke Smith (http://lucassmith.name), Ben Bryan,
* Leslie Hoare, Andrej Pavlovic, Dino, mk.keck, Rival, Diogo Resende, Yannoo,
* gabriel paderni, FGFEmperor, jakes, Atli Þór, Howard Yeend, Allan Jensen
* (http://www.winternet.no), Benjamin Lupton
* 
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
* 
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* 
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

(function() {
if (typeof(Security) == "undefined") {
var Security = function() {
if (window == this || !this.init) {
return new Security();
} else {
return this.init();
}
};
}

var nEncKey, cText, nCharSize, cSourceText;

Security.prototype = {
init : function() {
},

Encrypt_Text : function(cText, utf8) {


if (utf8) {
var eText = this.utf8_encode(cText);
} else {
var eText = cText;
}

var nCounter = 0;
// Get a random Number between 1 and 100. This will be the multiplier
// for the Ascii value of the characters.
this.nEncKey = this.intval((100 * this.Rnd()) + 1);

// Loop until we get a random value betwee 5 and 7. This will be
// the lenght (with leading zeros) of the value of the Characters.
this.nCharSize = 0;
var nUpperBound = 10;
var nLowerBound = 5;
this.nCharSize = this.intval((nUpperBound - nLowerBound + 1) * this.Rnd() + nLowerBound);
// Encrypt the Size of the characters and convert it to String.
// This size has to be standard so we always get the right character.
var cCharSize = this.fEncryptedKeySize(this.nCharSize);
// Convert the KeyNumber to String with leading zeros.
var cEncKey = this.NumToString(this.nEncKey, this.nCharSize);
// Get the text to encrypt and it's size.
var cEncryptedText = '';
var nTextLenght = this.strlen(eText);

// Loop thru the text one character at the time.
for (nCounter = 1; nCounter <= nTextLenght; nCounter++) {
// Get the Next Character.
var cChar = this.Mid(eText, nCounter, 1);
// Get Ascii Value of the character multplied by the Key Number.
var nChar = this.ord(cChar) * this.nEncKey;
// Get the String version of the Ascii Code with leading zeros.
// using the Random generated Key Lenght.
var cChar2 = this.NumToString(nChar, this.nCharSize);
// Add the Newly generated character to the encrypted text variable.
cEncryptedText += cChar2;
}

// Separate the text in two to insert the enc
// key in the middle of the string.
var nLeft = this.intval(this.strlen(cEncryptedText) / 2);
var cLeft = this.strleft(cEncryptedText, nLeft);
var nRight = this.strlen(cEncryptedText) - nLeft;
var cRight = this.strright(cEncryptedText, nRight);
// Add a Dummy string at the end to fool people.
var cDummy = this.CreateDummy();
// Add all the strings together to get the final result.
this.cSourceText = cEncryptedText;
this.InsertInTheMiddle(this.cSourceText, cEncKey);
this.InsertInTheMiddle(this.cSourceText, cCharSize);
cEncryptedText = this.cSourceText;
cEncryptedText = this.CreateDummy() + cEncryptedText + this.CreateDummy();

return cEncryptedText;

},

Decrypt_Text : function(cText, utf8) {

var cTempText = cText;
var cDecryptedText = '';
var len = this.strlen(cTempText);
var nChar2 = 0;
var nChar = 0;

this.cText = '';

// Replace alpha characters for zeros.
for (var nCounter = 1; nCounter <= len; nCounter++) {
cChar = this.Mid(cTempText, nCounter, 1);
if (this.is_numeric(cChar) == true) {
this.cText += cChar;
} else {
this.cText += '0';
}

}

// Get the size of the key.
this.cText = this.strleft(this.cText, this.strlen(this.cText) - 4);
this.cText = this.strright(this.cText, this.strlen(this.cText) - 4);
this.nCharSize = 0;
this.Extract_Char_Size(this.cText, this.nCharSize);
this.Extract_Enc_Key(this.cText, this.nCharSize, this.nEncKey);

// Decrypt the Size of the encrypted characters.
nTextLenght = this.strlen(this.cText);
// Loop thru text in increments of the Key Size.
var nCounter = 1;

do { // Get a Character the size of the key.
cChar = this.Mid(this.cText, nCounter, this.nCharSize);
// Get the value of the character.
nChar = this.Val(cChar);
// Divide the value by the Key to get the real value of the
// character.
if (this.nEncKey > 0) {
nChar2 = parseInt(nChar / this.nEncKey);
}

// Convert the value to the character.
cChar2 = this.chr(nChar2);
cDecryptedText += cChar2;
nCounter += parseInt(this.nCharSize);
} while (nCounter <= nTextLenght);

// Clear any unwanted spaces and show the decrypted text.
cDecryptedText = this.trim(cDecryptedText);

if (utf8) {
return this.utf8_decode(cDecryptedText);
} else {
return cDecryptedText;
}

},

Extract_Char_Size : function(cText, nCharSize) {

// Get the half left side of the text.
var nLeft = this.intval(this.strlen(cText) / 2);
var cLeft = this.strleft(cText, nLeft);
// Get the half right side of the text.
var nRight = this.strlen(cText) - nLeft;
var cRight = this.strright(cText, nRight);

// Get the key from the text.
var nKeyEnc = this.Val(this.strright(cLeft, 2));
var nKeySize = this.Val(this.strleft(cRight, 2));

if (nKeyEnc >= 5) {
this.nCharSize = parseInt(nKeySize) + parseInt(nKeyEnc);   
} else {
this.nCharSize = parseInt(nKeySize) - parseInt(nKeyEnc); 
}

this.cText = this.strleft(cLeft, this.strlen(cLeft) - 2) +
this.strright(cRight, this.strlen(cRight) - 2);

},

Extract_Enc_Key : function(cText, nCharSize, nEncKey) {

var cEncKey = '';

// Get the real size of the text (without the previously
// stored character size).
var nLenght = this.strlen(cText) - nCharSize;
// Get the half left and half right sides of the text.
var nLeft = this.intval(nLenght / 2);
var cLeft = this.strleft(cText, nLeft);
var nRight = nLenght - nLeft;
var cRight = this.strright(cText, nRight);
// Get the key from the text.
cEncKey = this.Mid(cText, nLeft + 1, nCharSize);
// Get the numeric value of the key.
this.nEncKey = this.Val(this.trim(cEncKey));
// Get the real text to decrypt (left side + right side).
this.cText = cLeft + '' + cRight;
},

fEncryptedKeySize : function(nKeySize) {

var nLowerBound = 0;
var nKeyEnc = this.intval((nKeySize - nLowerBound + 1) * this.Rnd() + nLowerBound);

if (nKeyEnc >= 5) {
nKeySize = parseInt(nKeySize) - parseInt(nKeyEnc); 
} else {
nKeySize = parseInt(nKeySize) + parseInt(nKeyEnc); 
}

return this.NumToString(nKeyEnc, 2) + this.NumToString(nKeySize, 2);

},

NumToString : function(nNumber, nZeros) {

// Check that the zeros to fill are not smaller than the actual size.
var cNumber = this.trim(nNumber);
var nLenght = this.strlen(cNumber);

if (nZeros < nLenght) {
nZeros = 0;
}

var nUpperBound = 122;
var nLowerBound = 65;
var nCounter = 0;

for (nCounter = 1; nCounter <= (nZeros - nLenght); nCounter++) { // Add a zero in front of the string until we reach the desired size.
var lCreated = false;

do {
nNumber = this.intval((nUpperBound - nLowerBound + 1) * this.Rnd() + nLowerBound);
if ((nNumber > 90) && (nNumber < 97)) {
lCreated = false; 
} else {
lCreated = true; 
}

} while (lCreated == false);

cChar = this.chr(nNumber);
cNumber = cChar + cNumber;
}

// Return the resulting string.
return cNumber;

},

InsertInTheMiddle : function(cSourceText, cTextToInsert) {

// Get the half left and half right sides of the text.
var nLeft = this.intval(this.strlen(cSourceText) / 2);
var cLeft = this.strleft(cSourceText, nLeft);
var nRight = this.strlen(cSourceText) - nLeft;
var cRight = this.strright(cSourceText, nRight);
// Insert cTextToString in the middle of cSourceText.
this.cSourceText = cLeft + cTextToInsert + cRight;

},

CreateDummy : function() {

var nUpperBound = 122;
var nLowerBound = 48;
var nCounter = 0;
var cDummy = '';

for (nCounter = 1; nCounter <= 4; nCounter++) {
var lCreated = false;

do {
nDummy = this.intval((nUpperBound - nLowerBound + 1) * this.Rnd() + nLowerBound)
if (((nDummy > 57) && (nDummy < 65)) || ((nDummy > 90) && (nDummy < 97))) {
lCreated = false; 
} else {
lCreated = true; 
}

} while (lCreated == false);

cDummy += this.chr(nDummy);

}

return cDummy;

},

is_numeric : function(mixed_var) {
// More info at: http://phpjs.org
// This is version: 2.47 php.js is copyright 2009 Kevin van Zonneveld.

if (mixed_var === '') {
return false;
}

return !isNaN(mixed_var * 1);

},

strlen : function(string) {

var str = string + '';

return str.length;

},

strright : function(tmp, nRight) {

var len = this.strlen(tmp);

if (nRight == 0){
str = ''; 
} else if (nRight < len) {
str = this.Mid(tmp, len - nRight + 1, len); 
}

return str;

},

strleft : function(tmp, nLeft) {

var len = this.strlen(tmp);

if (nLeft == 0){
str = ''; 
} else if (nLeft < len) {
str = this.Mid(tmp, 1, nLeft); 
}

return str;

},

Mid : function(tmp, start, length) {

str = this.substr(tmp, start - 1, length);
return str;

},

substr : function(f_string, f_start, f_length) {

var str = f_string + '';

return str.substr(f_start, f_length);

},

trim : function(f_string) {

var str = f_string + '';

while (str.charAt(0) == (" ")) {
str = str.substring(1);
}

while (str.charAt(str.length-1) == " ") {
str = str.substring(0,str.length-1);
}

return str;

},

Rnd : function() {

do {
var tmp = Math.abs( Math.tan( Math.random() ) );
} while ((tmp > 1) || (tmp < 0));

tmp = this.Mid(tmp, 1, 8);

return tmp;

},

Val : function(tmp) {

var length = this.strlen(tmp);
var tmp2 = 0;

for (i = 1; i <= length; i++) {
var tmp1 = this.substr(tmp, i - 1, 1);
if (this.is_numeric(tmp1) == true) {
tmp2 += tmp1;
}

}

return this.intval(tmp2);

},

intval : function(mixed_var, base) {
// More info at: http://phpjs.org
// This is version: 2.47 php.js is copyright 2009 Kevin van Zonneveld.

var tmp;
var type = typeof(mixed_var);
if (type == 'boolean') {
if (mixed_var == true) {
return 1;
} else {
return 0;
}

} else if (type == 'string') {
tmp = parseInt(mixed_var * 1);
if (isNaN(tmp) || !isFinite(tmp)) {
return 0;
} else {
return tmp.toString(base || 10);
}

} else if (type == 'number' && isFinite(mixed_var)) {
return Math.floor(mixed_var);
} else {
return 0;
}

},

chr : function(ascii) {

return String.fromCharCode(ascii);

},

ord : function(string) {

string += '';
return string.charCodeAt(0);

},

utf8_encode : function(string) {
// More info at: http://phpjs.org
// This is version: 2.47 php.js is copyright 2009 Kevin van Zonneveld.

string = (string + '').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = "";
var start, end;
var stringl = 0;
start = end = 0;
stringl = string.length;

for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;

if (c1 < 128) {
end++;
} else if ((c1 > 127) && (c1 < 2048)) {
enc = String.fromCharCode((c1 >> 6) | 192)
+ String.fromCharCode((c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224)
+ String.fromCharCode(((c1 >> 6) & 63) | 128)
+ String.fromCharCode((c1 & 63) | 128);
}

if (enc != null) {
if (end > start) {
utftext += string.substring(start, end);
}

utftext += enc;
start = end = n + 1;
}

}

if (end > start) {
utftext += string.substring(start, string.length);
}

return utftext;

},

utf8_decode : function(str_data) {
// More info at: http://phpjs.org
// This is version: 2.47 php.js is copyright 2009 Kevin van Zonneveld.

var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
str_data += '';

while (i < str_data.length) {
c1 = str_data.charCodeAt(i);
if (c1 < 128) {
tmp_arr[ac++] = String.fromCharCode(c1);
i++;
} else if ((c1 > 191) && (c1 < 224)) {
c2 = str_data.charCodeAt(i + 1);
tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6)
| (c2 & 63));
i += 2;
} else {
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12)
| ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}

}

return tmp_arr.join('');

}

};

window.$Security = Security();

})();

No hay comentarios.: