Python – Mask/hide GitHub access tokens

Mask/hide GitHub access tokens… here is a solution to the problem.

Mask/hide GitHub access tokens

Let’s say I have a GitHub that looks like this accesses token a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 。 This token needs to be placed in some code to create an issue when the secondary account needs it. I don’t want people to know about my access token, because that would be a terrible idea. What is the best way to mask/hide my access token to put it in the code, and how would I reverse the mask/hide functionality without the obvious?

Solution

You can encode it using Base64 encoding:

>>> import base64
>>> access_token = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"
>>> encoded_access_token = base64.b64encode(access_token)
>>> encoded_access_token
'YTk0YThmZTVjY2IxOWJhNjFjNGMwODczZDM5MWU5ODc5ODJmYmJkMw=='

It’s not necessarily safe, but we can make it safe. We can go ahead and encode access_token n and hide the number n in the result string. I chose the end.

For example, set n = 5.

def encodeToken(access_token, n):
    for i in range(n + 1):
         access_token = base64.b64encode(access_token)
    return access_token + str(n)

def decodeToken(encoded_token):
    n = encoded_token[-1]
    encoded_token = encoded_token[:-1]
    for i in range(int(n) + 1):
         encoded_token = base64.b64decode(encoded_token)
    return encoded_token

>>> access_token = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"
>>> encoded_access_token = encodeToken(access_token, 5)
>>>  encoded_access_token
"Vm1wR1lWVXlUbkpOVldScFVteGFiMVZ1Y0VkaFJscHlWMjFHYWxadFVsWlZNblIzWWtaS1ZXSkdiRlpOYWtaMlZrUktSMk5zWkhWU2JGWm9UV3hLVUZkclVrSk9Wa3BYWVROd2FsSXdXbFJWYkZKQ1pVWmFSMWR0ZEZkaGVsWlhWREZXVjFkdFZuTlhiRVpXWVRGYU0xcEZXbXR YUlRGV1pFZG9UbEpGVmpaV1ZWcFNaREZDVWxCVU1EMD0=5"
>>> decoded_access_token = decodeToken(encoded_access_token)
>>> decoded_access_token
"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"

The safest practice is to define your own methods to encode access tokens.

Related Problems and Solutions