TypeError:需要一个类似字节的对象,而不是'str''xxx';'xxx'

时间:2019-12-29 04:13:27

标签: python python-3.x binary operating-system

当我尝试在二进制文件中打印新行时。 我得到这个错误。 错误:

Traceback (most recent call last):
  File "F:/PyCharm Python Works/OpenCity/cryptograph/key_creator.py", line 25, in <module>
    create_key('sairam')
  File "F:/PyCharm Python Works/OpenCity/cryptograph/key_creator.py", line 21, in create_key
    f1.write(os.linesep)
TypeError: a bytes-like object is required, not 'str'

key_creator.py

def create_key(x):
    import base64
    import os
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

    password_provided = str(x)
    password = password_provided.encode()
    salt = b'\xfb|\xe8\xe0\xe5\x9d\x11\xf5\xbc 8o\xbe<\xd9\x92'
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(password))
    f1 = open('keys.key', 'ab')
    f1.write(key)
    f1.write(os.linesep)
    f1.close()


create_key('sairam')

请帮助我。 预先感谢。

1 个答案:

答案 0 :(得分:1)

您的问题是,您正在尝试输入期望有字节的字符串。使用.encode()。以下内容对我有用,请问您还有其他问题吗?

def create_key(x):
    import base64
    import os
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

    password_provided = str(x)
    password = password_provided.encode()
    salt = b'\xfb|\xe8\xe0\xe5\x9d\x11\xf5\xbc 8o\xbe<\xd9\x92'
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(password))
    f1 = open('keys.key', 'ab')
    f1.write(key)
    f1.write(os.linesep.encode())
    f1.close()


create_key('sairam')