開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Python計算機科学新教本 ―新定番問題を解決する探索アルゴリズム、k平均法、ニューラルネットワーク (David Kopec(著)、黒川 利明(翻訳)、オライリージャパン)の1章(簡単な問題)、1.7(練習問題)4の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
from unittest import TestCase, main
from secrets import token_bytes
from typing import Tuple
class OneTimePadTest(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test(self):
with open('sample4.png', 'rb') as f:
data: bytes = f.read()
dumm_key, original_key = encrypt(data)
result: bytes = decrypt(dumm_key, original_key)
with open('sample4_1.png', 'wb') as f:
f.write(result)
self.assertEqual(result, data)
def random_key(length: int) -> int:
return int.from_bytes(token_bytes(length), 'big')
def encrypt(original: bytes) -> Tuple[int, int]:
dummy_key: int = random_key(len(original))
original_key: int = int.from_bytes(original, 'big')
encrypted_key: int = original_key ^ dummy_key
return dummy_key, encrypted_key
def decrypt(key1: int, key2: int) -> bytes:
decrypted: int = key1 ^ key2
return decrypted.to_bytes((decrypted.bit_length() + 7) // 8, 'big')
if __name__ == '__main__':
main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample4.py . ---------------------------------------------------------------------- Ran 1 test in 0.001s OK $ diff sample4.png sample4_1.png $
0 コメント:
コメントを投稿