如何在 Python 中使用变量进行加密和解密



我的目标是用Python编写一个执行以下操作的代码:1.生成公钥。2. 对公钥进行哈希处理。3. 生成一个随机字符串。4. 使用散列公钥加密和解密随机字符串。

这是我编写的代码:

from Crypto.PublicKey import RSA
import random
import string
import hashlib
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def encrypt(plaintext, password):
   f = Fernet(base64.urlsafe_b64encode(
       PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000,
                  backend=default_backend()).derive(password.encode())))
   return f.encrypt(plaintext.encode()).decode()
def decrypt(ciphertext, password):
   f = Fernet(base64.urlsafe_b64encode(
       PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000,
                  backend=default_backend()).derive(password.encode())))
   return f.decrypt(ciphertext.encode()).decode()
def randomString(strlength = 16):   #Random code
   letters = string.ascii_letters
   return ''.join(random.choice(letters) for i in range(strlength))
key = RSA.generate(2048)  # Private key creation
code = 'nooneknows'
privatekey = key.exportKey(passphrase=code, pkcs=8)
publickey = key.publickey().exportKey()
result = hashlib.md5(publickey)  #Hashing the Publickey
publickey = result.digest()
Nonce=randomString()  # Creating Nonce
encrypt((str(Nonce)), password=(str(publickey)))  # Encrypting nonce with hashed pub.key
decrypt((str(encrypt)), password=(str(publickey)))
print("This is the decrption", encrypt)
print("This is the decrption", decrypt)

当我运行它时,我收到错误:

D:Anaconda3python.exe C:/Users/AVIV/.PyCharmCE2019.1/config/scratches/test.py
Traceback (most recent call last):
  File "D:Anaconda3libsite-packagescryptographyfernet.py", line 87, in _get_unverified_token_data
    data = base64.urlsafe_b64decode(token)
  File "D:Anaconda3libbase64.py", line 133, in urlsafe_b64decode
    return b64decode(s)
  File "D:Anaconda3libbase64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:/Users/AVIV/.PyCharmCE2019.1/config/scratches/test.py", line 39, in <module>
    decrypt((str(encrypt)), password=(str(publickey)))
  File "C:/Users/AVIV/.PyCharmCE2019.1/config/scratches/test.py", line 21, in decrypt
    return f.decrypt(ciphertext.encode()).decode()
  File "D:Anaconda3libsite-packagescryptographyfernet.py", line 74, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "D:Anaconda3libsite-packagescryptographyfernet.py", line 89, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

有没有办法解决这个错误?我的猜测是,问题出在解码和编码到/从字节编码。我尝试多次解码/编码它,但总是以错误告终。另外,我想它的填充有问题,但我不知道如何解决它。我在想,也许Fernet加密不适合我的项目目标,也许我应该使用其他加密/库?

您实际上并没有将 encrypt 分配给变量,而是将加密函数作为解密函数的参数发送。在代码末尾进行此更改:

encrypted = encrypt((str(Nonce)), password=(str(publickey)))  # Encrypting nonce with hashed pub.key
decrypted = decrypt((str(encrypted)), password=(str(publickey)))
print("This is the encrypted", encrypted)
print("This is the decrypted", decrypted)

decrypted的输出将是您加密的随机数。

最新更新