259

I am using the following code, but it's not working.

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)));
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
max
  • 3,047
  • 5
  • 20
  • 17
  • 3
    You must import this `import android.util.Base64;` and then can use `Base64.encodeToString` & `Base64.decode` according to your needs – Zohab Ali Dec 08 '18 at 10:10

14 Answers14

558

First:

  • Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.

Transmitting end:

  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

Receiving end:

  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

So something like:

// 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");

Or with 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);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • can you give me exact code that would be great help. i am using but its not working. 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))); – max Sep 09 '11 at 11:24
  • 9
    @max: "It's not working" is never a good description of what's happening. Will edit my post though. – Jon Skeet Sep 09 '11 at 12:23
  • 3
    Also note that you shouldn't call static methods as if they're instance methods... – Jon Skeet Sep 09 '11 at 12:25
  • 4
    if you put it like that it will work String base64 = Base64.encodeToString(data, Base64.NO_WRAP); – Joy Oct 08 '13 at 14:20
  • You should be careful using this answer. You really should handle the UnsupportedEncodingException. So surround this answer with try-catch. – portfoliobuilder Jan 03 '17 at 18:35
  • 1
    @portfoliobuilder: Absolutely not. `UTF-8` is guaranteed to be a valid encoding in Java: see http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html. Admittedly these days I'd specify `StandardCharsets.UTF_8` instead. I've updated the answer to specify that you should be confident in the presence of the charset, but I'd pretty much *always* use UTF-8. – Jon Skeet Jan 03 '17 at 18:37
  • 1
    When I use Base64.DEFAULT then it says bad base64. So use Base64.URL_SAFE and enjoyee – Android Help May 12 '17 at 07:26
  • 1
    @AndroidHelp: No, use the right version for your context. If you want to put the data into a URL, then sure, use `URL_SAFE`. But if you're *not* putting it in a URL, it's better to use the default one, as that complies with the more common encoding. – Jon Skeet May 12 '17 at 07:41
  • in my case add header not in url Base64.NO_WRAP !) – Fortran Jan 14 '21 at 16:13
29

For Kotlin mb better to use this:

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)
}

Example:

Log.d("LOGIN", "TEST")
Log.d("LOGIN", "TEST".encode())
Log.d("LOGIN", "TEST".encode().decode())
brunql
  • 415
  • 5
  • 5
  • 10
    Naming for these extensions functions is horrible. I would highly recommend using encodeToBase64 or something similar. – Rolf ツ Nov 14 '18 at 10:59
  • They are absolutely not clear and obvious. Tell me: what means "decode" or "encode"? There are thousands of decoding/encoding algorithms... What if you need Base64 and Hex? How would you name the methods then? – Rolf ツ Nov 15 '18 at 11:25
  • Not to mention the different Base64 standards out there. – Rolf ツ Nov 15 '18 at 11:27
  • Clear and obvious for this use case. If i need another algorithm i will never use it as extension method. – brunql Nov 15 '18 at 11:29
  • 2
    Nevertheless I would prefer something like: 'toBase64()' and 'fromBase64()' as a minimum. This way I don't need to read any documentation to know what the method will do. Keep in mind: "code is read more than it is written". – Rolf ツ Nov 15 '18 at 11:30
  • 1
    Yes, if i want to emphasize encoding and algorithm i will name it like toBase64UTF8(), but i don't need it, simple is better. Naming is one of the major problem in development. Please vote down on this answer and we close this dicussion, thanks. – brunql Nov 15 '18 at 11:39
  • 6
    So much fuss for an example :) – Simas Nov 15 '18 at 20:04
20

To anyone else who ended up here while searching for info on how to decode a string encoded with Base64.encodeBytes(), here was my solution:

// 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"); 

Also, I'm supporting older versions of Android so I'm using Robert Harder's Base64 library from http://iharder.net/base64

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Dunfield
  • 785
  • 6
  • 11
12

