Skip to content

Instantly share code, notes, and snippets.

@tiero
Created November 15, 2021 15:42
Show Gist options
  • Save tiero/a50bf6f18fcc13984529e3dd6e843093 to your computer and use it in GitHub Desktop.
Save tiero/a50bf6f18fcc13984529e3dd6e843093 to your computer and use it in GitHub Desktop.
Deocde a PEM certificate encoded as base64 url
const base64url = require('base64url')
const decodeUriComponent = require('decode-uri-component')
const fs = require('fs')
const untildify = require('untildify')
/**
* decode a tls certificate from a base64 encoded url string.
* @param {String} certString base64url encoded string to decode
* @return {String} decoded certificate
*/
const decodeCert = certString => {
if (!certString) {
return ''
}
const unescaped = decodeUriComponent(certString)
if (isAbsolute(untildify(unescaped))) {
return unescaped
}
const cert = base64url.toBase64(unescaped)
var prefix = '-----BEGIN CERTIFICATE-----\n'
var postfix = '-----END CERTIFICATE-----'
return prefix + cert.match(/.{0,64}/g).join('\n') + postfix
}
/**
* Cross platform isAbsolute path routine extracted from node JS code
*/
const CHAR_UPPERCASE_A = 65 /* A */
const CHAR_LOWERCASE_A = 97 /* a */
const CHAR_UPPERCASE_Z = 90 /* Z */
const CHAR_LOWERCASE_Z = 122 /* z */
const CHAR_FORWARD_SLASH = 47 /* / */
const CHAR_BACKWARD_SLASH = 92
const CHAR_COLON = 58
function isWindowsDeviceRoot(code) {
return (
(code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
)
}
function isPathSeparator(code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}
function isAbsolute(path) {
const len = path.length
if (len === 0) return false
const code = path.charCodeAt(0)
return (
isPathSeparator(code) ||
// Possible device root
(len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator(path.charCodeAt(2)))
)
}
const decoded = decodeCert("your_tdexdcoonect_string");
fs.writeFileSync('./cert.pem', decoded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment