python base64 编码与自定义转换表

admin 2024年5月30日03:51:58评论3 views字数 2156阅读7分11秒阅读模式

注意本文章只能作为学习用途, 造成的任何问题与作者无关, 如侵犯到你的权益,请联系删除。

因为在写加密解密的东西,看了一些python base64库的资料

代码如下:

import base64import randomimport stringdef 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 functiondef 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 functiondef 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 编码与自定义转换表

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年5月30日03:51:58
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   python base64 编码与自定义转换表http://cn-sec.com/archives/2793249.html

发表评论

匿名网友 填写信息