HOWTO: Understanding certificate download formats supported by the WebSDK

When using the 'Certificate/Retrieve' API function to download certificates and key material, it can be somewhat confusing to figure out how to convert the CertificateData that included in the response to the correct format on disk to use the certificate data.

Per the WebSDK documentation, we support the following formats:

Base64 - PEM encoded certificate
Base64 (PKCS #8) - PEM encoded certificate followed by PEM encoded encrypted private key
DER - Binary encoded certificate
PKCS #7 - Binary encoded certificate containing full root chain
PKCS #12 - Binary encoded certificate & encrypted private key.
Regardless of what format is being used to request the certificate, the CertificateData element contains the certificate data as a raw byte stream that is Base64 encoded. For binary certificate data (DER, PKCS #7 and PKCS #12), the Base64 data can be simply decoded as a byte array and written to disk. For printable certificate formats (Base64), the Base64 data represents a series of ASCII characters. Thus, to save the certificate data as a file, the data must first be Base64 decoded, then encoded as an ASCII string.

Windows PowerShell has the ability to use the .NET framework's data conversion functions which make it trivial to convert data to the correct format. Below is an example of using the System.Text.Encoding and System.Convert functions to obtain a PEM encoded certificate and corresponding encrypted private key using Certificates/Retrieve (this example assumes that a valid API key has already been set in the $header dictionary and that $certdn points to the full DN of a valid certificate in TPP):

$body = @{CertificateDN=$certdn;Format="Base64";IncludePrivateKey=$true;Password='Pa$$w0rd12'}

$json = ConvertTo-Json -InputObject $body

$uri = $baseurl + "/Certificates/Retrieve"
$result = Invoke-RestMethod -Uri $uri -Method Post -Headers $header -Body $json

$data = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($result.CertificateData))


Please sign in to leave a comment.