Skip to content

Instantly share code, notes, and snippets.

@NaoY-2501
Last active January 23, 2021 09:12
Show Gist options
  • Select an option

  • Save NaoY-2501/7965c6c54bfbc0aa6908753ba35df658 to your computer and use it in GitHub Desktop.

Select an option

Save NaoY-2501/7965c6c54bfbc0aa6908753ba35df658 to your computer and use it in GitHub Desktop.
『Pythonでいかにして暗号を破るか』5章 アレンジ+練習問題回答
# 『Pythonでいかにして暗号を破るか』5章 シーザー暗号
# caesarCipher.pyを参考にしたシーザー暗号プログラム
class CaesarCipher:
def __init__(self, key: int, symbols: str):
self.key = key
self.symbols = symbols
def encrypt(self, message: str) -> str:
translated = ''
symbol_len = len(self.symbols)
for symbol in message:
if symbol in self.symbols:
symbol_index = self.symbols.find(symbol)
translated_index = self.key + symbol_index
if translated_index >= symbol_len:
# ラップアラウンド処理
translated_index -= symbol_len
translated += self.symbols[translated_index]
else:
translated += symbol
return translated
def decrypt(self, cipher: str) -> str:
translated = ''
symbol_len = len(self.symbols)
for symbol in cipher:
if symbol in self.symbols:
symbol_index = self.symbols.find(symbol)
translated_index = symbol_index - self.key
if translated_index < 0:
# ラップアラウンド処理
translated_index += symbol_len
translated += self.symbols[translated_index]
else:
translated += symbol
return translated
def make_symbols() -> str:
upper = ''
a_ord = ord('A')
for i in range(0, 26):
upper += chr(a_ord+i)
lower = upper.lower()
symbols = upper + lower + '1234567890' + ' !?.'
return symbols
symbols = make_symbols()
message = 'This is my secret message.'
key = 13
caesar_cipher = CaesarCipher(key=key, symbols=symbols)
cipher = caesar_cipher.encrypt(message=message)
print(message)
print(cipher)
plain = caesar_cipher.decrypt(cipher=cipher)
print(plain)
# 1
caesar = CaesarCipher(key=8, symbols=symbols)
message = '"You can show black is white by argument," said Filby, "but you will never convince me".'
cipher = caesar.encrypt(message=message)
print('--- 1-a ---')
print(message)
print(cipher)
print(caesar.decrypt(cipher=cipher))
caesar = CaesarCipher(key=21, symbols=symbols)
message = '1234567890'
cipher = caesar.encrypt(message=message)
print('--- 1-b ---')
print(message)
print(cipher)
print(caesar.decrypt(cipher=cipher))
# 2
caesar = CaesarCipher(key=2, symbols=symbols)
cipher = 'Kv?uqwpfu?rncwukdng?gpqwijB'
print('--- 2-a ---')
plain = caesar.decrypt(cipher)
print(cipher)
print(plain)
print(caesar.encrypt(message=plain))
caesar = CaesarCipher(key=22, symbols=symbols)
cipher = 'XCBSw88S18A1S 2SB41SE .8zSEwAS50D5A5x81V'
print('--- 2-b ---')
plain = caesar.decrypt(cipher)
print(cipher)
print(plain)
print(caesar.encrypt(message=plain))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment