Base64 Java encode and decode a string
You can use following approach:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
Hope this answers your doubt.
Decode Base64 data in Java
As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter
has static methods that make this easy. See parseBase64Binary()
and printBase64Binary()
.
UPDATE: JAXB is no longer shipped with Java (since Java 11). If JAXB is required for your project, you will need to configure the relevant libraries via your dependency management system, for example Maven. If you require the compiler (xjc.exe
) you also need to download that separately.
How to encode and decode Base64 and Base64Url in Flutter / Dart
The dart:convert
library contains an encoder and decoder for Base64 and Base64Url. However, they encode and decode Lists of integers, so for strings you also need to encode and decode in UTF-8. Rather than doing these two encodings separately, you can combine them with fuse
.
You need to have the following import:
import 'dart:convert';
Base64
String credentials = "username:password";
Codec<String, String> stringToBase64 = utf8.fuse(base64);
String encoded = stringToBase64.encode(credentials); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64.decode(encoded); // username:password
Note that this is equivalent to:
String encoded = base64.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64.decode(encoded)); // username:password
Base64Url
String credentials = "username:password";
Codec<String, String> stringToBase64Url = utf8.fuse(base64Url);
String encoded = stringToBase64Url.encode(credentials); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64Url.decode(encoded); // username:password
Again, this is equivalent to:
String encoded = base64Url.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64Url.decode(encoded)); // username:password
See also
- RCF 4648
- String based data encoding: Base64 vs Base64url
base 64 encode and decode a string in angular (2+)
Use the btoa()
function to encode:
console.log(btoa("password")); // cGFzc3dvcmQ=
GOLANG Base64 Encode and Decode size mismatched for large files
you don't Close()
the encoder
so it doesn't flush all the data. from the docs (emphasis mine):
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser
NewEncoder returns a new base64 stream encoder. Data written to the
returned writer will be encoded using enc and then written to w.
Base64 encodings operate in 4-byte blocks; when finished writing, the
caller must Close the returned encoder to flush any partially written
blocks.
I also quote the example from the docs which has a nice comment:
package main
import (
"encoding/base64"
"os"
)
func main() {
input := []byte("foo\x00bar")
encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
encoder.Write(input)
// Must close the encoder when finished to flush any partial blocks.
// If you comment out the following line, the last partial block "r"
// won't be encoded.
encoder.Close()
}
Encoding as Base64 in Java
You need to change the import of your class:
import org.apache.commons.codec.binary.Base64;
And then change your class to use the Base64 class.
Here's some example code:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
Then read why you shouldn't use sun.* packages.
Update (2016-12-16)
You can now use java.util.Base64
with Java 8. First, import it as you normally do:
import java.util.Base64;
Then use the Base64 static methods as follows:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
If you directly want to encode string and get the result as encoded string, you can use this:
String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
See Java documentation for Base64 for more.
Does anyone know how to decode and encode a string in Base64 using Base64?
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);
Related Topics
How to Know Whether I am in a Call on Android
What's a Good Library for Parsing Mathematical Expressions in Java
Android How to Listen for Volume Button Events
Android: Switch Camera When Button Clicked
How to Change a Bitmap's Opacity
What Is Difference Between @+Id/Android:List and @+Id/List
Send Sms Until It Is Successful
Change Listview Background - Strange Behaviour
Code Will Only Return 0.0, 0.0 Gps Coordinate While Throwing Nullpointerexception
Android Studio Convert Iso String to "America/New_York" When Adding to Event to Calendar
How to Automatically Generate Getters and Setters in Eclipse
Using Client/Server Certificates for Two Way Authentication Ssl Socket on Android
Elegant Way to Read File into Byte[] Array in Java
How to Use Okhttp to Upload a File
Why Doesn't Java Throw an Exception When Dividing by 0.0