
單代換密碼解密
在本章中,你可以瞭解到單代換密碼的簡單實現,它按照單代換密碼技術使用的邏輯來顯示加密和解密後的資訊。這可以被視為一種替代的編碼方法。
程式碼
你可以使用一下程式碼來執行單代換密碼解密 -
import random chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \ 'abcdefghijklmnopqrstuvwxyz' + \ '0123456789' + \ ':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\' def generate_key(): """Generate an key for our cipher""" shuffled = sorted(chars, key=lambda k: random.random()) return dict(zip(chars, shuffled)) def encrypt(key, plaintext): """Encrypt the string and return the ciphertext""" return ''.join(key[l] for l in plaintext) def decrypt(key, ciphertext): """Decrypt the string and return the plaintext""" flipped = {v: k for k, v in key.items()} return ''.join(flipped[l] for l in ciphertext) def show_result(plaintext): """Generate a resulting cipher with elements shown""" key = generate_key() encrypted = encrypt(key, plaintext) decrypted = decrypt(key, encrypted) print 'Key: %s' % key print 'Plaintext: %s' % plaintext print 'Encrypted: %s' % encrypted print 'Decrypted: %s' % decrypted show_result('Hello World. This is demo of substitution cipher')
輸出
上述程式碼給你的輸出如上所示 -

廣告