Mostrando las entradas con la etiqueta Encrypt. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Encrypt. Mostrar todas las entradas

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();

})();

domingo, marzo 26, 2006

Clase de PHP para encriptar y desencriptar cualquier cadena de texto

Hola.

Bueno quiero primero que todo dar las gracias a Kelvin por haberme facilitado su método de encriptación para implementarlo de VB en PHP, uff un tedioso pero emociante trabajo.

Quiero explicar como funciona la clase y que métodos deben invocar.

Archivo base donde esta el código de encriptación EnDecryptText.php

Antes de empezar se debe llamar a la clase desde la ruta donde se encuentre, para ello debes definirla de la siguiente forma:

require_once("EnDecryptText.php"); // Abre la instancia EnDecryptText.php.
$EnDecryptText = new EnDecryptText(); // Crea una nueva instancia de EnDecryptText.php.


Una vez hecho lo anterior, es cuestión de utilizar los dos métodos de la clase, los cuales son los siguientes:

Encrypt_Text y Decrypt_Text

Ahora bien como se invocan, veamos un ejemplo utilizando un ciclo for y con un dato venido desde un formulario html.

for ($i = 1; $i <= 12; $i++)
{
$sTemp = $EnDecryptText->Encrypt_Text($HTTP_POST_VARS["Chain"]);
echo $sTemp;
// Puedes también usarlo así $sTemp = $EnDecryptText->Encrypt_Text($Chain);
$rText = $EnDecryptText->Decrypt_Text($sTemp);
echo $rText;
}

El símbolo -> denota el apuntador de la clase, el cuál en los dos casos apuntan a las funciones de la clase Decrypt_Text y Encrypt_Text.

Bueno aquí un método más cotidiano programado en VB y PHP, un saludo.

 1: '* Private Variable
 2:  Private UserKeyAscii()  As String
 3:  Private TextAscii()     As String
 4: 
 5: Public Function Encrypt(ByVal String1 As String) As String
 6:  Dim k   As Long, Temp As Long, L As Long
 7:  Dim Rtn As String, iM As Integer
 8: 
 9:  '* Función que Encripta.
10:  EnCryIni String1
11:  iM = 0
12:  For k = 1 To Len(String1)
13:   L = IIf(L >= Len(String1), 1, L + 1)
14:   iM = iM + 1
15:   If (iM > Len(UserKey)) Then iM = 1
16:   Temp = CLng(TextAscii(L)) + CLng(UserKeyAscii(iM))
17:   If (k > Len(String1)) Then Exit For
18:   If (Temp > 255) Then Temp = Temp - 255
19:   Rtn = Rtn + Chr$(Temp)
20:  Next k
21:  Encrypt = Rtn
22: End Function
23: 
24: Public Function Decrypt(ByVal String1 As String) As String
25:  Dim k   As Long, L    As Long, Temp As Long
26:  Dim Rtn As String, iM As Integer
27: 
28:  '* Función que quita la Encriptación.
29:  EnCryIni String1
30:  iM = 0
31:  For k = 1 To Len(String1)
32:   L = IIf(L >= Len(String1), 1, L + 1)
33:   iM = iM + 1
34:   If (iM > Len(UserKey)) Then iM = 1
35:   Temp = Abs(CLng(UserKeyAscii(iM)) - CLng(TextAscii(L)))
36:   If (Temp < 0) Then Temp = Temp + 255
37:   Rtn = Rtn + Chr$(Temp)
38:  Next k
39:  Decrypt = Rtn
40: End Function
41: 
42: Private Sub EnCryIni(ByVal Text As String)
43:  Dim N As Long, k As Long
44: 
45:  '* Procedimiento Inicial de la Encriptación.
46:  N = Len(UserKey)
47:  If Not (N = 0) Then
48:   ReDim UserKeyAscii(1 To N)
49:  Else
50:   Exit Sub
51:  End If
52:  For k = 1 To N
53:   UserKeyAscii(k) = Asc(Mid$(UserKey, k, 1))
54:  Next k
55:  ReDim TextAscii(Len(Text)) As String
56:  For k = 1 To Len(Text)
57:   TextAscii(k) = Asc(Mid$(Text, k, 1))
58:  Next k
59: End Sub


