Advertisement
deeperton

Vigenere

Mar 27th, 2012
3,680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import os, sys
  5.  
  6. ALPHA = range(256) # наш алфвит  -- вся ASCII-таблица.
  7.  
  8. KEY = 1 # 1 % 33
  9.  
  10. def get_symbol(filename):
  11.     with open(filename, 'rb') as f:
  12.         while True:
  13.             b = f.read(1)
  14.             if b:
  15.                 yield b
  16.             else:
  17.                 break
  18.  
  19. def _key():
  20.     while True:
  21.         for k in ALPHA:
  22.             yield k
  23.         x = ALPHA.pop()  # ключ -- сдвиг алфавита на 1
  24.         ALPHA.insert(0, x)
  25.  
  26. _KEY = _key()
  27.  
  28. def vigenere(symbol, is_decode):
  29.     code = ord(symbol)
  30.     if is_decode:
  31.         new_symbol = (code - _KEY.next() + 256) % 256
  32.     else:
  33.         new_symbol = (code + _KEY.next()) % 256
  34.    
  35.     if new_symbol > 255:
  36.         new_symbol = abs(255 - new_symbol)
  37.     if new_symbol < 0:
  38.         new_symbol = abs(255 + new_symbol)
  39.  
  40.     return chr(new_symbol)
  41.  
  42. if __name__ == '__main__':
  43.  
  44.     filename = os.path.abspath(sys.argv[1])
  45.     decode = False
  46.     if len(sys.argv) > 2:
  47.         decode = sys.argv[2] == '-d'
  48.    
  49.     for ch in get_symbol(filename):
  50.         sys.stdout.write(vigenere(ch, decode))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement