programing

python에서 base64로 텍스트를 인코딩하는 방법

kingscode 2023. 5. 21. 14:38
반응형

python에서 base64로 텍스트를 인코딩하는 방법

텍스트 문자열을 base64로 인코딩하려고 합니다.

나는 이것을 하려고 했습니다:

name = "your name"
print('encoding %s in base64 yields = %s\n'%(name,name.encode('base64','strict')))

그러나 이로 인해 다음과 같은 오류가 발생합니다.

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

어떻게 해야 하나요? (파이썬 3.4 사용)

base64를 가져오는 것을 기억하고 b64encode는 바이트를 인수로 사용합니다.

import base64
b = base64.b64encode(bytes('your string', 'utf-8')) # bytes
base64_str = b.decode('utf-8') # convert bytes to string

이것은 자신만의 모듈을 가질 수 있을 만큼 충분히 중요한 것으로 밝혀졌습니다.

import base64
base64.b64encode(b'your name')  # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii'))  # b'eW91ciBuYW1l'

위해서py3베이스64encode그리고.decode문자열:

import base64

def b64e(s):
    return base64.b64encode(s.encode()).decode()


def b64d(s):
    return base64.b64decode(s).decode()

이 기능은 Python 2에서 가져오기 없이 작동합니다.

>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>

(비록 이것은 Python3에서 작동하지 않지만)

Python 3에서는 base64를 가져와 base64.b64decode('...')를 수행해야 합니다. - Python 2에서도 작동합니다.

base64 인코딩된 문자열을 통해 base64.b64decode를 호출한 후에도 실제 문자열 데이터를 사용하려면 decode() 함수를 호출하는 것이 필수적인 것 같습니다.왜냐하면 그것은 항상 바이트 리터럴을 반환한다는 것을 잊지 않기 때문입니다.

import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes)                                 # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str)                                # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str))              # b'your string'
print(base64.b64decode(encoded_str).decode())     # your string

py2 및 py3 모두와 호환됩니다.

import six
import base64

def b64encode(source):
    if six.PY3:
        source = source.encode('utf-8')
    content = base64.b64encode(source).decode('utf-8')

물론 사용할 수 있습니다.base64모듈, 당신은 또한 사용할 수 있습니다.codecs이진 인코딩(비표준 및 비텍스트 인코딩을 의미함)을 위한 모듈(오류 메시지에서 언급됨).

예:

import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")

이는 대용량 데이터를 연결하여 압축 및 json 직렬화 가능한 값을 얻을 수 있으므로 유용할 수 있습니다.

my_large_bytes = my_bytes * 10000
codecs.decode(
    codecs.encode(
        codecs.encode(
            my_large_bytes,
            "zip"
        ),
        "base64"),
    "utf8"
)

참조:

다음 코드를 사용합니다.

import base64

#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ") 

if(int(welcomeInput)==1 or int(welcomeInput)==2):
    #Code to Convert String to Base 64.
    if int(welcomeInput)==1:
        inputString= raw_input("Enter the String to be converted to Base64:") 
        base64Value = base64.b64encode(inputString.encode())
        print "Base64 Value = " + base64Value
    #Code to Convert Base 64 to String.
    elif int(welcomeInput)==2:
        inputString= raw_input("Enter the Base64 value to be converted to String:") 
        stringValue = base64.b64decode(inputString).decode('utf-8')
        print "Base64 Value = " + stringValue

else:
    print "Please enter a valid value."

Base64 인코딩은 이진 데이터를 6비트 문자 표현으로 변환하여 이진 데이터를 ASCII 문자열 형식으로 변환하는 프로세스입니다.Base64 인코딩 방법은 ASCII(일반 텍스트) 형식으로 데이터를 전송하도록 설계된 시스템을 통해 이미지 또는 비디오와 같은 이진 데이터를 전송할 때 사용됩니다.

이해 및 작업에 대한 자세한 내용은 이 링크를 참조하십시오.base64부호화

구현을 원하는 사용자를 위한base64이해를 위해 처음부터 인코딩, 여기 문자열을 인코딩하는 코드가 있습니다.base64.

인코더파이의

#!/usr/bin/env python3.10

class Base64Encoder:

    #base64Encoding maps integer to the encoded text since its a list here the index act as the key
    base64Encoding:list = None

    #data must be type of str or bytes
    def encode(data)->str:
        #data = data.encode("UTF-8")

        if not isinstance(data, str) and not isinstance(data, bytes):
            raise AttributeError(f"Expected {type('')} or {type(b'')} but found {type(data)}")

        if isinstance(data, str):
            data = data.encode("ascii")

        if Base64Encoder.base64Encoding == None:
            #construction base64Encoding
            Base64Encoder.base64Encoding = list()
            #mapping A-Z
            for key in range(0, 26):
                Base64Encoder.base64Encoding.append(chr(key + 65))
            #mapping a-z
            for key in range(0, 26):
                Base64Encoder.base64Encoding.append(chr(key + 97))
            #mapping 0-9
            for key in range(0, 10):
                Base64Encoder.base64Encoding.append(chr(key + 48))
            #mapping +
            Base64Encoder.base64Encoding.append('+')
            #mapping /
            Base64Encoder.base64Encoding.append('/')


        if len(data) == 0:
            return ""
        length=len(data)

        bytes_to_append = -(length%3)+(3 if length%3 != 0 else 0)
        #print(f"{bytes_to_append=}")
        binary_list = []
        for s in data:
            ascii_value = s
            binary = f"{ascii_value:08b}" 
            #binary = bin(ascii_value)[2:]
            #print(s, binary, type(binary))
            for bit in binary:
                binary_list.append(bit)
        length=len(binary_list)
        bits_to_append = -(length%6) + (6 if length%6 != 0 else 0)
        binary_list.extend([0]*bits_to_append)

        #print(f"{binary_list=}")

        base64 = []

        value = 0
        for index, bit in enumerate(reversed(binary_list)):
            #print (f"{bit=}")
            #converting block of 6 bits to integer value 
            value += ( 2**(index%6) if bit=='1' else 0)
            #print(f"{value=}")
            #print(bit, end = '')
            if (index+1)%6 == 0:
                base64.append(Base64Encoder.base64Encoding[value])
                #print(' ', end="")

                #resetting value
                value = 0
                pass
        #print()

        #padding if there is less bytes and returning the result
        return ''.join(reversed(base64))+''.join(['=']*bytes_to_append)

test Encoder.파이의

#!/usr/bin/env python3.10

from encoder import Base64Encoder

if __name__ == "__main__":
    print(Base64Encoder.encode("Hello"))
    print(Base64Encoder.encode("1 2 10 13 -7"))
    print(Base64Encoder.encode("A"))

    with open("image.jpg", "rb") as file_data:
        print(Base64Encoder.encode(file_data.read()))

출력:

$ ./testEncoder.py 
SGVsbG8=
MSAyIDEwIDEzIC03
QQ==

언급URL : https://stackoverflow.com/questions/23164058/how-to-encode-text-to-base64-in-python

반응형