1:  class encrypt_vb
2:  {var $UserKeyAscii;
3:   var $TextAscii;
4:   var $UserKey;
5: 
6: 
7:   function encrypt_vb()
8:   {$this->UserKeyAscii = array();
9:    $this->TextAscii    = array();
10:    $this->UserKey      = '';
11:   }
12: 
13:   //------------------------------------------------------------------------------------
14:   // Encripta una cadena de texto.
15:   //------------------------------------------------------------------------------------
16:   // Parámetros
17:   //------------------------------------------------------------------------------------
18:   // $String1: Cadena a encriptar.
19:   //------------------------------------------------------------------------------------
20:   function Encrypt($String1)
21:   {// Función que Encripta.
22:    if ($this->EnCryIni($String1) == false) return '';
23:    $iM = 0;
24:    $L  = 0;
25:    for ($k = 1; $k <= strlen($String1); $k++)
26:    {if ($L >= strlen($String1)) $L = 1;
27:     else $L++;
28:     $iM++;
29:     if ($iM > strlen($this->UserKey)) $iM = 1;
30:     $Temp = $this->TextAscii[$L] + $this->UserKeyAscii[$iM];
 31:     if ($k > strlen($String1)) break;
32:     if ($Temp > 255) $Temp -= 255;
33:     $Rtn .= chr($Temp);
34:    }
35:    return $Rtn;
36:   }
37: 
38:   //------------------------------------------------------------------------------------
39:   // Desencripta una cadena de texto.
40:   //------------------------------------------------------------------------------------
41:   // Parámetros
42:   //------------------------------------------------------------------------------------
43:   // $String1: Cadena a desencriptar.
44:   //------------------------------------------------------------------------------------
45:   function Decrypt($String1)
46:   {// Función que quita la Encriptación.
47:    if ($this->EnCryIni($String1) == false) return '';
48:    $iM = 0;
49:    $L  = 0;
50:    for ($k = 1; $k <= strlen($String1); $k++)
51:    {if ($L >= strlen($String1)) $L = 1;
52:     else $L++;
53:     $iM++;
54:     if ($iM > strlen($this->UserKey)) $iM = 1;
55:     $Temp = abs($this->UserKeyAscii[$iM] - $this->TextAscii[$L]);
56:     if ($Temp < 0) $Temp += 255;
57:     $Rtn .= chr($Temp);
58:    }
59:    return $Rtn;
60:   }
61: 
62:   //------------------------------------------------------------------------------------
63:   // Función iniciadora de la encriptación.
64:   //------------------------------------------------------------------------------------
65:   // Parámetros
66:   //------------------------------------------------------------------------------------
67:   // $Text: Cadena.
68:   //------------------------------------------------------------------------------------
69:   function EnCryIni($Text)
70:   {// Procedimiento Inicial de la Encriptación.
71:    $N = strlen($this->UserKey);
72:    if ($N == 0) return false;
73:    for ($k = 1; $k <= $N; $k++)
74:    {$tmp = ord($this->Mid($this->UserKey, $k, 1));
75:     $this->UserKeyAscii[$k] = $tmp;
76:    }
77:    for ($k = 1; $k <= strlen($Text); $k++)
78:    {$tmp = ord($this->Mid($Text, $k, 1));
79:     $this->TextAscii[$k] = $tmp;
80:    }
81:    return true;
82:   }
83: 
84:   //------------------------------------------------------------------------------------
85:   // Token principal de la cadena.
86:   //------------------------------------------------------------------------------------
87:   // Parámetros
88:   //------------------------------------------------------------------------------------
89:   // $Text: Cadena que permite encriptar otra cadena sumando sus carácteres.
90:   //------------------------------------------------------------------------------------
91:   function KeyToken($Text)
92:   {$this->UserKey = $Text;}
93: 
94:   //------------------------------------------------------------------------------------
95:   // Devuelve un número especificado de caracteres de una cadena.
96:   //------------------------------------------------------------------------------------
97:   // Parámetros
98:   //------------------------------------------------------------------------------------
99:   // $tmp:    Cadena.
100:   // $start:  Posición inicial en la cadena.
101:   // $length: Cantidad de carácteres de izquierda a derecha.
102:   //------------------------------------------------------------------------------------
103:   function Mid($tmp, $start, $length = '')
104:   {$start -= 1;
105:    if (is_string($length) == true) $length = strlen($tmp);
106:    $str = substr($tmp, $start, $length);
107:    return $str;
108:   }
109:  }