python3.x 16進文字列バイト文字列、base 64、base 32復号化

4253 ワード

に質問
16進数文字列を1バイト文字列に復号するか、1バイト文字列を16進数文字列に符号化します.
ソリューション
2つの方法があります.
  • binasciiモジュール
  • を使用する.
  • base64モジュール
  • を使用する.binasciiモジュールの使用
    import binascii
    string = b'hello'
    # Encode as hex
    string_hex = binascii.b2a_hex(string)
    # Decode back to bytes
    string_row = binascii.a2b_hex(string_hex)
    
    print(string_hex)
    print(string_row)
    
    base64モジュールの使用binasciiモジュールとは異なり、base64モジュールでは16進文字列からバイト文字列に移行する場合、16進文字列では大文字でなければならないため、upper()と組み合わせて使用する必要があります.
    import base64
    
    string = b'hello'
    # Encode as hex
    # base16   16  
    string_hex = base64.b16encode(string)
    # Decode back to bytes
    string_row = base64.b16decode(string_hex)
    
    print(string_hex)
    print(string_row)
    #     16              lower     
    string_row =  base64.b16decode(string_hex.upper())
    
    base64モジュールにおけるbase 64/base 32の暗号化、復号化
    import base64
    
    string = b'zzz'
    string_32encode = base64.b32encode(string) 
    string_32decode = base64.b32decode(string_32encode)
    
    string_64encode = base64.b64encode(string) 
    string_64decode = base64.b64decode(string_64encode)
    
    print(string_32encode)
    print(string_32decode)
    print(string_64encode)
    print(string_64decode)
    

    参照:16進数の符号化と復号化