【问题标题】:"binascii.Error: Incorrect padding" when making an encrypted password制作加密密码时出现“binascii.Error:不正确的填充”
【发布时间】:2021-12-27 19:59:42
【问题描述】:
from cryptography.fernet import Fernet

"""
def write_key():
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key.file.write(key)"""

def load_key():
    file = open("key.key", "rb")
    key = file.read()
    return key

m_pwd = input("what is the master password? ")
key = load_key() + m_pwd.encode() 
fer = Fernet(key)

def view():
    with open("passwords.txt", 'r', encoding = "utf-8") as f:
        for line in f.readlines():
            data = line.rstrip()
            user, passw = data.split("|")
            print ("User:", user, ", Password:", 
                    fer.decrypt(passw.encode()))

def add():
    name = input("Account Name: ")
    password = input("Password: ")
    with open("passwords.txt", 'a', encoding = "utf-8") as f:
        f.write(name + "|" + str(fer.encrypt(password.encode()) + "\n"))

while True:
    mode = input("would you like to add a new password or view existing ones (view, add), press q to quit? ").lower()
    if mode == "q":
        break

    elif mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("invalid mode")
        continue
    fer = Fernet(key)
    key = base64.urlsafe_b64decode(key)
  File "C:\Users\samsw\AppData\Local\Programs\Python\Python310\lib\base64.py", line 133, in urlsafe_b64decode
    return b64decode(s)
  File "C:\Users\samsw\AppData\Local\Programs\Python\Python310\lib\base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding```



当我尝试输入任何内容来解密文件时,它会引发“binascii.Error”,我对 Python 还是很陌生,我不确定为什么会一直发生这种情况。如果有人有任何建议(或者更好的是能够修复代码),请回复:)

【问题讨论】:

  • 请显示完整的回溯
  • 我的错!刚刚添加。

标签: python passwords


【解决方案1】:

Fernet 的密钥必须是 32 字节的 base64 编码密钥:

>>> key = b"a"*32  # 32 bytes
>>> import base64
>>> key = base64.urlsafe_b64encode(key)
>>> cryptography.fernet.Fernet(key)
<cryptography.fernet.Fernet object at 0x0000017300541750>

您的密钥比应有的短或长,并且编码不正确。


编辑:我有fixed 密码学,所以错误会更清楚。感谢您提请我们注意 :-)

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2016-03-11
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2017-09-02
    • 2015-05-22
    • 2019-03-10
    相关资源
    最近更新 更多