Created
June 24, 2016 19:52
-
-
Save jorng/e612ac7d2a105a1c68d38d849ef7c5c8 to your computer and use it in GitHub Desktop.
(Python) Get a compiled regex to match a base64 string for a given hashing algorithm
This file contains hidden or 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 re | |
from math import ceil | |
import hashlib | |
def base64Regex(byteLength): | |
padLength = (3 - (byteLength % 3)) if (byteLength % 3) > 0 else 0 | |
strLength = int(ceil(byteLength / 3.)) * 4 - padLength | |
padding = '=' * padLength | |
regexString = '[a-zA-Z0-9+/]{{{strLength}}}{padding}'.format(**locals()) | |
return re.compile(regexString) | |
def base64RegexForHash(hashType): | |
if hashType not in hashlib.algorithms_available: | |
raise RuntimeError('Invalid hash type: {}'.format(hashType)) | |
byteLength = len(hashlib.new(hashType).digest()) | |
return base64Regex(byteLength) | |
# example usage: | |
sha1_b64_regex = base64RegexForHash('sha1') # r'[a-zA-Z0-9+/]{27}=' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment