简体   繁体   English

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

[英]How to encrypt and decrypt with variables in Python

My goal is to write a code in Python that do the following: 1.Generate a public key.我的目标是用 Python 编写执行以下操作的代码: 1.生成公钥。 2. Hash the public key. 2. 散列公钥。 3. Generate a random string. 3. 生成随机字符串。 4. Encrypt & decrypt the random string with the hashed public key. 4. 用散列的公钥加密和解密随机字符串。

This is the code I written:这是我写的代码:

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)

When I run it, I get the error:当我运行它时,我收到错误:

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

Is there a way to solve this error?有没有办法解决这个错误? My guess, is that the issue is with the decoding and encoding to/from bytes.我的猜测是,问题在于字节的解码和编码。 I tried to decode/encode it many times, but always ended up with an error.我多次尝试对其进行解码/编码,但总是以错误告终。 Also, I guess that it has an issue with the padding, but I couldn't figured how to solve it.另外,我猜它的填充有问题,但我不知道如何解决。 I was thinking, maybe the Fernet encryption isn't the right fit for the goals of my project, maybe I should use other encryption/library?我在想,也许 Fernet 加密不适合我的项目目标,也许我应该使用其他加密/库?

You are not actually assigning encrypt to a variable, you are sending in an encrypt function as the argument for the decrypt function.您实际上并没有将 encrypt 分配给变量,而是将 encrypt 函数作为解密函数的参数发送。 Make this change this at the end of your code:在代码末尾进行更改:

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)

The output for decrypted will be the Nonce that you encrypted. decrypted的输出将是您加密的 Nonce。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM