Encoding TLS Certificates in Base64

Prev Next

You can use the following code to encode the CA certificate, key and client certificate in base64.

Set ​TLS_ROOT​ to point to the system directory where TLS certificates and related assets are stored (​/var/lib/...​​).

#!/bin/bash

TLS_ROOT=<path to TLS assets> 

# Key: PEM as base64
CLIENT_KEY_B64=$(sudo cat $TLS_ROOT/client-admin.key | base64 -w 0)

# Client Certificate: Extract ONLY the first certificate (not the chain)
CLIENT_CERT_ONLY=$(sudo cat $TLS_ROOT/client-admin.crt | \
  awk '/BEGIN CERTIFICATE/,/END CERTIFICATE/ {print; if (/END CERTIFICATE/) exit}')
CLIENT_CERT_B64=$(echo "$CLIENT_CERT_ONLY" | base64 -w 0)

# CA Certificate: From separate file
CA_CERT_B64=$(sudo cat $TLS_ROOT/server-ca.crt | base64 -w 0)

cat <<EOF
{
  "client_key_b64": "$CLIENT_KEY_B64",
  "client_certificate_b64": "$CLIENT_CERT_B64",
  "certificate_authority_b64": "$CA_CERT_B64"
}
EOF