Answer the question
In order to leave comments, you need to log in
How to implement reversible XOR encryption based on a limited alphabet in Python?
There is a limited alphabet. Let's say it's letters and numbers. That is a total of 62 characters. In this case, 6 bits are enough for encryption.
There is a word to encrypt and a key.
# Составляем словарь
def form_dict():
alphabet = list(ascii_letters) + list(digits)
return dict([(i, alphabet[i]) for i in range(len(alphabet))])
# Разбираем слово и ключ
def encode_val(word):
d = form_dict()
return [k for c in word for k, v in d.items() if v == c]
# Шифруем слово:
def comparator(value, key):
return dict([(index, list(character))
for index, character in enumerate(zip(value, cycle(key)))])
def full_encode(value, key):
d = comparator(value, key)
l = len(form_dict())
return [(v[0] ^ v[1]) % l for v in d.values()]
def full_decode(value, key):
d = comparator(value, key)
l = len(form_dict())
return [(v[0] - v[1]) % l for v in d.values()]
#шифруем
word = 'habrahabrru'
key = 'occaZZion9'
print 'Слово: ' + word
print 'Ключ: ' + key
key_encoded = encode_val(key)
value_encoded = encode_val(word)
encoded_text = full_encode(value_encoded, key_encoded)
#пытаемся расшифровать
decoded = full_decode(encoded_text, key_encoded)
Answer the question
In order to leave comments, you need to log in
I wrote a version that should work for any alphabet. However, the following conditions must be met:
1) the size of the alphabet is a power of two;
2) the initial message and the key consist of characters of this alphabet.
On the other hand, if you need a limited alphabet to display or store in the database, then you can cast already encrypted text to it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question