Data Encryption Standard: Difference between revisions

→‎{{header|Python}}: edit 32.11.18: removed the long message as there were issues with padding rsulting in wron encrypted message.
(→‎{{header|Python}}: edit 32.11.18: removed the long message as there were issues with padding rsulting in wron encrypted message.)
Line 1,296:
 
=={{header|Python}}==
 
{{incorrect|Python|encrypted should be c099... not ca57...}}
implemented like in the article linked in description. <br>
really good article btw
<lang Python>#!/usr/bin/python
#!/usr/bin/python
 
# Permutation tables and Sboxes
IP = (
Line 1,414 ⟶ 1,416:
22, 11, 4, 25
)
 
def process_input(msg, key, decrypt=False):
# only takes int values, not str
# no need for manual padding during encryption using python ints and bitshifts
 
if key.bit_length() > 64:
return -1
 
# split msg into 64-bit blocks
msg_blocks = []
if msg.bit_length() > 64:
while msg.bit_length() > 0:
block = msg & (2**64-1)
msg_blocks.append(block)
msg >>= 64
else:
msg_blocks.append(msg)
 
# encrypt each block seperately using key (ECB-mode)
cipher_blocks = []
for block in msg_blocks:
if decrypt:
cipher_block = encrypt(block, key, decrypt=True)
else:
cipher_block = encrypt(block, key)
cipher_blocks.append(cipher_block)
 
# concatenate blocks to one int again
cipher_msg = 0
for block in cipher_blocks:
cipher_msg <<= 64
cipher_msg += block
 
return cipher_msg
def encrypt(msg, key, decrypt=False):
# only encrypt single blocks
assert isinstance(msg, int) and isinstance(key, int)
ifassert not msg.bit_length() > 64:
ifassert not key.bit_length() > 64:
 
# permutate by table PC1
Line 1,482 ⟶ 1,454:
 
return cipher_block
 
 
def round_function(Ri, Ki):
Line 1,557 ⟶ 1,528:
 
k = 0x0e329232ea6d0d73 # 64 bit
k2 = 0x133457799BBCDFF1
m = 0x8787878787878787
m2 = 0x0123456789ABCDEF
m_long = 0x596F7572206C6970732061726520736D6F6F74686572207468616E20766173656C696E650D0A
 
def prove(key, msg):
print('key: {:x}'.format(key))
print('message: {:x}'.format(msg))
cipher_text = process_inputencrypt(msg, key)
print('encrypted: {:x}'.format(cipher_text))
plain_text = process_inputencrypt(cipher_text, key, decrypt=True)
print('decrypted: {:x}'.format(plain_text))
 
prove(k, m)
print('----------')
prove(kk2, m_longm2)
 
</lang>
{{Out}}
Note: This is just the algorithm for single 64-bit blocks. No padding or block chipher operation mode
<pre>key: e329232ea6d0d73
message: 8787878787878787
Line 1,578 ⟶ 1,552:
decrypted: 8787878787878787
----------
key: e329232ea6d0d73133457799bbcdff1
message: 123456789abcdef
message: 596f7572206c6970732061726520736d6f6f74686572207468616e20766173656c696e650d0a
encrypted: 85e813540f0ab405
encrypted: ca57d5c43d9ab744f2734b6d497cc0ca6c293d78d8ee1cbf51c50571f460c9f1088f68e9d7b9fb4a
decrypted: 123456789abcdef</pre>
decrypted: 596f7572206c6970732061726520736d6f6f74686572207468616e20766173656c696e650d0a</pre>
 
=={{header|REXX}}==