如何在Python中将文本编码为base64

问题描述 投票:0回答:9

我正在尝试将文本字符串编码为 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

我该如何去做呢? (使用Python 3.4)

python python-3.x encoding base64
9个回答
159
投票

记住导入 base64 并且 b64encode 将字节作为参数。

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

33
投票

对于

py3
、base64
encode
decode
字符串:

import base64

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


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

31
投票

事实证明,这非常重要,足以获得它自己的模块...

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

17
投票

1) 这在 Python 2 中无需导入即可工作:

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

(虽然这在Python3中不起作用)

2)在Python 3中,你必须导入base64并执行base64.b64decode('...') - 也可以在 Python 2 中工作。


5
投票

看起来,即使在对

decode()
编码字符串调用
base64.b64decode
之后,也必须调用
base64
函数才能使用实际的字符串数据。因为永远不要忘记,它总是返回字节文字。

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

4
投票

兼容 py2 和 py3

import six
import base64

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

2
投票

虽然您当然可以使用

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"
)

参考资料:


0
投票

使用以下代码:

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."

0
投票

Base64 编码是将二进制数据转换为 ASCII 的过程 字符串格式,将二进制数据转换为6位字符 表示。二进制时使用Base64编码方法 数据(例如图像或视频)通过以下系统传输: 设计用于以纯文本(ASCII)格式传输数据。

请点击此链接,了解有关

base64
编码的理解和工作的更多详细信息。

对于那些为了理解而想要从头开始实现

base64
编码的人,这里是将字符串编码为
base64
的代码。

编码器.py

#!/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)

测试编码器.py

#!/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==
© www.soinside.com 2019 - 2024. All rights reserved.