{"id":24064718,"url":"https://github.com/jeninsutradhar/base64-rust-encoder-decoder","last_synced_at":"2026-06-14T15:39:57.868Z","repository":{"id":242551297,"uuid":"809867731","full_name":"JeninSutradhar/base64-Rust-Encoder-Decoder","owner":"JeninSutradhar","description":"A Rust implementation of a Base64 encoder and decoder. This project includes functions to encode binary data into a Base64 string and decode a Base64 string back into binary data.","archived":false,"fork":false,"pushed_at":"2024-06-04T13:46:36.000Z","size":31,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-09T10:39:47.130Z","etag":null,"topics":["base64","base64-decoding","base64-encoding","encoder-decoder","encryption-decryption","rust-lang","rust-library"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JeninSutradhar.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-03T15:47:02.000Z","updated_at":"2024-10-16T07:17:52.000Z","dependencies_parsed_at":"2024-06-03T18:44:37.257Z","dependency_job_id":null,"html_url":"https://github.com/JeninSutradhar/base64-Rust-Encoder-Decoder","commit_stats":null,"previous_names":["jeninsutradhar/base64-rust-encoder-decoder"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JeninSutradhar%2Fbase64-Rust-Encoder-Decoder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JeninSutradhar%2Fbase64-Rust-Encoder-Decoder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JeninSutradhar%2Fbase64-Rust-Encoder-Decoder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JeninSutradhar%2Fbase64-Rust-Encoder-Decoder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JeninSutradhar","download_url":"https://codeload.github.com/JeninSutradhar/base64-Rust-Encoder-Decoder/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240907852,"owners_count":19876691,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["base64","base64-decoding","base64-encoding","encoder-decoder","encryption-decryption","rust-lang","rust-library"],"created_at":"2025-01-09T10:39:52.315Z","updated_at":"2026-06-14T15:39:52.847Z","avatar_url":"https://github.com/JeninSutradhar.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Base64 Encoder and Decoder Rust\n\nA Rust implementation of a Base64 encoder and decoder. This project includes functions to encode binary data into a Base64 string and decode a Base64 string back into binary data.\n\n![image](https://github.com/JeninSutradhar/base64-Rust-Encoder-Decoder/assets/111521642/53221eb0-11eb-4478-b3f4-f1835e8e24c7)\n\n## Table of Contents\n\n- [Introduction](#introduction)\n- [Usage](#usage)\n  - [Encoding](#encoding)\n  - [Decoding](#decoding)\n- [Examples](#examples)\n- [Installation](#installation)\n- [Code Explaination](#code-explaination)\n- [Running Tests](#running-tests)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Introduction\n\nBase64 encoding is a method to convert binary data into an ASCII string format using 64 printable characters (A-Z, a-z, 0-9, +, and /). This encoding scheme is widely used for transmitting binary data over media designed to handle text.\n\n- This project provides a simple and efficient implementation of Base64 encoding and decoding in Rust.\n\n## Usage\n\n### Encoding\n\nTo encode data using Base64, use the `base64_encode` function provided by the library. It takes a byte slice and returns a Base64 encoded string.\n\n### Decoding\n\nTo decode a Base64 encoded string, use the `base64_decode` function. It takes a Base64 encoded string and returns a byte vector (if decoding is successful) or an error.\n\n## Examples\n\n### Encoding Example\n\nHere is an example of encoding data to a Base64 string:\n\n```rust\nuse base64::base64_encode;\n\nfn main() {\n    // Data : String to Encode\n    let data = b\"The quick brown fox jumps over the lazy dog\";\n    let encoded = base64_encode(data);\n    println!(\"Encoded: {}\", encoded);\n}\n```\n\n### Decoding Example\n\nHere is an example of decoding a Base64 string back to its original binary data:\n\n```rust\nuse base64::base64_decode;\n\nfn main() {\n    // Decoded 'String' to Encode\n    let encoded = \"VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==\";\n    \n    match base64_decode(encoded) {\n        Ok(decoded) =\u003e {\n            let decoded_str = String::from_utf8(decoded).expect(\"Invalid UTF-8 sequence\");\n            println!(\"Decoded: {}\", decoded_str);\n        },\n        Err((err_msg, invalid_byte)) =\u003e {\n            println!(\"Error: {} (invalid byte: {})\", err_msg, invalid_byte);\n        }\n    }\n}\n```\n\n## Installation\n\nTo use this library in your project, add the following to your `Cargo.toml`:\n\n```toml\n[dependencies]\nbase64 = { path = \"path/to/your/library\" }\n```\n\nThen, import the library in your `main.rs` or `lib.rs`:\n\n```rust\nuse base64::{base64_encode, base64_decode};\n```\n\n# Code Explaination\nCertainly! Let's break down the working of the code and the `base64_encode` and `base64_decode` functions in detail.\n\n### Working of the Code\n\n**Base64 Encoding and Decoding Overview**:\n- Base64 encoding converts binary data into a textual representation using 64 ASCII characters. Each Base64 character represents 6 bits of the original binary data.\n- Decoding is the reverse process, converting the Base64 text back into binary data.\n\n### Constants\n\n1. **CHARSET**:\n   ```rust\n   const CHARSET: \u0026[u8; 64] = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n   ```\n   This defines the 64 characters used in Base64 encoding.\n\n2. **PADDING**:\n   ```rust\n   const PADDING: char = '=';\n   ```\n   This character is used for padding the Base64 encoded string when the input data is not a multiple of 3 bytes.\n\n### Helper Function\n\n**collect_six_bits**:\n```rust\nfn collect_six_bits(from: (u8, u8), offset: u8) -\u003e u8 {\n    let combined: u16 = ((from.0 as u16) \u003c\u003c 8) | (from.1 as u16);\n    ((combined \u0026 (0b1111110000000000u16 \u003e\u003e offset)) \u003e\u003e (10 - offset)) as u8\n}\n```\n- **Parameters**: Takes a tuple of two bytes (`from`) and an offset (`offset`).\n- **Combines** the two bytes into a single 16-bit integer.\n- **Masks** and extracts 6 bits from the combined value based on the offset.\n- **Returns**: A single byte (u8) containing the 6 bits extracted.\n\n### Encoding Function\n\n**base64_encode**:\n```rust\npub fn base64_encode(data: \u0026[u8]) -\u003e String {\n    let mut encoded_string = String::new();\n    let mut bits_encoded = 0usize;\n\n    let padding_needed = ((6 - (data.len() * 8) % 6) / 2) % 3;\n    loop {\n        let lower_byte_index_to_encode = bits_encoded / 8usize;\n        if lower_byte_index_to_encode == data.len() {\n            break;\n        };\n\n        let lower_byte_to_encode = data[lower_byte_index_to_encode];\n        let upper_byte_to_code = if (lower_byte_index_to_encode + 1) == data.len() {\n            0u8\n        } else {\n            data[lower_byte_index_to_encode + 1]\n        };\n\n        let bytes_to_encode = (lower_byte_to_encode, upper_byte_to_code);\n        let offset: u8 = (bits_encoded % 8) as u8;\n        encoded_string.push(CHARSET[collect_six_bits(bytes_to_encode, offset) as usize] as char);\n\n        bits_encoded += 6;\n    }\n\n    for _ in 0..padding_needed {\n        encoded_string.push(PADDING);\n    }\n\n    encoded_string\n}\n```\n- **Input**: Takes a byte slice (`\u0026[u8]`) of the data to be encoded.\n- **Initializes** an empty string `encoded_string` to hold the resulting Base64 encoded string.\n- **Calculates** the necessary padding based on the length of the input data.\n- **Loop**:\n  - Determines the index of the current byte to encode based on `bits_encoded`.\n  - If all bytes are processed, the loop breaks.\n  - Retrieves the current byte and the next byte (if available) to form a 16-bit combined value.\n  - Calls `collect_six_bits` to get 6 bits from the combined value.\n  - Maps the 6 bits to a Base64 character using `CHARSET` and appends it to `encoded_string`.\n  - Increments `bits_encoded` by 6.\n- **Adds** padding characters if needed.\n- **Returns** the encoded string.\n\n### Decoding Function\n\n**base64_decode**:\n```rust\npub fn base64_decode(data: \u0026str) -\u003e Result\u003cVec\u003cu8\u003e, (\u0026str, u8)\u003e {\n    let mut collected_bits = 0;\n    let mut byte_buffer = 0u16;\n    let mut databytes = data.bytes();\n    let mut outputbytes = Vec::\u003cu8\u003e::new();\n\n    'decodeloop: loop {\n        while collected_bits \u003c 8 {\n            if let Some(nextbyte) = databytes.next() {\n                if let Some(idx) = CHARSET.iter().position(|\u0026x| x == nextbyte) {\n                    byte_buffer |= ((idx \u0026 0b00111111) as u16) \u003c\u003c (10 - collected_bits);\n                    collected_bits += 6;\n                } else if nextbyte == (PADDING as u8) {\n                    collected_bits -= 2;\n                } else {\n                    return Err((\"Failed to decode base64: Expected byte from charset, found invalid byte.\", nextbyte));\n                }\n            } else {\n                break 'decodeloop;\n            }\n        }\n        outputbytes.push(((0b1111111100000000 \u0026 byte_buffer) \u003e\u003e 8) as u8);\n        byte_buffer \u0026= 0b0000000011111111;\n        byte_buffer \u003c\u003c= 8;\n        collected_bits -= 8;\n    }\n\n    if collected_bits != 0 {\n        return Err((\"Failed to decode base64: Invalid padding.\", collected_bits));\n    }\n\n    Ok(outputbytes)\n}\n```\n- **Input**: Takes a Base64 encoded string (`\u0026str`).\n- **Initializes**:\n  - `collected_bits` to keep track of bits collected.\n  - `byte_buffer` to store bits as they are collected.\n  - `databytes` as an iterator over the bytes of the input string.\n  - `outputbytes` as a vector to store the decoded bytes.\n- **Loop**:\n  - Collects bits until at least 8 bits are available.\n  - Retrieves the next byte from the iterator.\n  - Checks if the byte is in the `CHARSET` and gets its index, otherwise checks for padding.\n  - Updates `byte_buffer` with the 6 bits from the current byte.\n  - Adds the byte to the `outputbytes` when at least 8 bits are available.\n  - Adjusts `byte_buffer` and `collected_bits` for the next iteration.\n- **Handles padding** by reducing `collected_bits` when a padding character is encountered.\n- **Returns** the decoded byte vector or an error if there is an issue with the input string (invalid characters or incorrect padding).\n\n### Testing\n\n**Tests**:\n- **`pregenerated_random_bytes_encode`**: Tests the encoding function with predefined byte arrays and their expected Base64 encoded strings.\n- **`pregenerated_random_bytes_decode`**: Tests the decoding function with predefined Base64 encoded strings and their expected byte arrays.\n- **`encode_decode`**: Tests the encoding and then decoding of predefined byte arrays to ensure the output matches the original input.\n- **`decode_encode`**: Tests the decoding and then encoding of predefined Base64 encoded strings to ensure the output matches the original input.\n\nThese tests ensure that the encoding and decoding functions work correctly for a variety of inputs, including edge cases and random data.\n\n## Running Tests\n\nTo run the provided tests for the encoder and decoder, use the following command:\n\n```sh\ncargo test\n```\n\n## Contributing\n\nContributions are welcome! If you find a bug or have a feature request, please open an issue. If you'd like to contribute code, please fork the repository and create a pull request.\n\n1. Fork the repository.\n2. Create a new branch for your feature or bugfix.\n3. Commit your changes.\n4. Push to your branch.\n5. Create a pull request.\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeninsutradhar%2Fbase64-rust-encoder-decoder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjeninsutradhar%2Fbase64-rust-encoder-decoder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeninsutradhar%2Fbase64-rust-encoder-decoder/lists"}