base64 — Base16, Base32, Base64, Base85 데이터 인코딩

소스 코드: Lib/base64.py


This module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. It provides encoding and decoding functions for the encodings specified in RFC 4648, which defines the Base16, Base32, and Base64 algorithms, and for the de-facto standard Ascii85 and Base85 encodings.

The RFC 4648 encodings are suitable for encoding binary data so that it can be safely sent by email, used as parts of URLs, or included as part of an HTTP POST request. The encoding algorithm is not the same as the uuencode program.

There are two interfaces provided by this module. The modern interface supports encoding bytes-like objects to ASCII bytes, and decoding bytes-like objects or strings containing ASCII to bytes. Both base-64 alphabets defined in RFC 4648 (normal, and URL- and filesystem-safe) are supported.

레거시 인터페이스는 문자열로부터의 디코딩을 지원하지 않지만, 파일 객체에서 인코딩과 디코딩하는 함수를 제공합니다. Base64 표준 알파벳만 지원하며, RFC 2045에 따라 76자마다 개행 문자를 추가합니다. RFC 2045 지원을 원한다면 아마도 대신 email 패키지를 보고 싶을 것입니다.

버전 3.3에서 변경: ASCII 전용 유니코드 문자열은 이제 최신 인터페이스의 디코딩 함수가 받아들입니다.

버전 3.4에서 변경: 모든 바이트열류 객체는 이제 이 모듈의 모든 인코딩과 디코딩 함수가 받아들입니다. Ascii85/Base85 지원이 추가되었습니다.

최신 인터페이스는 다음과 같은 것들을 제공합니다:

base64.b64encode(s, altchars=None)

Base64를 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

Optional altchars must be a bytes-like object of length 2 which specifies an alternative alphabet for the + and / characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.

May assert or raise a ValueError if the length of altchars is not 2. Raises a TypeError if altchars is not a bytes-like object.

base64.b64decode(s, altchars=None, validate=False)

Base64로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the + and / characters.

s가 잘못 채워지면(padded) binascii.Error 예외가 발생합니다.

validateFalse(기본값)면, 일반 base-64 알파벳도 대체 알파벳도 아닌 문자는 채우기(padding) 검사 전에 버려집니다. validateTrue면, 입력에 이 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

For more information about the strict base64 check, see binascii.a2b_base64()

May assert or raise a ValueError if the length of altchars is not 2.

base64.standard_b64encode(s)

표준 Base64 알파벳을 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.standard_b64decode(s)

표준 Base64 알파벳을 사용하여 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

base64.urlsafe_b64encode(s)

표준 Base64 알파벳에서 + 대신 -를, / 대신 _를 사용하도록 대체한 URL과 파일 시스템에서 안전한 알파벳을 사용하여 바이트열류 객체 s를 인코딩하고, 인코딩된 bytes를 반환합니다. 결과에는 여전히 =가 포함될 수 있습니다.

base64.urlsafe_b64decode(s)

표준 Base64 알파벳에서 + 대신 -를, / 대신 _를 사용하도록 대체한 URL과 파일 시스템에서 안전한 알파벳을 사용하여 바이트열류 객체나 ASCII 문자열 s를 디코딩하고, 디코딩된 bytes를 반환합니다.

base64.b32encode(s)

Base32를 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.b32decode(s, casefold=False, map01=None)

Base32로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

선택적 casefold는 소문자 알파벳을 입력으로 사용할 수 있는지를 지정하는 플래그입니다. 보안을 위해, 기본값은 False입니다.

RFC 4648 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input.

s가 잘못 채워졌거나(padded) 입력에 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

base64.b32hexencode(s)

Similar to b32encode() but uses the Extended Hex Alphabet, as defined in RFC 4648.

버전 3.10에 추가.

base64.b32hexdecode(s, casefold=False)

Similar to b32decode() but uses the Extended Hex Alphabet, as defined in RFC 4648.

This version does not allow the digit 0 (zero) to the letter O (oh) and digit 1 (one) to either the letter I (eye) or letter L (el) mappings, all these characters are included in the Extended Hex Alphabet and are not interchangeable.

버전 3.10에 추가.

base64.b16encode(s)

Base16을 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.b16decode(s, casefold=False)

Base16으로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

선택적 casefold는 소문자 알파벳을 입력으로 사용할 수 있는지를 지정하는 플래그입니다. 보안을 위해, 기본값은 False입니다.

s가 잘못 채워졌거나(padded) 입력에 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

base64.a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

