我必須制作一個輸入位元組生成器(randint默認為函式)的流密碼。我試圖以這種方式實作它,但我不想在輸出上有str() 表示,我想要位元組一個,所以b'\x.......').
我讀到bytes()整數串列給出了str表示,所以如果我回傳crypted,回圈傳遞給crypting_fn一次唯一的一個,我會解決我的“問題”嗎?如果沒有,你能解釋一下我該怎么做嗎?forbytes()int
import numpy as np
import numpy.random
class SC(object):
def __init__(self, key, prng=None, **kwargs):
if prng is None:
seed=None
rs = np.random.RandomState(seed)
def gen(seed):
rs = np.random.RandomState(seed)
while True:
yield rs.randint(0,255)
self.prng = rs.randint(0, 255)
else:
self.prng = prng(key, **kwargs)
def encrypt(self, plaintext):
return self.crypting_fn(plaintext)
def decrypt(self, ciphertext):
return self.crypting_fn(ciphertext)
def crypting_fn(self, text):
crypted=bytes([b^s for b, s in zip(text, range(self.prng))])
return crypted
message = 'hello world!'
key = 0x012345678
a = SC(key)
b = SC(key)
plaintextA = message.encode('utf-8')
ciphertext = a.encrypt(plaintextA)
plaintextB = b.decrypt(ciphertext)
print(plaintextA)
print(ciphertext)
print(plaintextB)
輸出是:
b'hello world!'
b'hdnok%qhzen*'
b'hello world!'
uj5u.com熱心網友回復:
您對 PRNG 的使用不正常;而不是生成位元組流,而是生成單個位元組,并且您的密鑰流只是 0、1、2、3 ......直到您遇到隨機位元組(所以當位元組很小時,您甚至沒有足夠的加密整個輸入)。
修復您的代碼以制作self.prng密鑰流生成器,而不是單個隨機位元組,并按原樣使用它,您將獲得看起來像您想要的東西:
import numpy as np
import numpy.random
class SC(object):
def __init__(self, key, prng=None, **kwargs):
if prng is None:
def gen(seed):
rs = np.random.RandomState(seed)
while True:
yield rs.randint(0, 255)
self.prng = gen(key) # Seed with provided "key", not None (which seeds from system random)
else:
# Without knowing what prng should be, I can't be sure this line is correct
# This is what you'd want if calling prng produced an iterator using the keystream
self.prng = prng(key, **kwargs)
def encrypt(self, plaintext):
return self.crypting_fn(plaintext)
def decrypt(self, ciphertext):
return self.crypting_fn(ciphertext)
def crypting_fn(self, text):
crypted=bytes([b^s for b, s in zip(text, self.prng)])
return crypted
message = 'hello world!'
key = 0x012345678
a = SC(key)
b = SC(key)
plaintextA = message.encode('utf-8')
ciphertext = a.encrypt(plaintextA)
plaintextB = b.decrypt(ciphertext)
print(plaintextA)
print(ciphertext)
print(plaintextB)
輸出:
b'hello world!'
b' \x9f\xc8\xec\xd4\\\xac\xf6\xae\xba\x9c\xeb'
b'hello world!'
在線嘗試!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/469022.html
