简体   繁体   English

我将如何生成可重复的加密密钥?

[英]how would I generate a repeatable encryption key?

I need to sent my friend Bob the number 42, my code will use a pre-shared key generate a random number to encrypt the message (42) and decrypt it on Bobs end.我需要向我的朋友 Bob 发送数字 42,我的代码将使用预共享密钥生成一个随机数来加密消息 (42) 并在 Bob 端解密。 the only problem is, I have no clue how to generate a repeatable encryption key in python.唯一的问题是,我不知道如何在 python 中生成可重复的加密密钥。

You can use Crypto to encrypt a message using AES.您可以使用 Crypto 使用 AES 加密消息。

import hashlib, base64
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher():
    def __init__(self, key):
        self.private_key = hashlib.sha256(key.encode()).digest()
        self.bs = AES.block_size

    def encrypt(self, data):
        # generate public key
        public_key = Random.new().read(self.bs)

        # setup AES Cipher using public key and private key
        cipher = AES.new(self.private_key, AES.MODE_CBC, public_key)

        # enrpyt the data and convert to base64
        return base64.b64encode(public_key + cipher.encrypt(self.pad(data).encode()))

    def decrypt(self, enc):
        # convert encrypted data to base 64
        enc = base64.b64decode(enc)

        # get public key
        public_key = enc[:AES.block_size]

        # setup AES Cipher using public and private key
        cipher = AES.new(self.private_key, AES.MODE_CBC, public_key)

        # decrypt data using the public key
        return self.unpad(cipher.decrypt(enc[AES.block_size:])).decode("utf-8")

    def pad(self, s):
        # pads data so that it's a multiple of 16
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def unpad(self, s):
        # removes padding
        return s[:-ord(s[len(s)-1:])]

cipher = AESCipher("your secret key")

Here I encrypt some text, the public key with the encrypted text is joined and returned from the encrypt method, you can then send the returned text to Bob, to decrypt the text bob then just needs to run the decrypt method.这里我对一些文本进行加密,将加密文本的公钥加入并从encrypt方法返回,然后您可以将返回的文本发送给 Bob,对文本进行解密 Bob 只需运行decrypt方法。

>>> cipher.encrypt("your message")
b'HYfUkcd//CaRquG9AhReR8bJYdVQdcGWRAjcp9AstLs='
>>> output = cipher.encrypt("your message")
>>> output
b'RVTK7L7ZDw9DzvuXuj8zYPZJjBO/A0N3l5N1hp9LY6U='
>>> cipher.decrypt(output)
'your message'
>>> 

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

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