CoolFace
Apppublic

Amould/Message-Encryption

sourceHugging Faceccupdated 3y agoView on Hugging Face
0likes
msg_encX.py137 linesDownload Raw Back to root
1import os2from datetime import datetime3import random4import math5import base646import hashlib7from Crypto import Random8from Crypto.Cipher import AES9import rsa10import string11 12encoding0 = int(os.environ['encoding'])13padding0 = int(os.environ['padding'])14encryption_difficulty0 = int(os.environ['encryption_difficulty'])15N_days0=int(os.environ['N_days'])16User_passcode0=int(os.environ['User_passcode'])17power0 = float(os.environ['power'])18#path0 = float(os.environ['path'])19#publicKey0 = int(os.environ['publicKey'])20 21 22def seedx(path , User_passcode=User_passcode0, N_days=N_days0, encryption_difficulty = encryption_difficulty0):23  try:24    with open(path +'indx.txt') as f:25      old_day_index = int(f.read())26  except:27    old_day_index = 028    print('no old index was found')29  #os.environ['old_day_index'] = str(old_day_index)30  timestamp = datetime.timestamp(datetime.now())31  #total number of days since unix time32  days_span = timestamp/math.factorial(6)/120 + 0.1#*random.random() #first time calculate the days since unix, thae latter randomize the time zone by up to ~7 hours33  day_index = math.floor(days_span/N_days)34  seed = int(day_index**power0 + User_passcode)35  if day_index == old_day_index:36#      with open('prvt.pem', 'rb') as file:37#        key_data = file.read()38#        privateKey = rsa.PrivateKey.load_pkcs1(key_data)39      with open('pblc.pem', 'rb') as file:40          key_data = file.read()41          publicKey = rsa.PublicKey.load_pkcs1(key_data)42  else:43      publicKey, privateKey = rsa.newkeys(encryption_difficulty)44      old_day_index = day_index45      #save in a folder46      with open(path +'indx.txt', 'w') as f:47        f.write(str(old_day_index))48      #with open(path +'prvt.pem', 'w') as f:49      #  f.write(privateKey.save_pkcs1().decode('utf-8'))50      with open(path +'pblc.pem', 'w') as f:51        f.write(publicKey.save_pkcs1().decode('utf-8'))52        53  return {'seed':seed,'publicKey': publicKey} #, 'privateKey': privateKey}54 55 56def AES_encrypt(User_message,seed, publicKey,encoding = encoding0, padding = padding0):57  #number conversion to encrypt non-english content58  User_message_numbered = (int.from_bytes(bytes(User_message, 'utf-16'), "big"))59  #padding60  front_padding = ''.join(random.choices(string.digits, k=padding)) #string.ascii_lowercase +61  back_padding = ''.join(random.choices(string.digits, k=padding)) #string.ascii_lowercase +62  msg = front_padding + str(User_message_numbered) + back_padding63  msg_len =len(msg) #total number of charachters in the msg64  permutation_list = list(range(0,msg_len))65  random.seed(seed)66  random.shuffle(permutation_list)67  shffled_msg_list = [msg[i] for i in permutation_list]68  shffled_msg = ''.join(shffled_msg_list)69  #print(shffled_msg)70  encMessage = AESCipher(str(publicKey.n)).encrypt(shffled_msg)71  if encoding == 0:72    encMessage_int = encMessage73  elif encoding == 1:74    encMessage_int = encMessage.decode('utf-16')75  else:76    encMessage_int = int.from_bytes(encMessage, "big")77  return encMessage_int78 79 80class AESCipher(object):81    def __init__(self, key):82        self.bs = AES.block_size83        self.key = hashlib.sha256(key.encode()).digest()84    def encrypt(self, raw):85        raw = self._pad(raw)86        iv = Random.new().read(AES.block_size)87        cipher = AES.new(self.key, AES.MODE_CBC, iv)88        return base64.b64encode(iv + cipher.encrypt(raw.encode()))89    def decrypt(self, enc):90        enc = base64.b64decode(enc)91        iv = enc[:AES.block_size]92        cipher = AES.new(self.key, AES.MODE_CBC, iv)93        return AESCipher._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')94    def _pad(self, s):95        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)96    @staticmethod97    def _unpad(s):98        return s[:-ord(s[len(s)-1:])]99 100def invert_perm_list(p):101    return [p.index(l) for l in range(len(p))]102 103def AES_decrypt(encMessage,seed,publicKey, encoding = encoding0, encryption_difficulty = encryption_difficulty0, padding = padding0):104  if encoding == 0:105    encMessage_byte = encMessage106  elif encoding == 1:107    encMessage_byte = encMessage.encode('utf-16')108  else:109    encMessage_byte = encMessage.to_bytes((encMessage.bit_length() + 7) // 8, "big")110  decMessage = AESCipher(str(publicKey.n)).decrypt(encMessage_byte)111  decMessage_len =len(decMessage) #total number of charachters in the msg112  permutation_list = list(range(0,decMessage_len))113  random.seed(seed)114  random.shuffle(permutation_list)115  inverted_permutation_list = invert_perm_list(permutation_list)116  recovered_list = [decMessage[i] for i in inverted_permutation_list]117  recovered_msg_i_pad = ''.join(recovered_list)118  recovered_msg_i = int(recovered_msg_i_pad[padding:-padding])119  recovered_msg = recovered_msg_i.to_bytes((recovered_msg_i.bit_length() + 7) // 8, "big").decode("utf-16")120  return recovered_msg121 122 123 124def Encrypt_msg(User_message,user_password,path=''):125    User_passcode = (int.from_bytes(bytes(str(user_password), 'utf-8'), "little"))126    Num_dict_enc = seedx(path, User_passcode)127    encMessage_i = AES_encrypt(User_message,Num_dict_enc['seed'], Num_dict_enc['publicKey'],encoding = encoding0, padding = padding0)128    #print(encMessage_i)129    return encMessage_i130 131 132def Decrypt_msg(encMessage,user_password,path=''):133    User_passcode = (int.from_bytes(bytes(str(user_password), 'utf-8'), "little"))134    Num_dict_enc = seedx(path, User_passcode)135    recovered_msg = AES_decrypt(encMessage,Num_dict_enc['seed'], Num_dict_enc['publicKey'], encoding = encoding0, encryption_difficulty = encryption_difficulty0, padding = padding0)136    #print(recovered_msg)137    return recovered_msg