注意本文章只能作为学习用途, 造成的任何问题与作者无关, 如侵犯到你的权益,请联系删除。
因为在写加密解密的东西,看了一些python base64库的资料
代码如下:
import base64
import random
import string
def test_base64_encode():
result = None
# 要编码的数据,是bytes类型
# str --> byte
print("hello".encode('utf-8'))
# byte
b'hello'
# base64编码
temp01 = "hello"
# 对数据进行Base64编码,编码后也是byte类型
encoded_data = base64.b64encode(temp01.encode())
print(encoded_data)
# byte --> str
print("byte --> str " + encoded_data.decode('utf-8'))
def test_base64_decode():
str1 = "aGVsbG8="
# 对Base64编码的字符串进行解码,返回值是byte
decoded_data = base64.b64decode(str1)
print(decoded_data)
print(decoded_data.decode())
"""
自定义/随机字符集
"""
def test_custom_base64():
normal_base_64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
str_list = list(normal_base_64)
random.shuffle(str_list)
custom_base_64 = "".join(str_list)
print("随机字符集: " + custom_base_64)
str1 = "test"
print("原版: " + base64.b64encode(str1.encode()).decode())
base64_temp = EncodeCustomBase64(str1.encode(), custom_base_64)
print("自定义后: " + base64_temp)
decode_temp = DecodeCustomBase64(base64_temp, custom_base_64)
print("自定义解码: " + decode_temp)
# custom encoding function
def EncodeCustomBase64(stringToBeEncoded,custom_b64):
standard_b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
encoded = base64.b64encode(stringToBeEncoded)
final_encoded = ""
for ch in encoded.decode():
if (str(ch) in custom_b64):
final_encoded += custom_b64[standard_b64.find(str(ch))]
elif (ch == '='):
final_encoded += '='
return final_encoded
# custom decoding function
def DecodeCustomBase64(stringToBeDecoded:str,custom_b64):
standard_b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
temp_decoded = ""
for ch in stringToBeDecoded:
if (str(ch) in custom_b64):
temp_decoded += standard_b64[custom_b64.find(str(ch))]
elif (ch == '='):
temp_decoded += '='
decoded = base64.b64decode(temp_decoded)
return decoded.decode()
if __name__ == '__main__':
# test_base64_encode()
# test_base64_decode()
test_custom_base64()
初次之外还有
• base64.urlsafe_b64encode(data):使用URL和文件名安全的Base64字符集进行编码,将+和/分别替换为-和_。
• base64.urlsafe_b64decode(data):解码使用URL和文件名安全Base64字符集编码的数据。
参考链接:
https://mp.weixin.qq.com/s/6_b-IGBzmQSbwDdj0GGySg
自定义转换表
https://www.matteomalvica.com/blog/2019/01/21/custom-base64-alphabet-encoder/decoder/
原文始发于微信公众号(进击的HACK):python base64 编码与自定义转换表
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论