bashmacosbase64hexxxd

Decode a base64 string and encode it as hex using xxd


First, I take a base64 encoded string and decode it:

local base64_str="OQbb8rXnj/DwvglW018uP/1tqldwiJMbjxBhX7ZqwTw="
echo "${base64_str}" | base64 --decode > foo.txt

The size of the binary file is 32 bytes based on: wc -c < foo.txt

I use xxd to encode the value in the file to hex format:

xxd -p ./foo.txt ./foo.hex.txt

The hex value in the file foo.hex.txt is:

3906dbf2b5e78ff0f0be0956d35f2e3ffd6daa577088931b8f10615fb66a
c13c

The size of the encoded hash file is 66 bytes using wc -c < foo.hex.txt

I would like to take the base64 string and convert it to hex such that it remains a 32 byte string that I can use with openssl to encrypt and decrypt using aes-256 ciphers.

local iv_hex=$(base64_to_hex "${iv}")
local key_hex=$(base64_to_hex "${key}")

openssl enc -aes-256-ctr -K "${key_hex}" -iv "${iv_hex}" -in "${input_file}" -out "${output_file}"

Solution

  • xxd -p may have \n chars in the output so you need to remove them:

    base64_to_hex()
    {
        echo "$1" | base64 --decode | xxd -p | tr -d '\n'
    }
    

    Use your base64 string as example:

    $ hex=$( base64_to_hex OQbb8rXnj/DwvglW018uP/1tqldwiJMbjxBhX7ZqwTw= )
    $ echo $hex
    3906dbf2b5e78ff0f0be0956d35f2e3ffd6daa577088931b8f10615fb66ac13c