Advertisement
Guest User

General block cipher implementation

a guest
Apr 24th, 2019
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.48 KB | None | 0 0
  1. #Block cipher
  2. #Feistel cipher
  3. import sys
  4. import os
  5. from _blake2 import blake2b
  6.  
  7. def f(R, K):
  8.     #Irreversible function
  9.     #R is integer
  10.     #K is character
  11.     K = ord(K)
  12.     size = len(bin(R)[2:])
  13.     #must return of the same size (bits) as input
  14.     var = (str(K)+str(R))
  15.     return int(blake2b(var.encode()).hexdigest()[::-1],16)^int('1'*size,2)
  16.  
  17. def xor(x, y):
  18.     return x^y
  19.  
  20.  
  21. def Feistel_enc(L0, R0, K):
  22.     for i in range(0,len(K)):
  23.         L_next = R0
  24.         R_next = xor(L0, f(R0, K[i]))
  25.         L0 = L_next
  26.         R0 = R_next
  27.     return R0,L0
  28.  
  29. def Feistel_dec(R0, L0, K):
  30.     "K is the same as enc"
  31.     K = K[::-1]
  32.     return Feistel_enc(R0, L0, K)
  33.  
  34. def split(string):
  35.     half = len(string)//2
  36.     return string[:half], string[half:]
  37.  
  38. char_adjust = 8
  39.  
  40. def message2int(message):
  41.     fin = []
  42.     for char in message:
  43.         value = str(ord(char))
  44.         adjust = char_adjust-len(value)
  45.         fin.append(('0'*adjust)+value)
  46.     fins = "".join(fin)
  47.     fini = int(fins)
  48.     return fini
  49.  
  50. def int2message(integer):
  51.     s = str(integer)
  52.     fin = []
  53.     counter = 0
  54.     finl = [s[i:i+char_adjust] for i in range(0, len(s), char_adjust)]
  55.     if len(finl[-1])<char_adjust:
  56.         s = (char_adjust-len(finl[-1]))*"0" + s
  57.         finl = [s[i:i+char_adjust] for i in range(0, len(s), char_adjust)]
  58.     finl = list(map(int,finl))
  59.     fin = list(map(chr,finl))
  60.     return "".join(fin)
  61.  
  62. def main(args):
  63.     if 'enc' in args:
  64.         enc = True
  65.         dec=False
  66.     elif 'dec' in args:
  67.         dec = True
  68.         enc=False
  69.     else:
  70.         dec=False
  71.         enc=False
  72.  
  73.     K = args[1]
  74.     if enc:
  75.         message = " ".join(args[2:])
  76.         m1,m2 = split(message)
  77.         m1i = message2int(m1)
  78.         m2i = message2int(m2)
  79.         l,r = Feistel_enc(m1i,m2i,K)
  80.         #cipher = int2message(int(str(l)+str(r)))
  81.         cipher = str(l)+str(r)
  82.         return cipher
  83.         print("Ciphertext:\n\n{}".format(cipher))
  84.     elif dec:
  85.         cipher = args[2]
  86.         c1,c2 = split(cipher)
  87.         #c1i = message2int(c1)
  88.         #c2i = message2int(c2)
  89.         c1i = int(c1)
  90.         c2i = int(c2)
  91.         l,r = Feistel_dec(c1i,c2i,K)
  92.         plain = int2message(l)+int2message(r)
  93.         #plain = int2message(int(str(l)+str(r)))
  94.         return plain
  95.         print("Plaintext:\n\n{}".format(plain))
  96.     else:
  97.         print("Something went wrong. Got\a\n{}".format(args))
  98.         input()
  99.  
  100. def helping():
  101.     print("Please use command line syntax:")
  102.     print("""
  103. fc enc KEY FILEPATH
  104.    Encryption
  105. fc dec KEY FILEPATH
  106.    Decryption
  107.  
  108. Files must be plaintext. No binary data.""")
  109.        
  110. if __name__ == "__main__":
  111.     args = sys.argv
  112.     if len(args)<3:
  113.         helping()
  114.         sys.exit()
  115.     #print(args)
  116.     args = args[1:]
  117.     if args[0]=="enc":
  118.         ext = ".enc"
  119.     elif args[0]=="dec":
  120.         ext = ".dec"
  121.     output = args[2]+ext
  122.     try:
  123.         with open(args[2], "r") as file:
  124.             text = file.read()
  125.     except OSError:
  126.         print("Failed to open file: ", args[2])
  127.         sys.exit()
  128.  
  129.     args[2] = text
  130.     result = main(args)
  131.  
  132.     if output[-8:-4]==".enc":
  133.         output = output[:-8]+output[-4:]
  134.     elif output[-8:-4]==".dec":
  135.         output = output[:-8]+output[-4:]
  136.    
  137.     try:
  138.         with open(output, "w+") as out:
  139.             out.write(result)
  140.     except OSError:
  141.         print("Failed to write to file: ", output)
  142.         sys.exit()
  143.     print("Executed successfully.")
  144.     sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement