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.

Answer from Frank on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Base64.Encoder.html
Base64.Encoder (Java Platform SE 8 )
July 21, 2026 - Encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme.
Discussions

Will Base64.Encoder.encode(byte[]) behave consistently across platforms?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
8
4
April 18, 2024
Help needed to decode base64 string to byte array.
Note that data.codec is now not necessary and you can just use https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html in the JDK More on reddit.com
🌐 r/Clojure
7
4
June 4, 2024
Base64 Encoding Performance: Java vs Rust
I feel like this article could really do with an explanation of why java outperforms rust here. The ending just comes off as "wow this performs better thus jvm > rust" which I doubt is the full story. More on reddit.com
🌐 r/rust
34
49
October 16, 2022
Is it a good idea to convert images into base64 string and save them in database?
You will get many people saying don't because if not implemented well it can bite ya. Don't be concerned about "optimal", tell yourself "good enough" and "don't let perfect be the enemy of good". But I have done this for several projects (enterprise, mission critical systems) and it works just fine. From the developer standpoint I love it. When I yank the "byte array" from the DB I can just pass it right to the client as-is, just adding on the mime type, super simple. Right now I have a system that stores photos of students at a university and we serve those out with an API. All done in C# and SQL Server. We have probably 50,000 photos and it is lighting fast. That being said I have also stored files in S3 and just stored the name in the DB. I will usually rename the file so S3 stores it efficiently. I like things like s3 better than a file system since you can dedicate a bucket just to this and some sysadmin won't go mucking around. I agree with you on storing the unstructured binary data along with your structured data for simplicity. I had a project once that wrote images to a filesystem. Years later older images were lost due to some file system cleanup process. Over my 25 years programming I have found you cannot guess where the issues will be. Don't optimize until you measure it. If you can build a proof of concept then hammer it, do it. Write a script that inserts and reads images and loop it for a few hours. See what happens. Also if you implement something and a few years later it starts to falter, then refactor. But you need to monitor! This is another place where people get bit, they do something like this and just let it run in a corner until it "just dies for no reason" one day. You or someone needs to care and feed for it. I am going to assume on-prem Microsoft SQL Server, your usage may vary. Use "VARBINARY(MAX)" for the field type https://docs.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver15 Put it in a table by itself with an id to look it up. Store filename, and filetype(mime-type) too if needed. Slap an index on the id, reference that id in other tables. Critical: Put the table in its own filegroup separate from the other tables. This will allow for faster restores since you can restore the primary filegroup and get your DB back online ASAP, then as it is up and running restore the filegroup with the images. So instead of the whole DB being down for hours, it is up in minutes with only the images being unavailable for hours. https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-files-and-filegroups?view=sql-server-ver15 As with all DBs the filegroups should not be on the system (C) drive, maybe even put the images table filegroup on its own drive with nothing else. Do set a limit on the incoming filesize in your code. Someone could send in a few Blu-ray ISOs and cripple your system. In .NET code you store the image data in a byte array "byte[] " variable. That byte array is what is stored in the varbinary(max) DB field. It is easy to convert the incoming image/file to byte[], just google around for that there are many easy to do it. Design and implement a cleanup process and purge old unneeded records. No one ever seems to do this and the data grows forever until the system is retired/migrated. For small DBs it's not a problem but for this you must go back to your stakeholder and get in writing when you can delete old records then set an automated process or scheduled manual progress to do it. If they need the data long term maybe older data can be moved out of the online system and to an archive or warehouse. Microsoft has some other methods that I have not used. Check those out. https://docs.microsoft.com/en-us/sql/relational-databases/blob/binary-large-object-blob-data-sql-server?view=sql-server-ver15 -- Good luck More on reddit.com
🌐 r/dotnet
111
46
April 28, 2022
🌐
Baeldung
baeldung.com › home › java › java base64 encoding and decoding
Java Base64 Encoding and Decoding | Baeldung
February 18, 2026 - Java supports Base64 encoding and decoding features through the java.util.Base64 utility class.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Base64.html
Base64 (Java Platform SE 8 )
July 21, 2026 - Uses the "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return '\r' followed immediately by a linefeed '\n' as the line separator.
🌐
Base64Encode.org
base64encode.org › enc › java
Base64 Encoding of "java" - Online
Encode java to Base64 format with various advanced options. Our site has an easy to use online tool to convert your data.
🌐
GitHub
github.com › openjdk › jdk › blob › master › src › java.base › share › classes › java › util › Base64.java
jdk/src/java.base/share/classes/java/util/Base64.java at master · openjdk/jdk
import jdk.internal.access.JavaLangAccess; import jdk.internal.access.SharedSecrets; import jdk.internal.util.Preconditions; import jdk.internal.vm.annotation.IntrinsicCandidate; · /** * This class consists exclusively of static methods for obtaining · * encoders and decoders for the Base64 encoding scheme.
Author: openjdk
Find elsewhere
🌐
Apache Commons
commons.apache.org › proper › commons-codec › apidocs › org › apache › commons › codec › binary › Base64.html
Base64 (Apache Commons Codec 1.22.1 API)
The class can be parameterized in the following manner with its Base64.Builder: URL-safe mode: Default off. Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
🌐
GeeksforGeeks
geeksforgeeks.org › java › basic-type-base64-encoding-and-decoding-in-java
Basic Type Base64 Encoding and Decoding in Java - GeeksforGeeks
July 11, 2025 - The Basic encoding means no line feeds are added to the output and the output is mapped to a set of characters in A-Za-z0-9+/ character set and the decoder rejects any character outside of this set.
🌐
Medium
medium.com › @AlexanderObregon › javas-base64-getencoder-method-explained-d3c331139837
Java’s Base64.getEncoder() Method Explained | Medium
October 22, 2024 - Let’s break down the core idea behind the Base64.getEncoder() method: Binary-to-Text Encoding: It converts any arbitrary binary data (represented as a byte array in Java) into a Base64-encoded string.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java 8 Base64 Encoding and Decoding (With Examples) - Java Code Geeks
September 8, 2020 - In java 8, We can use mainly 3 types of encoding and decoding capabilities as standard. All of the classes are related to this are in java.util.base64 package.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
Base64 encoding and decoding in Java 8 | InfoWorld
December 6, 2017 - Also, this variant is useful when the encoded data is to be used for a filename because Unix and Windows filenames cannot contain /. Java 8 introduced a Base64 API consisting of the java.util.Base64 class along with its Encoder and Decoder nested static classes.
🌐
Reddit
reddit.com › r/javahelp › will base64.encoder.encode(byte[]) behave consistently across platforms?
r/javahelp on Reddit: Will Base64.Encoder.encode(byte[]) behave consistently across platforms?
April 18, 2024 -

My coworker and I are building a Java API that expects a certain parameter to be passed in as a byte array that is Base64-encoded in accordance with RFC 4648.

We are currently writing sample Java code to share with integrators that is meant to be illustrative of how they should call the API. My suggestion was that we should tell them to call Base64.Encoder.encode(byte[]) on their pre-encoded payload, and then pass the returned base64-encoded byte array into our API.

My coworker has expressed worry that this may result in behavior that is platform-dependent, with the behavior potentially being different depending on what the default Charset is on whatever platform the integrator's software is running on. He has suggested that we should instead call Base64.Encoder.encodeToString(byte[]), and then convert the returned ISO-8859-1 String to byte[].

To give a concrete example, his worry seems to be that Base64.Encoder.encode(byte[]) could theoretically encode the base64 alphabet sequence ABC as {0, 65, 0, 66, 0, 67} instead of {65, 66, 67} — again, depending on what the default Charset is.

I don't think something like this can happen, for the following reasons:

  1. We are starting with a byte array and ending with a byte array, so Charsets shouldn't be relevant, as we aren't dealing in Strings at all.

  2. As I understand, Java is generally platform-independent in the sense that the same code should behave the same way, regardless of what platform it's running on.

Is his concern a valid one, and if so, how should we write our sample code?

Thanks!

Top answer
1 of 3
4
No, his concern is not a valid one. As you said, base64 encoder takes as input an array of bytes and outputs another array of bytes. This has nothing to do with any charsets. The encoding scheme is clearly defined and will always result in the same outputs, no matter on which system. Also, calling encodeToString first would make no sense either as it simply calls encode internally.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Tutorialspoint
tutorialspoint.com › java › java_base64.htm
Java - Base64 Encoding and Decoding
This encoder uses characters lying in A-Za-z0-9+/ character set. Following is the snippet explaining the use of Base64 encoder. String stringToEncode = "TutorialsPoint?java8"; // Encode using basic encoder String base64encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes("utf-8"));
🌐
GitHub
gist.github.com › 1276960 › 9e99b409e8d57c624e2a16793faa9c16e3745db2
Encode a file to base64 binary in Java · GitHub
File originalFile = new File("signature.jpg"); String encodedBase64 = null; try { FileInputStream fileInputStreamReader = new FileInputStream(originalFile); byte[] bytes = new byte[(int)originalFile.length()]; fileInputStreamReader.read(bytes); encodedBase64 = new String(Base64.encodeBase64(bytes)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
🌐
Coderanch
coderanch.com › t › 566134 › java › encode-long-base
How to encode a long into base64 and get it back? (Java in General forum at Coderanch)
Also, when encoding a complete value, the number of bytes is often put at the front. Certainly, what you're seeing is way more than just a long. There is a lot to know about base64, and I suspect you need to do some reading, rather than just "expecting" your encoded value to be the same as what you see from an outside source.
🌐
Blogger
javarevisited.blogspot.com › 2016 › 10 › base64-encoding-example-in-java-8.html
How to Base 64 Encoding Decoding in Java 8 - Example Tutorial
April 24, 2023 - Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and its Base64 class to encode or decode binary data into base 64 encoding, as shown ...
🌐
Coderanch
coderanch.com › t › 327477 › java › Base-Encoding
Base64 Encoding (Java in General forum at Coderanch)
September 22, 2005 - I was going to add "in java" but it's essentially identical in C, C++ and C#. No chuckling but this is a beginner topic in any language. http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html Nail down bitwise operations then you can do things like Base64 encoding or anything else that manipulates bits and bit fields.
🌐
Coderanch
coderanch.com › t › 354353 › java › base-encoding
Help:: how can I do the base64 encoding? (Servlets forum at Coderanch)
Thakns. //get usrname and password String username = request.getParameter("username"); String password = request.getParameter("password"); String userInfo = username + password; out.println(userInfo); //encoder username and password BASE64Encoder encoder = new BASE64Encoder();
🌐
Medium
medium.com › @abdellatife.housni › base64-encoding-decoding-in-java-6cfb651e4ee9
Base64 Encoding/Decoding in Java. Base64 is a group of binary-to-text… | by Abdellatife Housni | Medium
September 30, 2022 - MIME Uses “The Base64 Alphabet” as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator.
🌐
Ocaso3D
b64encode.com › blog › base64-in-java
Base64 in Java: How to Encode & Decode - B64Encode
May 2, 2024 - The URL-safe encoding method produces a Base64-encoded string where the characters ‘+’ and ‘/’ are replaced with ‘-‘ and ‘_’. This is useful when encoding data for URLs. To use URL-safe encoding, you can directly obtain an instance of the URL-safe encoder and call the encodeToString method. import java.util.Base64; public class Base64Example { public static void main(String[] args) { byte[] binaryData = "B64Encode".getBytes(); Base64.Encoder urlEncoder = Base64.getUrlEncoder(); String urlSafeString = urlEncoder.encodeToString(binaryData); System.out.println("URL-Safe Encoding: " + urlSafeString); } }