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

How Can I Encode and Decode Strings Using Base64 in Java?

Mary-Kate Olsen
Release: 2024-11-25 12:37:11
Original
365 people have browsed it

How Can I Encode and Decode Strings Using Base64 in Java?

Base64: Encoding and Decoding Strings with Base64

The Base64 encoding scheme is a way to represent binary data in an ASCII string. It is often used to encode data for transmission over networks or storage in databases.

Decoding and Encoding a String

To decode and encode a string using Base64, you can use the Java Base64 class. Here's the corrected code:

import java.util.Base64;

String source = "password";
byte[] byteArray = source.getBytes(StandardCharsets.UTF_8);

// Encode
byte[] encodedBytes = Base64.getEncoder().encode(byteArray);
String encodedString = new String(encodedBytes);
System.out.println("Encoded String: " + encodedString);

// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
String decodedString = new String(decodedBytes);
System.out.println("Decoded String: " + decodedString);
Copy after login

Encoding Process

  1. Convert the string to bytes: Encode the string into a byte array using UTF-8 or UTF-16 encoding.
  2. Base64 encode the bytes: Use the Base64 class to encode the byte array into a Base64 string.

Decoding Process

  1. Base64 decode the string: Use the Base64 class to decode the Base64 string back into a byte array.
  2. Convert the bytes to string: Decode the byte array into a string using the same encoding used for encoding.

The above is the detailed content of How Can I Encode and Decode Strings Using Base64 in 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