[Base64 encoder/decoder]

Iniciado por xmbeat, 13 Julio 2012, 05:55 AM

0 Miembros y 1 Visitante están viendo este tema.

xmbeat

Un pequeno codigo que hice para codificar unas urls que me hacian falta
Código (java) [Seleccionar]

/*
Copyright (c) <2012> <xmbeat::Juan Hebert Chable Covarrubias>

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 THE AUTHORS
OR COPYRIGHT HOLDERS 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.
*/
public class Base64 {
private static String TABLE_64;
private static byte INDEX_TABLE[] = new byte[256];
private char _padChar = '=';
static
{
TABLE_64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (int i = 0; i < 64; i++)
{
INDEX_TABLE[TABLE_64.charAt(i)] = (byte)i;
}
}
public Base64(){}
public Base64(char padChar)
{
_padChar = padChar;
}
public String encode(byte[] data)
{
int finalLen = data.length / 3 * 4;
if (data.length % 3 > 0)finalLen+=4;
StringBuffer string64 = new StringBuffer();
string64.setLength(finalLen);
int leftBits = 0;
int rightBits = 0;
int shift = 2;
int index = 0;
for (int i = 0; i < data.length; i++)
{
int curByte = data[i] & 0xFF;
leftBits = (rightBits | (curByte >> shift));
string64.setCharAt(index++, TABLE_64.charAt(leftBits));
rightBits = (curByte << (6-shift)) & 0x3F;
if (shift == 6 || i == data.length - 1)
{
string64.setCharAt(index++,TABLE_64.charAt(rightBits));
rightBits = 0;
shift = 2;
}
else
shift+=2;
}
for (;index < finalLen; index++)
{
string64.setCharAt(index, _padChar);
}
return string64.toString();
}
public byte[] decode(String data)
{
int realLen  = data.length() - 1;
while(data.charAt(realLen)==_padChar) realLen--;
realLen++;
byte []result =  new byte[realLen*3/4];
int rightBits = 0;
int leftBits = 0;
int shift = 2;
int index = 0;
boolean procesado = false;
for (int i = 0; i < realLen; i++)
{
int curByte = INDEX_TABLE[data.charAt(i)] & 0xFF;
//Incluí todos los caractares a una tabla, para asi ganar un poco de velocidad
//Pero a consecuencia de que si un byte no esta en la tabla lo trata como la letra
//'A', si quieren pongan un condicional para generar una excepcion
rightBits = curByte >> (8-shift);
if (procesado)
{
result[index++]=(byte)(rightBits | leftBits);
}
leftBits = (curByte << shift) & 0xFF;
if (shift == 8)
{
procesado = false;
shift = 2;
}
else
{
procesado = true;
shift += 2;
}
}
return result;
}
public static void main(String[] args)
{
Base64 converter = new Base64();
String strEncode = converter.encode("A la ***** la universidad, yo quiero ser actor porno".getBytes());
System.out.println(strEncode);
System.out.println(new String(converter.decode(strEncode)));
}
}


Debci

Muchísimas gracias por tu aporte, esto nos será de mucha ayuda, sobretodo para comprender el método de conversión aplicado a un algoritmo.


Saludos y bienvenido al foro :P