If you are using Kotlin than use like this

For Encode

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

For Decode

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))
Mohit Suthar
  • 8,725
  • 10
  • 37
  • 67
7

something like

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();
}
Nayan
  • 1,521
  • 2
  • 13
  • 27
DonGru
  • 13,532
  • 8
  • 45
  • 55
6

To encrypt:

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

To decrypt:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
2

'java.util.Base64' class provides functionality to encode and decode the information in Base64 format.

How to get Base64 Encoder?

Encoder encoder = Base64.getEncoder();

How to get Base64 Decoder?

Decoder decoder = Base64.getDecoder();

How to encode the data?

Encoder encoder = Base64.getEncoder();
String originalData = "java";
byte[] encodedBytes = encoder.encode(originalData.getBytes());

How to decode the data?

Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedBytes);
String decodedStr = new String(decodedBytes);

You can get more details at this link.

Hari Krishna
  • 3,658
  • 1
  • 36
  • 57
  • This might result in ClassNotFoundException on certain devices. Imo you should use android.util.Base64 instead (assuming we're in an android context, based on labels). – el_chupacabra Jul 16 '21 at 15:32
2

Above many answers that don't work for me, and some of them are no exception handling in the correct way. here am adding a perfect solution that works amazing for me sure also for you too.

//base64 decode string 
 String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
    ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
    String val = a(s) ;
     Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
    
       public static String a(String str) {
             try {
                 return new String(Base64.decode(str, 0), "UTF-8");
             } catch (UnsupportedEncodingException | IllegalArgumentException unused) {
                 return "This is not a base64 data";
             }
         }
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Waheed Sabir
  • 159
  • 2
  • 4
1

Based on the previous answers I'm using the following utility methods in case anyone would like to use it.

    /**
 * @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;
}
Szabolcs Becze
  • 507
  • 1
  • 5
  • 10
1

For API level 26+

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

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

4b0
  • 21,981
  • 30
  • 95
  • 142
Fung
  • 961
  • 1
  • 8
  • 17
1

Answer from 2021 in Kotlin.

Encode :

val data: String = "Hello"
val dataByteArray: ByteArray = data.toByteArray()
val dataInBase64: String = Base64Utils.encode(dataByteArray)

Decode :

val dataInBase64: String = "..."
val dataByteArray: ByteArray = Base64Utils.decode(dataInBase64)
val data: String = dataByteArray.toString()
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
i30mb1
  • 3,894
  • 3
  • 18
  • 34
0
package net.itempire.virtualapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class BaseActivity extends AppCompatActivity {
EditText editText;
TextView textView;
TextView textView2;
TextView textView3;
TextView textView4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        editText=(EditText)findViewById(R.id.edt);
        textView=(TextView) findViewById(R.id.tv1);
        textView2=(TextView) findViewById(R.id.tv2);
        textView3=(TextView) findViewById(R.id.tv3);
        textView4=(TextView) findViewById(R.id.tv4);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             textView2.setText(Base64.encodeToString(editText.getText().toString().getBytes(),Base64.DEFAULT));
            }
        });

        textView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView4.setText(new String(Base64.decode(textView2.getText().toString(),Base64.DEFAULT)));

            }
        });


    }
}
Asif Ali
  • 27
  • 2
-1

for android API byte[] to Base64String encoder

byte[] data=new byte[];
String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
Android
  • 1,420
  • 4
  • 13
  • 23
orhan
  • 11
  • note, this is outdated, I think since Android API 26. use `Base64.getEncoder().encodeToString(data)` instead – rubo77 Dec 15 '21 at 08:35
-1
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".BaseActivity">
   <EditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/edt"
       android:paddingTop="30dp"
       />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:text="Encode"
        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv2"

        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv3"
        android:text="decode"
        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv4"
        android:textSize="20dp"
        android:padding="20dp"


        />
</LinearLayout>
Asif Ali
  • 27
  • 2