Home > Java > javaTutorial > How to Encode and Decode Strings in Base64 Using Java?

How to Encode and Decode Strings in Base64 Using Java?

Susan Sarandon
Release: 2024-11-21 05:48:09
Original
465 people have browsed it

How to Encode and Decode Strings in Base64 Using Java?

Decoding and Encoding Strings in Base64 Using Base64

Decoding and encoding strings in Base64 is a common task in programming, and Java provides built-in functionality for these operations. However, it's important to understand the process and ensure proper implementation.

Firstly, you'll need to choose an encoding, with UTF-8 being a recommended choice. It's crucial to select an encoding that will be supported on both the sending and receiving ends.

Encoding Process:

  1. Convert the original string into bytes using the getBytes() method with the appropriate encoding.
  2. Use the encodeBytes() method provided by the Base64 class to encode the bytes.
  3. The resulting encoded string can now be transmitted.

Decoding Process:

  1. Receive the encoded string.
  2. Employ the decode() method of the Base64 class to decode the base64 string back into bytes.
  3. Finally, decode the bytes into a string using new String(bytes, encodingName).

An improved version of the code provided in the question:

String source = "password"; 
byte[] byteArray = source.getBytes(StandardCharsets.UTF_8); 
Base64 base64 = new Base64(); 
System.out.println(base64.encodeToString(byteArray, Base64.DEFAULT)); 
System.out.println(new String(base64.decode(byteArray)));
Copy after login

The code ensures proper encoding/decoding using the recommended UTF-8 encoding and applies correct methods to encode/decode the string.

The above is the detailed content of How to Encode and Decode Strings in Base64 Using Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template