python - urlsafe_b64decode:返回 binascii.a2b_base64(s)
问题描述
我正在cryptography
按照教程学习 python 。
这是代码:
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
BASE_DESTINATION = os.path.dirname(os.path.abspath(__file__))
KEY_DESTINATION = os.path.join(BASE_DESTINATION, 'keys/')
def generate_key_from_password(path = KEY_DESTINATION):
passwordProvided = str(input("Enter Password: ")) # enter your password
password = passwordProvided.encode()
salt = os.urandom(16)
# salt = b'aeroplane'
kdf = PBKDF2HMAC(
algorithm= hashes.SHA256(),
length= 32,
salt= salt,
iterations= 100_000,
backend = default_backend()
)
key = base64.urlsafe_b64decode(kdf.derive(password)) # generated successed!
print("key: ", key)
generate_key_from_password()
当生成密钥时base64.urlsafe_b64decode(kdf.derive(password))
出现错误:binascii.Error: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4
我访问了很多答案,但没有什么真正适合我的代码。即:我在密码字符串中添加了'='
and'=='
来解决填充问题并通过计算添加填充password = str(password) + ('=' * len(password))
,但它也不起作用。
这是完整的错误:
Enter Password: pass
Traceback (most recent call last):
File "gfp.py", line 33, in <module>
generate_key_from_password()
File "gfp.py", line 28, in generate_key_from_password
key = base64.urlsafe_b64decode(kdf.derive(password)) # generated successed!
File "C:\Users\user\Anaconda3\envs\IRIS-REC\lib\base64.py", line 133, in urlsafe_b64decode
return b64decode(s)
File "C:\Users\user\Anaconda3\envs\IRIS-REC\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4
解决方案
解决方案由@Topaco 在评论中提供。(谢谢!)
问题出在语法上。
它应该base64.urlsafe_b64encode(...)
代替base64.urlsafe_b64decode(kdf.derive(password))
. 我已经多次看过代码,但不知何故我每次都错过了这个。
谢谢@topaco