class MyBase64(obejct):
STANDARD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' # standard base64 alphabet
def __init__(self, alphabet=None):
if alphabet == None:
alphabet = MyBase64.STANDARD_ALPHABET
if len(alphabet) != len(MyBase64.STANDARD_ALPHABET):
raise RuntimeError('MyBase64 init error:alphabet len should equal 64')
self.alphabet = alphabet
def encode(self, data_to_encode):
encoded = base64.b64encode(data_to_encode)
return encoded.translate(maketrans(MyBase64.STANDARD_ALPHABET, self.alphabet))
def decode(self, string_to_decode):
encoded = string_to_decode.translate(maketrans(self.alphabet, MyBase64.STANDARD_ALPHABET))
return base64.b64decode(encoded)
@staticmethod
def random_alphabet():
temp = MyBase64.STANDARD_ALPHABET
out = ''
while (True):
size = len(temp)
if size <= 0:
break
index = random.randint(0, size - 1)
out = out + temp[index]
if index + 1 >= size:
temp = temp[0:index]
else:
temp = temp[0:index] + temp[index + 1:]
return out
python 自定义base64
最新推荐文章于 2024-06-12 13:43:16 发布