Skip to content
Fix Code Error

Encoding as Base64 in Java

March 13, 2021 by Code Error
Posted By: Anonymous

I need to encode some data in the Base64 encoding in Java. How do I do that? What is the name of the class that provides a Base64 encoder?


I tried to use the sun.misc.BASE64Encoder class, without success. I have the following line of Java 7 code:

wr.write(new sun.misc.BASE64Encoder().encode(buf));

I’m using Eclipse. Eclipse marks this line as an error. I imported the required libraries:

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

But again, both of them are shown as errors. I found a similar post here.

I used Apache Commons as the solution suggested by including:

import org.apache.commons.*;

and importing the JAR files downloaded from: http://commons.apache.org/codec/

But the problem still exists. Eclipse still shows the errors previously mentioned. What should I do?

Solution

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.

Answered By: Anonymous

Related Articles

  • Eclipse will not start and I haven't changed anything
  • Plugin…
  • Can't access Eclipse marketplace
  • Neither BindingResult nor plain target object for…
  • Eclipse fails to open .vue files in Web Page Editor
  • What are the best JVM settings for Eclipse?
  • Problems using Maven and SSL behind proxy
  • Maven2: Missing artifact but jars are in place
  • Launching Spring application Address already in use
  • When I'm testing a web app by JUnit and Mockito I…
  • Name [jdbc/mydb] is not bound in this Context
  • Failed to execute goal…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Why am I getting a "401 Unauthorized" error in Maven?
  • TypeError: Cannot convert a symbolic Keras…
  • Creating an dynamic array, but getting segmentation…
  • "Non-resolvable parent POM: Could not transfer…
  • Exception in thread "JobGenerator"…
  • NullPointerException in eclipse in Eclipse itself at…
  • java.lang.ClassNotFoundException: HttpServletRequest
  • Tomcat 7 "SEVERE: A child container failed during start"
  • JPA Hibernate Persistence exception…
  • Spring schemaLocation fails when there is no…
  • C char array initialization
  • How to set HTML5 required attribute in Javascript?
  • Requested bean is currently in creation: Is there an…
  • What's causing my java.net.SocketException:…
  • Apache server keeps crashing, "caught SIGTERM,…
  • Using enums in a spring entity
  • UnsatisfiedDependencyException: Error creating bean…
  • java.lang.RuntimeException: Unable to instantiate…
  • Java Hashmap: How to get key from value?
  • ClassNotFoundException:…
  • PySpark 3 - UDF to remove items from list column
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • Reference - What does this regex mean?
  • How to handle invalid SSL certificates with Apache…
  • Error creating bean with name
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • AppCompat v7 r21 returning error in values.xml?
  • Address already in use: JVM_Bind
  • A fatal error has been detected by the Java Runtime…
  • How do I list / export private keys from a keystore?
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Injection of autowired dependencies failed;
  • SQLException: No suitable Driver Found for…
  • java.io.IOException: Broken pipe
  • NoClassDefFoundError while trying to run my jar with…
  • Vaadin Spring Boot - There was an exception while…
  • How to check if a String is numeric in Java
  • import sun.misc.BASE64Encoder results in error…
  • What encoding/code page is cmd.exe using?
  • error LNK2005: ✘✘✘ already defined in…
  • No Spring WebApplicationInitializer types detected…
  • Could not calculate build plan: Plugin…
  • How to set level logging to DEBUG in Tomcat?
  • Non-resolvable parent POM for Could not find…
  • Content is not allowed in Prolog SAXParserException
  • How to install JSTL? The absolute uri:…
  • How can I resolve Web Component Testing error?
  • Configure hibernate to connect to database via JNDI…
  • Exception in thread "main"…
  • javax.faces.application.ViewExpiredException: View…
  • My Application Could not open ServletContext resource
  • Jetpack Compose and Hilt Conflict
  • How do I use 3DES encryption/decryption in Java?
  • How to disable SSL certificate checking with Spring…
  • Unable to Build using MAVEN with ERROR - Failed to…
  • Running a simple JSF webapp on TOMEE-9.0 PLUS cannot…
  • How to solve this java.lang.NoClassDefFoundError:…
  • Is this very likely to create a memory leak in Tomcat?
  • How do I configure the proxy settings so that…
  • Get Base64 encode file-data from Input Form
  • HTTP Status 500 - org.apache.jasper.JasperException:…
  • Gradle error: Execution failed for task…
  • How to show title in hover - css / jquery
  • CSS Float: Floating an image to the left of the text
  • how to calculate percentage in python
  • What do the icons in Eclipse mean?
  • Eclipse - Run in Debug Mode fails
  • Reading and writing to serial port in C on Linux
  • How to fix Invalid AES key length?
  • Why did Servlet.service() for servlet jsp throw this…
  • How to encrypt String in Java
  • Autowiring fails: Not an managed Type
  • Maven does not find JUnit tests to run
  • Deploying Maven project throws…
  • laravel vuejs/axios put request Formdata is empty
  • String isNullOrEmpty in Java?
  • Spring data jpa- No bean named…
  • java IO Exception: Stream Closed
  • Unable to run Robolectric and Espresso with a…
  • How can I pad a String in Java?
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • org.gradle.api.tasks.TaskExecutionException:…
  • Spring Security exclude url patterns in security…
  • How to use java.net.URLConnection to fire and handle…
  • How to get UTF-8 working in Java webapps?
  • org.springframework.beans.factory.BeanCreationExcept…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

Next Post:

Unknown column in ‘field list’ error on MySQL Update query

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error