Last active
May 24, 2024 03:10
-
-
Save Wind010/76902a5ea3f48287e34829e9bca67ff9 to your computer and use it in GitHub Desktop.
Just base 64 encoding and decoding with URL safe call with hex string output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
def base64_decode(encoded_str, url_safe=True): | |
hexadecimal_hash = '' | |
padding = 4 - (len(encoded_str) % 4) | |
if padding and padding != 4: # Padding can be 1, 2, or 3 | |
encoded_str += '=' * padding | |
print(encoded_str) | |
if url_safe: | |
decoded_bytes = base64.urlsafe_b64decode(encoded_str) | |
else: | |
decoded_bytes = base64.b64decode(encoded_str) | |
try: | |
hex_str = ''.join(['{:02x}'.format(byte) for byte in decoded_bytes]) | |
except Exception as ex: | |
print("Could not decode.", ex) | |
return hex_str | |
def base64_encode(hex_str, url_safe=True): | |
data = bytes.fromhex(hex_str) | |
if url_safe: | |
encoded_bytes = base64.urlsafe_b64encode(data) | |
else: | |
encoded_bytes = base64.b64encode(data) | |
encoded_str = encoded_bytes.decode('utf-8') | |
return encoded_str | |
# Example usage: | |
data = '81dc9bdb52d04dc20036dbd8313ed055' | |
encoded = base64_encode(data) | |
print(encoded) | |
encoded_hash = "gdyb21LQTcIANtvYMT7QVQ==" | |
print(encoded_hash) | |
decoded = base64_decode(encoded_hash) | |
print(decoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment