Base64 PSK Rolling Over

When creating a 128/256-bit PSK that starts with a specific base64 prefix, you might notice the prefix changes after encoding. For example, you set your key to start with ABCDPSK, but the encoded string shows ABCDPSL or something else instead.

Only today I realized that Base64 encoding works in groups of 3 bytes (24 bits), which translates to 4 base64 characters. If your prefix length isn’t a multiple of 4 characters, the encoding can “roll over” when random bytes are appended, shifting the bits and changing the prefix characters.

Below is my workaround:

  • Choose a prefix with length divisible by 4 (e.g., 4, 8, 12, 16 characters).
  • Decode this prefix to raw bytes.
  • Fix these bytes at the start of your PSK.
  • Append random bytes to complete 32 bytes (256 bits).
  • Encode the full key to base64.

This way, the base64 string will start exactly with your chosen prefix without rollover.

TLDR: Fix your prefix length to multiples of 4 base64 chars to ensure your key starts exactly as expected. Understanding base64 encoding basics can save you trouble when generating keys.