Created
November 9, 2015 16:30
-
-
Save 1Project/d3534cc4648d6541549d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sbox(binary): | |
# assert len(binary)=8 hz kak | |
i = int(binary[0]+binary[5], 2) # v1 vector | |
j = int(binary[1:5], 2) # v2 vector | |
sbox_table = \ | |
((14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7), | |
(0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8), | |
(4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0), | |
(15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13)) | |
return(sbox_table[i][j]) | |
def chunks(l, n): | |
""" Yield successive n-sized chunks from l. | |
""" | |
for i in range(0, len(l), n): | |
yield l[i:i+n] | |
def des_encrypt(text, key, rounds=1): | |
text_ascii = [bin(ord(c) % 848) for c in text] | |
key = list(chunks(key, 6)) | |
# таблица перестановок | |
perm = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, | |
4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, | |
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, | |
53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] | |
text_ascii = ''.join([str(e) for e in text_ascii]) | |
print('исходный текст в бинарном формате (ascii) ', text_ascii) | |
text_permutated = list() | |
for i in perm: | |
text_permutated.insert(i, text_ascii[i-1]) | |
text_permutated = ''.join(text_permutated) | |
print('текст после перестановки ', text_permutated) | |
l_block = text_ascii[:len(text_ascii)//2] | |
print('левая половина ', l_block) | |
r_block = text_ascii[len(text_ascii)//2:] | |
print('правая половина ', r_block) | |
# разбиваем блок R на 4-битовые подблоки | |
r_block_4 = list(chunks(r_block, 4)) | |
# расширяем правый блок | |
r_block_6 = [] | |
for i in range(0, len(r_block_4)): | |
first = r_block_4[i-1][3] | |
last = r_block_4[(i+1) % len(r_block_4)][0] | |
r_block_6.append(first+r_block_4[i]+last) | |
# r_block_6 сложение по модулю 2 ключа | |
def my_xor(a_list, b_list): | |
for a, b in zip(a_list, b_list): | |
y = int(a,2) ^ int(b,2) | |
yield ('{0:b}'.format(y)).zfill(len(a)) | |
xored_list = list(my_xor(r_block_6, key)) | |
# таблица перестановки S-box | |
# s_box() | |
# соединяем блоки R и L | |
# обратная перестановка | |
print(des_encrypt('АБВГДЕЖЗИ ', 'elelle')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment