我正在嘗試創建一個加密系統,為此我將使用一個位元組陣列,我打算使用一個
random.Random(seed).shuffle(bytearray)
功能來加密資訊。
我在為解密反轉這個程序時遇到了麻煩,我嘗試了類似的東西(沒有用):
random.Random(1/seed).shuffle(encryptedbytearray)
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
您需要使用相同的種子來洗牌索引,以便您可以回溯原始位置。(列舉將允許您避免對該映射進行排序)
import random
def encrypt(decrypted,seed=4):
encrypted = decrypted.copy()
random.Random(seed).shuffle(encrypted)
return encrypted
def decrypt(encrypted,seed=4):
decrypted = encrypted.copy()
indexes = list(range(len(encrypted)))
random.Random(seed).shuffle(indexes)
for e,d in enumerate(indexes):
decrypted[d] = encrypted[e]
return decrypted
示例運行(使用字串列,但它適用于位元組陣列或任何其他型別的串列):
clearText = list('ABCDE')
encryptedText = encrypt(clearText)
print(encryptedText)
['D', 'E', 'A', 'C', 'B']
decryptedText = decrypt(encryptedText)
print(decryptedText)
['A', 'B', 'C', 'D', 'E']
如果您希望函式直接在陣列上“就地”作業(而不是回傳值),您可以像這樣撰寫它們:
def encrypt(decrypted,seed=4):
random.Random(seed).shuffle(encrypted)
def decrypt(encrypted,seed=4):
before = encrypted.copy()
indexes = list(range(len(encrypted)))
random.Random(seed).shuffle(indexes)
for e,d in enumerate(indexes):
encrypted[d] = before[e]
uj5u.com熱心網友回復:
打亂排序的范圍,以便我們可以將打亂的索引與未打亂的索引進行匹配。
x = list(range(len(s)))
random.Random(seed).shuffle(x)
對于 12345 的種子,這會產生[14, 15, 12, 3, 24, 16, 7, 22, 10, 2, 19, 4, 20, 17, 1, 21, 5, 25, 18, 8, 6, 11, 9, 0, 23, 13]. 這表示shuffled串列中第0個索引的值實際上在unshuffled串列的第14個索引中,第1個索引實際上是第15個unshuffled,以此類推。
然后將每個混洗后的索引與混洗后的值進行匹配,然后(根據索引)將其排序回未混洗的位置。
unshuffled = bytearray(c for i, c in sorted(zip(x, s)))
print(unshuffled)
完整示例:
import random
# setup
s = bytearray(b"abcdefghijklmnopqrstuvxwyz")
seed = 12345
random.Random(seed).shuffle(s)
# shuffle a sorted range, so that we can match the shuffled indicies to the unshuffled indicies
x = list(range(len(s)))
random.Random(seed).shuffle(x)
# match each shuffled index to the shuffled value, and then sort (based on the index) back into their unshuffled positions
unshuffled = bytearray(c for i, c in sorted(zip(x, s)))
print(unshuffled)
上面詳述的程序應該適用于任何混洗序列(例如串列),而不僅僅是位元組陣列。
這是在 crypto.se上對這個程序的更詳細解釋,涉及更多數學。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321524.html
下一篇:如何將鏈表轉換為陣列?
