
28.01.2009, 19:47
|
|
Флудер
Регистрация: 12.08.2004
Сообщений: 3,791
Провел на форуме: 6490435
Репутация:
2290
|
|
Код:
def check_correct(string, alphabet):
"""Check string in alphabet"""
for c in string:
if c not in alphabet:
raise "Wrong data: found wrong characters"
def code(char, alphabet):
"""Return number of character in alphabet"""
return alphabet.find(char)
def shift_char(char1, char2, alphabet):
"""Shift character with the other one"""
c = code(char1, alphabet) + code(char2, alphabet)
if c > len(alphabet):
c -= len(alphabet)
return alphabet[c]
def unshift_char(char1, char2, alphabet):
"""Unshift character with the other one"""
c1 = code(char1, alphabet)
c2 = code(char2, alphabet)
if c1 < c2:
c1 += len(alphabet)
c = c1 - c2
return alphabet[c]
def encrypt(phrase, autokey, alphabet):
"""Encrypt data with autokey"""
check_correct(phrase, alphabet)
check_correct(autokey, alphabet)
key = autokey + phrase
encrypted = ""
for i in range(len(phrase)):
encrypted += shift_char(phrase[i], key[i], alphabet)
return encrypted
def decrypt(encrypted, autokey, alphabet):
"""Decrypt data with autokey"""
check_correct(encrypted, alphabet)
check_correct(autokey, alphabet)
key = autokey
for i in range(len(encrypted)):
key += unshift_char(encrypted[i], key[i], alphabet)
return key[len(autokey):]
Автоключ на питоне
|
|
|