[C#] Converting Between Byte Arrays and Base64 Strings

目次

Overview

This article explains how to implement Base64 encoding, which is essential for handling binary data (such as images, PDFs, or encrypted keys) in text formats like JSON or HTTP headers. By using the standard System.Convert class, you can efficiently convert between byte arrays and Base64 strings.

Specifications (Input/Output)

  • Input
    • Encoding: Any byte[] (byte array).
    • Decoding: A valid Base64-formatted string.
  • Output
    • Encoding: A Base64-formatted string.
    • Decoding: The original byte[].
  • Exceptions
    • When decoding, if the input string is not a valid Base64 format, a FormatException will occur.

Basic Usage

The following is a basic example of converting a byte array to a Base64 string and back to the original byte array.

byte[] sourceBytes = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // "Hello"

// byte[] -> Base64
string base64String = Convert.ToBase64String(sourceBytes);

// Base64 -> byte[]
byte[] decodedBytes = Convert.FromBase64String(base64String);

Full Code

This console application demonstrates the process of converting string data into a UTF-8 byte array, encoding it into Base64 for communication, and finally restoring it.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            // 1. Original data (e.g., API keys, auth tokens, image data, etc.)
            string originalText = "User:Guest;Role:Admin;Exp:2025";
            Console.WriteLine($"[Original] {originalText}");

            // Convert string to byte array (UTF-8)
            byte[] rawBytes = Encoding.UTF8.GetBytes(originalText);
            
            // ---------------------------------------------------------
            // 2. Encoding: byte[] -> Base64 string
            // ---------------------------------------------------------
            string base64Encoded = Convert.ToBase64String(rawBytes);

            Console.WriteLine($"[Encoded ] {base64Encoded}");

            // ---------------------------------------------------------
            // 3. Decoding: Base64 string -> byte[]
            // ---------------------------------------------------------
            // Process on the receiving side to restore the original binary
            byte[] restoredBytes = Convert.FromBase64String(base64Encoded);

            // Convert the byte array back to a string for confirmation
            string restoredText = Encoding.UTF8.GetString(restoredBytes);
            Console.WriteLine($"[Restored] {restoredText}");

            // Integrity check
            bool isSame = originalText == restoredText;
            Console.WriteLine($"[Result  ] Success: {isSame}");
        }
        catch (FormatException ex)
        {
            Console.WriteLine($"[Error] Invalid Base64 format: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[Error] Unexpected error: {ex.Message}");
        }
    }
}

Output Example

[Original] User:Guest;Role:Admin;Exp:2025
[Encoded ] VXNlcjpHdWVzdDtSb2xlOkFkbWluO0V4cDoyMDI1
[Restored] User:Guest;Role:Admin;Exp:2025
[Result  ] Success: True

Customization Points

  • Changing Encodings: When using strings as the source, specify the encoding (e.g., Encoding.UTF8, Encoding.ASCII, or Encoding.Unicode) according to your system requirements.
  • Partial Conversion: Convert.ToBase64String has overloads that allow you to specify an array offset and length. Use this when you only need to convert a portion of a large buffer.
  • Formatting Options: By specifying Base64FormattingOptions.InsertLineBreaks, you can insert line breaks into the output string (useful for email attachments that have a 76-character limit).

Points of Caution

  • Data Size Increase: Base64 encoding increases the data size by approximately 1.33 times (about 33%) compared to the original binary. Be mindful of this when estimating bandwidth or storage capacity.
  • String Validity: FromBase64String will immediately throw an exception if the input string length is not a multiple of 4 or contains invalid characters. When handling user input, always use a try-catch block or perform prior validation.
  • Usage in URLs: Standard Base64 includes symbols that cannot be used in URLs (+, /). If you need to pass data as a URL parameter, you must use a “URL-Safe” approach (see the Application section below).
  • Padding Characters: The = characters at the end are padding. Deleting these carelessly will make the data unreadable, so they must be handled as they are.

Application

URL-Safe Base64 Conversion

This implementation example replaces + with - and / with _, and removes the = padding so the string can be used in Web API query parameters or JSON Web Tokens (JWT).

using System;
using System.Text;

public static class Base64UrlUtil
{
    // Encode to URL-Safe Base64
    public static string Encode(byte[] input)
    {
        string base64 = Convert.ToBase64String(input);
        // Replace + with -, / with _, and remove =
        return base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
    }

    // Decode from URL-Safe Base64
    public static byte[] Decode(string input)
    {
        // Replace - with +, _ with /
        string base64 = input.Replace('-', '+').Replace('_', '/');
        
        // Restore padding (=)
        switch (base64.Length % 4)
        {
            case 2: base64 += "=="; break;
            case 3: base64 += "="; break;
        }
        
        return Convert.FromBase64String(base64);
    }
}

Summary

Convert.ToBase64String and Convert.FromBase64String are ideal for scenarios where binary data needs to be safely transferred or stored as text. When using Base64 in a web communication context, you should modify the standard symbols to be URL-safe. Additionally, always consider the data size increase and the risk of exceptions from invalid input strings during implementation.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次