Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Code

442 views
from sage.crypto.util import ascii_integer from sage.crypto.block_cipher.sdes import SimplifiedDES bin = BinaryStrings(); def encrypt(m, k): ct = []; iv = ZZ.random_element(256); n = 0; for a in m: if n==0: pt = bin.encoding(chr(int(str(bin.encoding(a)), 2)^^iv)); else: pt = bin.encoding(chr(int(str(bin.encoding(a)), 2)^^int(ct[n-1],2))); c = sdes.encrypt(list(pt), k); ct.append(''.join(str(i) for i in c)); n = n + 1; return [format(iv, '08b')] + ct; def decrypt(ct, k): pt = ''; n = 0; iv = int(str(ct[0]), 2); for c in ct[1:]: p = sdes.decrypt(list(bin(c)), k); if n==0: p = chr(int(''.join(str(i) for i in p), 2) ^^ iv); else: p = chr(int(''.join(str(i) for i in p), 2) ^^ int(ct[n], 2)); pt += p; n = n + 1; return pt; sdes = SimplifiedDES(); k = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]; m = 'Top Secret'; print "Message = ", m; ct = encrypt(m, k); print "IV = ", ct[0]; print "Ciphertext = ", ct[1:]; pt = decrypt(ct, k); print "Plaintext = ", pt;
Message = Top Secret IV = 11111001 Ciphertext = ['10010110', '01100001', '00010101', '11111000', '01011001', '10001011', '11010011', '10111000', '00101100', '11010010'] Plaintext = Top Secret