我有一个想法,用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())