D
D
Denis Titusov2014-07-10 14:38:50
Python
Denis Titusov, 2014-07-10 14:38:50

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)

In this case, the text is perfectly encrypted and decrypted.
But, if you expand the alphabet to 64 characters (add, for example, a period, a comma and a hyphen), then 7 bits are needed for encryption, and the text starts to be encrypted incorrectly, after which it is not decrypted.
How to implement reversible XOR encryption so that the ciphertext necessarily consists of a limited alphabet (say, 64 characters), and then succumbs to reverse decryption?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2014-07-10
@denis-titusov

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 question

Ask a Question

731 491 924 answers to any question