• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python解码Fernet密钥

用户头像
it1352
帮助1

问题说明

我生成了几个Fernet密钥,并以str格式存储以供参考.现在,我需要将这些Fernet密钥以str格式编码为32个url安全的base64编码字节,以解密我的数据.

I have generated few fernet keys and stored in str format for reference. Now, I need to encode these fernet keys in str format to 32 url-safe base64-encoded bytes to decrypt my data.

from cryptography.fernet import Fernet as frt
keys=set()
keybin='keys'
keybin=open(keybin,'w')

for i in range(r.randint(5,14)):
 key=frt.generate_key()
 keys.add(key.decode())

for k in keys:
 keybin.write(str(k))
 keybin.write('\n')

我正在使用以下代码访问文件并解密 s

I'm using below code to access the file and decrypt s

 key=linecache.getline(cfile,x).encode()
 key=base64.b64encode(key)
 print(key)
 f=frt(key)
 token =f.decrypt(s.encode())

但是给我以下错误:

    "Fernet key must be 32 url-safe base64-encoded bytes."
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

正确答案

#1

在不使用base64编码密钥的情况下尝试您的代码,即:

Try your code without base64 encoding your key ie:

from cryptography.fernet import Fernet as frt

key=frt.generate_key()
s = "message"
print('input string: {0}'.format(s))
#key=base64.b64encode(key) #no need to do this
print('key: {0}, type: {1}'.format(key, type(key)))
f=frt(key)
token = f.encrypt(s.encode('utf-8')) #need to convert the string to bytes
print ('encrypted: {0}'.format(token))
output = f.decrypt(token)
output_decoded = output.decode('utf-8')
print ('decrypted: {0}'.format(output_decoded))

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkhak
系列文章
更多 icon
同类精品
更多 icon
继续加载