python中的base64加密和解密

python中的base64加密和解密

代碼以下:

import base64
import json


def row_data():
    content = {
        "buyer_nick": "家有親親",
        "payment": "109.40",
        "status": "ok",
        "iid": 0,
        "oid": 76491699395733780,
        "tid": "654561321213",
        "type": "guarantee_trade",
        "post_fee": "0.00",
        "seller_nick": "測試店鋪"
    }
    context_str = json.dumps(content, ensure_ascii=False)
    d = {
        "TmcId": 654561321213,
        "Topic": "taobao_trade_TradeBuyerPay",
        "UserId": "123456789",
        "UserNick": "測試店鋪",
        "PubAppKey": "12345678",
        "PubTime": "2017-10-18T16:32:39.033",
        "OutgoingTime": "2017-10-18T16:32:39.237",
        "Content": context_str
    }
    return d


class Base64Handler:
    @classmethod
    def base_encode(cls, json_data: dict):
        data_to_str = json.dumps(json_data, ensure_ascii=False)
        r = base64.b64encode(bytes(data_to_str, "utf-8"))
        return str(r, encoding="utf-8")

    @classmethod
    def base64_decode(cls, s):
        decode_data = base64.b64decode(s).decode()
        return decode_data


encode_data = Base64Handler.base_encode(row_data())

print("encode data:\n{}".format(encode_data))

decode_data = Base64Handler.base64_decode(encode_data)
print("decode data:\n{}".format(decode_data))

# base64在線加解密網站: https://www.sojson.com/base64.html
"""
encode data:
eyJUbWNJZCI6IDY1NDU2MTMyMTIxMywgIlRvcGljIjogInRhb2Jhb190cmFkZV9UcmFkZUJ1eWVyUGF5IiwgIlVzZXJJZCI6ICIxMjM0NTY3ODkiLCAiVXNlck5pY2siOiAi5rWL6K+V5bqX6ZO6IiwgIlB1YkFwcEtleSI6ICIxMjM0NTY3OCIsICJQdWJUaW1lIjogIjIwMTctMTAtMThUMTY6MzI6MzkuMDMzIiwgIk91dGdvaW5nVGltZSI6ICIyMDE3LTEwLTE4VDE2OjMyOjM5LjIzNyIsICJDb250ZW50IjogIntcImJ1eWVyX25pY2tcIjogXCLlrrbmnInkurLkurJcIiwgXCJwYXltZW50XCI6IFwiMTA5LjQwXCIsIFwic3RhdHVzXCI6IFwib2tcIiwgXCJpaWRcIjogMCwgXCJvaWRcIjogNzY0OTE2OTkzOTU3MzM3ODAsIFwidGlkXCI6IFwiNjU0NTYxMzIxMjEzXCIsIFwidHlwZVwiOiBcImd1YXJhbnRlZV90cmFkZVwiLCBcInBvc3RfZmVlXCI6IFwiMC4wMFwiLCBcInNlbGxlcl9uaWNrXCI6IFwi5rWL6K+V5bqX6ZO6XCJ9In0=
decode data:
{"TmcId": 654561321213, "Topic": "taobao_trade_TradeBuyerPay", "UserId": "123456789", "UserNick": "測試店鋪", "PubAppKey": "12345678", "PubTime": "2017-10-18T16:32:39.033", "OutgoingTime": "2017-10-18T16:32:39.237", "Content": "{\"buyer_nick\": \"家有親親\", \"payment\": \"109.40\", \"status\": \"ok\", \"iid\": 0, \"oid\": 76491699395733780, \"tid\": \"654561321213\", \"type\": \"guarantee_trade\", \"post_fee\": \"0.00\", \"seller_nick\": \"測試店鋪\"}"}
"""
相關文章
相關標籤/搜索