Base 64 codificar y decodificar código de ejemplo


¿alguien sabe cómo decodificar y codificar una cadena en Base64 usando Base64. Estoy usando el siguiente código, pero no funciona.

String source = "password"; 
byte[] byteArray = source.getBytes("UTF-16"); 
Base64 bs = new Base64(); 
//bs.encodeBytes(byteArray); 
System.out.println( bs.encodeBytes(byteArray)); 
//bs.decode(bs.encodeBytes(byteArray));
System.out.println(bs.decode(bs.encodeBytes(byteArray)));
Author: Braiam, 2011-09-09

9 answers

Primero:

  • Elija una codificación. UTF-8 es generalmente una buena opción; apégate a una codificación que definitivamente será válida en ambos lados. Sería raro usar algo que no sea UTF-8 o UTF-16.

Extremo de transmisión:

  • Codifica la cadena en bytes (por ejemplo, text.getBytes(encodingName))
  • Codifica los bytes a base64 usando la clase Base64
  • Transmitir la base64

Extremo receptor:

  • Recibe la base64
  • Decodificar el base64 a bytes usando la clase Base64
  • Decodifica los bytes en una cadena (por ejemplo, new String(bytes, encodingName))

Así que algo como:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

O con StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
 387
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 18:37:38

Para cualquier otra persona que terminó aquí mientras buscaba información sobre cómo decodificar una cadena codificada con Base64.encodeBytes(), aquí estaba mi solución:

// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());

// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2); 
String val2 = new String(tmp2, "UTF-8"); 

Además, estoy apoyando versiones anteriores de Android, así que estoy usando la biblioteca Base64 de Robert Harder de http://iharder.net/base64

 13
Author: Dunfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-30 16:03:25

Algo como

String source = "password"; 
byte[] byteArray;
try {
    byteArray = source.getBytes("UTF-16");
    System.out.println(new String(Base64.decode(Base64.encode(byteArray,
           Base64.DEFAULT), Base64.DEFAULT)));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 7
Author: DonGru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-04 05:31:05

Si está usando Kotlin {[4] } que use así

Para Codificar

val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)

Para Decodificar

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))
 4
Author: Mohit Suthar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-27 10:25:02

Para Kotlin mb es mejor usar esto:

fun String.decode(): String {
    return Base64.decode(this, Base64.DEFAULT).toString(charset("UTF-8"))
}

fun String.encode(): String {
    return Base64.encodeToString(this.toByteArray(charset("UTF-8")), Base64.DEFAULT)
}

Ejemplo:

Log.d("LOGIN", "TEST")
Log.d("LOGIN", "TEST".encode())
Log.d("LOGIN", "TEST".encode().decode())
 3
Author: brunql,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-23 08:04:46

Basado en las respuestas anteriores estoy usando los siguientes métodos de utilidad en caso de que alguien quiera usarlo.

    /**
 * @param message the message to be encoded
 *
 * @return the enooded from of the message
 */
public static String toBase64(String message) {
    byte[] data;
    try {
        data = message.getBytes("UTF-8");
        String base64Sms = Base64.encodeToString(data, Base64.DEFAULT);
        return base64Sms;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * @param message the encoded message
 *
 * @return the decoded message
 */
public static String fromBase64(String message) {
    byte[] data = Base64.decode(message, Base64.DEFAULT);
    try {
        return new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}
 1
Author: Szabolcs Becze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-01 07:35:39

Para cifrar:

byte[] encrpt= text.getBytes("UTF-8");
String base64 = Base64.encodeToString(encrpt, Base64.DEFAULT);

Para descifrar:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");
 1
Author: Community,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 11:18:13

Para el nivel de API 26 +

String encodedString = Base64.getEncoder().encodeToString(byteArray);

Ref: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte[])

 0
Author: Fung LAM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-06 03:44:40

Para android api byte [] para Base64String codificador

Byte [] data = nuevo byte[]; String Base64encodeString = android.útil.Base64.encodeToString (datos, android.útil.Base64.POR DEFECTO);

 -2
Author: orhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-27 01:36:46