Python - 如何使用加密帖子在Bulletin Board Pattern中实现读者/编写者

时间:2011-06-16 05:50:13

标签: python encryption

我有以下课程:

class MessageBoard:

    def __init__(self):
        self.messages = []
        self.readers = {}

    def post(self, message):
        self.messages.append(message)

    def register_reader(self, reader):
        self.readers[reader.name] = reader.public_key


class Reader:

    def __init__(self, name, public_key, private_key):
        self.name = name
        self.public_key = public_key
        self.private_key = private_key

    def register_on_board(self, board):
        board.register_reader(self)

    def read(self, message):
        return self._decrypt(message)

    def _decrypt(self, message):
        #Unknown method using private_key


class Writer:

    def __init__(self):
        pass

    def write(self, message, board, intended_reader_name):
        public_key = board.readers[intended_reader_name]
        board.post(self._encrypt(message, public_key))

    def _encrypt(self, message, key_to_use):
        #Unknown method using public_key

如何在Writer()._encryptReader()._decrypt中实施公钥/私钥生成及其使用?

1 个答案:

答案 0 :(得分:2)

如果确实想要这样做(集中生成和存储私钥),请参阅下面的these instructions相关代码段以供参考:

>>> from Crypto.PublicKey import RSA
>>> from Crypto import Random
>>> random_generator = Random.new().read
>>> private_key = RSA.generate(1024, random_generator)
>>> public_key = private_key.publickey()
>>> enc_data = public_key.encrypt('abcdefgh', 32)
>>> private_key.decrypt(enc_data)
'abcdefgh'

但是,请记住除非我误解了你的申请的目的这是一种不安全的做法

我假设Reader实际上并不与Writer位于同一系统中 - 如果他们这样做,我认为没有任何理由使用PKI(不对称加密) )在任何情况下,当简单的对称AES加密就足够了。

如果我的假设是正确的,Reader应该如上所述生成私钥,而将公钥传递给Writerimport the key使用RSA.importKey - 很遗憾,您需要pyCrypto >= 2.1