Encoding and Decoding Data Using Base64 - Notes By ShariqSP
Encoding and Decoding Data Using Base64
What is Base64 Encoding?
Base64 is a binary-to-text encoding scheme that converts binary data into a string format that can be safely transmitted or stored in text-based systems, such as JSON, XML, or URLs.
Base64 uses a 64-character set comprising letters (A–Z, a–z), numbers (0–9), and two additional symbols (`+` and `/`) to encode binary data into readable text. The output is often padded with `=` to ensure the final output is divisible by 4.
Steps in Base64 Encoding and Decoding
- Encoding: Converts binary data into a Base64 string. Commonly used for transmitting binary content like images or credentials in APIs.
- Decoding: Converts the Base64 string back into its original binary format.
Base64 in RestAssured
In RestAssured, Base64 is often used to encode sensitive data, such as API keys or credentials, before sending them as part of headers or payloads. For example, basic authentication requires a `username:password` string to be Base64 encoded.
For instance: - Plain credentials: admin:password - Base64 encoded: YWRtaW46cGFzc3dvcmQ=
Implementation in RestAssured
Below is a Java example demonstrating how to encode and decode data using Base64, followed by its integration with RestAssured.
Example Code
// Encode credentials String originalInput = "admin:password"; String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); System.out.println("Base64 Encoded: " + encodedString); // Decode Base64 string byte[] decodedBytes = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedBytes); System.out.println("Decoded String: " + decodedString); // Using encoded data in RestAssured RestAssured.given() .header("Authorization", "Basic " + encodedString) .get("http://example.com/api/endpoint") .then() .statusCode(200);