Ascii85를 사용하여 바이트열류 객체 b를 인코딩하고 인코딩된 bytes를 반환합니다.

foldspaces는 ‘btoa’ 가 지원하듯이 4개의 연속된 스페이스 (ASCII 0x20) 대신 특수한 짧은 시퀀스 ‘y’ 를 사용하는 선택적 플래그입니다. 이 기능은 “표준” Ascii85 인코딩에서 지원되지 않습니다.

wrapcol은 출력에 줄 바꿈 (b'\n') 문자가 추가되어야 하는지를 제어합니다. 이것이 0이 아니면, 각 출력 줄의 길이는 이 문자 수를 넘지 않습니다.

pad는 인코딩하기 전에 입력이 4의 배수로 채워졌는지를 제어합니다. btoa 구현은 항상 채운다는 것에 유의하십시오.

adobe는 인코딩된 바이트 시퀀스가 Adobe 구현에서 사용되는 <~~>로 프레임화되는지를 제어합니다.

버전 3.4에 추가.

base64.a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\x0b')

Ascii85로 인코딩된 바이트열류 객체나 ASCII 문자열 b를 디코딩하고 디코딩된 bytes를 반환합니다.

foldspaces는 짧은 시퀀스 ‘y’ 를 4개의 연속 된 스페이스(ASCII 0x20)에 대한 축약으로 받아들여야 하는지를 지정하는 플래그입니다. 이 기능은 “표준” Ascii85 인코딩에서 지원되지 않습니다.

adobe는 입력 시퀀스가 Adobe Ascii85 형식인지(즉 <~ 와 ~> 로 프레임화되었는지)를 제어합니다.

ignorechars는 입력에서 무시할 문자가 포함된 바이트열류 객체나 ASCII 문자열이어야 합니다. 여기에는 공백 문자만 포함되어야 하며, 기본적으로 ASCII의 모든 공백 문자가 포함됩니다.

버전 3.4에 추가.

base64.b85encode(b, pad=False)

base85를 사용하여 바이트열류 객체 b를 인코딩하고 (예를 들어 git 스타일 바이너리 diff에서 사용되는 것처럼), 인코딩된 bytes를 반환합니다.

pad가 참이면, 입력은 b'\0'으로 채워져서 길이는 인코딩 전에 4바이트의 배수가 됩니다.

버전 3.4에 추가.

base64.b85decode(b)

base85로 인코딩된 바이트열류 객체나 ASCII 문자열 b를 디코딩하고 디코딩된 bytes를 반환합니다. 필요하면, 채우기는 묵시적으로 제거됩니다.

버전 3.4에 추가.

레거시 인터페이스:

base64.decode(input, output)

바이너리 input 파일의 내용을 디코딩하고 결과 바이너리 데이터를 output 파일에 씁니다. inputoutput파일 객체여야 합니다. inputinput.readline()이 빈 바이트열 객체를 반환할 때까지 읽힙니다.

base64.decodebytes(s)

하나 이상의 base64 인코딩된 데이터 줄을 포함해야 하는 바이트열류 객체 s를 디코딩하고 디코딩된 bytes를 반환합니다.

버전 3.1에 추가.

base64.encode(input, output)

바이너리 input 파일의 내용을 인코딩하고 base64로 인코딩된 결과 데이터를 output 파일에 씁니다. inputoutput파일 객체여야 합니다. inputinput.read()이 빈 바이트열 객체를 반환할 때까지 읽힙니다. encode()RFC 2045(MIME)에 따라 출력의 76바이트마다 개행 문자(b'\n')를 삽입할 뿐만 아니라, 항상 출력이 개행 문자로 끝나도록 합니다.

base64.encodebytes(s)

임의의 바이너리 데이터를 포함할 수 있는 바이트열류 객체 s를 인코딩하고, RFC 2045 (MIME)에 따라 76바이트의 출력마다 개행(b'\n')이 삽입되고, 후행 개행이 붙은 base64 인코딩된 데이터를 포함하는 bytes를 반환합니다.

버전 3.1에 추가.

모듈 사용 예:

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

Security Considerations

A new security considerations section was added to RFC 4648 (section 12); it’s recommended to review the security section for any code deployed to production.

더 보기

모듈 binascii

ASCII에서 바이너리로, 바이너리에서 ASCII로의 변환이 포함된 지원 모듈.

RFC 1521 - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies

5.2 절, “Base64 Content-Transfer-Encoding” 은 base64 인코딩의 정의를 제공합니다.