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

时间:2019-06-21 12:44:29

标签: python encryption

我的目标是用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:\Anaconda3\python.exe C:/Users/AVIV/.PyCharmCE2019.1/config/scratches/test.py
Traceback (most recent call last):
  File "D:\Anaconda3\lib\site-packages\cryptography\fernet.py", line 87, in _get_unverified_token_data
    data = base64.urlsafe_b64decode(token)
  File "D:\Anaconda3\lib\base64.py", line 133, in urlsafe_b64decode
    return b64decode(s)
  File "D:\Anaconda3\lib\base64.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:\Anaconda3\lib\site-packages\cryptography\fernet.py", line 74, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "D:\Anaconda3\lib\site-packages\cryptography\fernet.py", line 89, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

是否有解决此错误的方法? 我的猜测是,问题在于与字节之间的解码和编码。我尝试对其进行解码/编码很多次,但总是以错误告终。 另外,我想这与填充有关,但是我不知道如何解决。 我当时在想,也许Fernet加密不适合我的项目目标,也许我应该使用其他加密/库?

1 个答案:

答案 0 :(得分:0)

您实际上并未将 encrypt 分配给变量,而是将 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 的输出将是您加密的 Nonce。