【发布时间】:2022-01-03 08:35:54
【问题描述】:
我有一个想法,用 python 的伪随机生成器生成的字节加密字符串,本质上创建一个一次性垫,这应该是安全的,问题是与随机生成器的播种有关以创建垫.
假设你不知道seed_key,随机生成器的种子冲突的可能性有多大?
#!/usr/bin/env python3
### IMPORTS ###
import random
from base91 import encode
from os import urandom
### CLASS DEFINITITON ###
class SeedPad:
""" Encrypts a string with a one time pad generated by the pseudo random generator using a seed """
def __init__(self, plain_text=None, cipher_text=None, seed_key=None):
self.__plain_text = plain_text
self.__cipher_text = cipher_text
self.__seed_key = seed_key
### PROPERTY GETTERS ###
@property
def plain_text(self):
return self.__plain_text
@property
def cipher_text(self):
return self.__cipher_text
@property
def seed_key(self):
return self.__seed_key
### PROPERTY SETTERS ###
@plain_text.setter
def plain_text(self, plain_text):
self.__plain_text = plain_text
@cipher_text.setter
def cipher_text(self, cipher_text):
self.__cipher_text = cipher_text
@seed_key.setter
def seed_key(self, seed_key):
self.__seed_key = seed_key
### METHODS ###
def encrypt(self):
"""
takes a plain text string and returns a cipher_text as a hex string
seed_key and plain_text must be set to use this method
"""
if self.__plain_text is None:
raise ValueError("plain_text is not set.")
if self.__seed_key is None:
self.__keygen()
if type(self.__plain_text) != bytes:
self.__plain_text = self.__plain_text.encode()
random.seed(self.__seed_key)
self.__cipher_text = ""
for i in self.__plain_text:
self.__cipher_text += f"{i ^ random.randint(0,255):02x}"
return self.__cipher_text
def decrypt(self):
if self.__cipher_text is None:
raise ValueError("cipher_text is not set.")
if self.__seed_key is None:
raise ValueError("seed_key is not set.")
random.seed(self.__seed_key)
# Convert hex string to bytes
cipher_bytes = bytes.fromhex(self.cipher_text)
self.__plain_text = ""
for byte in cipher_bytes:
self.__plain_text += chr(byte ^ random.randint(0, 255))
return self.__plain_text
def __keygen(self):
self.__seed_key = encode(urandom(16))
print("Random seed: ", self.__seed_key)
if __name__ == "__main__":
from flag import flag, secret_key
crypter = SeedPad(plain_text=flag, seed_key=secret_key)
print(crypter.encrypt())
【问题讨论】:
-
Stack Overflow 不是代码审查或评论网站。您也许可以通过Code Review 或Information Security 获得更多帮助,但请确保您参加他们的导览并阅读他们的帮助中心首先 以确保您的问题切题。
-
谢谢,我早该知道,可能应该在我受到负面声誉之前撤掉这篇文章
-
当您创建密文时,您在该过程中使用随机整数,但我看不到您将这些随机整数存储在哪里,或者我看不到这些随机整数是从关键,所以我很困惑你如何在创建数据后解密数据,因为它是使用随机数创建的,然后被丢弃?
-
@hostingutilities.com 他们使用种子来生成相同的值。
-
在解密算法结束时,您应该将
self.__seed_key设置回None。使用一次性密匙加密算法,如果一个人掌握了两条使用相同密钥加密的消息,他们将能够解密这些消息的内容。