Ahmad Hammoudeh
Update app.py
daea1e5
raw
history blame
7.38 kB
import gradio as gr
import os
os.system('!pip install pycryptodome -q')
from datetime import datetime
import random
import math
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import rsa
import string
def seedx(path , User_passcode=0, N_days=1, encryption_difficulty = 2**10):
try:
with open(path +'indx.txt') as f:
old_day_index = int(f.read())
except:
old_day_index = 0
print('no old index was found')
timestamp = datetime.timestamp(datetime.now())
#total number of days since unix time
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 hours
day_index = math.floor(days_span/N_days)
seed = int(day_index**2 + User_passcode)
if day_index == old_day_index:
with open('prvt.pem', 'rb') as file:
key_data = file.read()
privateKey = rsa.PrivateKey.load_pkcs1(key_data)
with open('pblc.pem', 'rb') as file:
key_data = file.read()
publicKey = rsa.PublicKey.load_pkcs1(key_data)
else:
publicKey, privateKey = rsa.newkeys(encryption_difficulty)
old_day_index = day_index
#save in a folder
with open(path +'indx.txt', 'w') as f:
f.write(str(old_day_index))
with open(path +'prvt.pem', 'w') as f:
f.write(privateKey.save_pkcs1().decode('utf-8'))
with open(path +'pblc.pem', 'w') as f:
f.write(publicKey.save_pkcs1().decode('utf-8'))
return {'seed':seed,'publicKey': publicKey, 'privateKey': privateKey}
def AES_encrypt(User_message,seed, publicKey,encoding = 1, padding = 30):
#number conversion to encrypt non-english content
User_message_numbered = (int.from_bytes(bytes(User_message, 'utf-16'), "big"))
#padding
front_padding = ''.join(random.choices(string.digits, k=padding)) #string.ascii_lowercase +
back_padding = ''.join(random.choices(string.digits, k=padding)) #string.ascii_lowercase +
msg = front_padding + str(User_message_numbered) + back_padding
msg_len =len(msg) #total number of charachters in the msg
permutation_list = list(range(0,msg_len))
random.seed(seed)
random.shuffle(permutation_list)
shffled_msg_list = [msg[i] for i in permutation_list]
shffled_msg = ''.join(shffled_msg_list)
#print(shffled_msg)
encMessage = AESCipher(str(publicKey.n)).encrypt(shffled_msg)
if encoding == 0:
encMessage_int = encMessage
elif encoding == 1:
encMessage_int = encMessage.decode('utf-16')
else:
encMessage_int = int.from_bytes(encMessage, "big")
return encMessage_int
class AESCipher(object):
def __init__(self, key):
self.bs = AES.block_size
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw.encode()))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return AESCipher._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def invert_perm_list(p):
return [p.index(l) for l in range(len(p))]
def AES_decrypt(encMessage,seed,publicKey, encoding = 1, encryption_difficulty = 2**10, padding = 30):
if encoding == 0:
encMessage_byte = encMessage
elif encoding == 1:
encMessage_byte = encMessage.encode('utf-16')
else:
encMessage_byte = encMessage.to_bytes((encMessage.bit_length() + 7) // 8, "big")
decMessage = AESCipher(str(publicKey.n)).decrypt(encMessage_byte)
decMessage_len =len(decMessage) #total number of charachters in the msg
permutation_list = list(range(0,decMessage_len))
random.seed(seed)
random.shuffle(permutation_list)
inverted_permutation_list = invert_perm_list(permutation_list)
recovered_list = [decMessage[i] for i in inverted_permutation_list]
recovered_msg_i_pad = ''.join(recovered_list)
recovered_msg_i = int(recovered_msg_i_pad[padding:-padding])
recovered_msg = recovered_msg_i.to_bytes((recovered_msg_i.bit_length() + 7) // 8, "big").decode("utf-16")
return recovered_msg
def Encrypt_msg(User_message,user_password,path):
User_passcode = (int.from_bytes(bytes(str(user_password), 'utf-8'), "little"))
Num_dict_enc = seedx(path, User_passcode)
encMessage_i = AES_encrypt(User_message,Num_dict_enc['seed'], Num_dict_enc['publicKey'],encoding = 1, padding = 30)
#print(encMessage_i)
return encMessage_i
def Decrypt_msg(encMessage,user_password,path):
User_passcode = (int.from_bytes(bytes(str(user_password), 'utf-8'), "little"))
Num_dict_enc = seedx(path, User_passcode)
recovered_msg = AES_decrypt(encMessage,Num_dict_enc['seed'], Num_dict_enc['publicKey'], encoding = 1, encryption_difficulty = 2**10, padding = 30)
#print(recovered_msg)
return recovered_msg
def Encrypt_users_txt(Txt):
encMessage = Encrypt_msg(User_message=Txt,user_password='',path='')
return encMessage
def Decrypt_users_txt(input_parameters):
Txt = input_parameters[0]
user_password = input_parameters[1]
encMessage = Decrypt_msg(encMessage=Txt,user_password=user_password,path='')
return encMessage
#result_button_encrypt = gr.Button('Encrypt')
#result_button_encrypt.click(greet, inputs = "text", outputs = "text")
#iface = gr.Interface(fn=greet, inputs="text", outputs="text")
#iface.launch()
with gr.Blocks() as demo:
#gr.Markdown("<h1><center>Free Fast YouTube URL Video-to-Text using <a href=https://openai.com/blog/whisper/ target=_blank>OpenAI's Whisper</a> Model</center></h1>")
#gr.Markdown("<center>Enter the link of any YouTube video to generate a text transcript of the video and then create a summary of the video transcript.</center>")
#gr.Markdown("<center>Enter the link of any YouTube video to generate a text transcript of the video.</center>")
#gr.Markdown("<center><b>'Whisper is a neural net that approaches human level robustness and accuracy on English speech recognition.'</b></center>")
#gr.Markdown("<center>Transcription takes 5-10 seconds per minute of the video (bad audio/hard accents slow it down a bit). #patience<br />If you have time while waiting, drop a ♥️ and check out my <a href=https://www.artificial-intelligence.blog target=_blank>AI blog</a> (opens in new tab).</center>")
input_text = gr.Textbox(placeholder='Message', label='User message')
User_password = gr.Textbox(placeholder='Password', label='User password')
result_button_encrypt = gr.Button('Encrypt')
result_button_decrypt = gr.Button('Decrypt')
#vc_f0method = gr.Radio(label="Encrypt or Decrypt", choices=["Encrypt", "Decrypt"],value="Encrypt",interactive=True,)
output_text = gr.Textbox(placeholder='Output message', label='Encrypte')
result_button_encrypt.click(Encrypt_users_txt, inputs = input_text, outputs = output_text)
result_button_decrypt.click(Decrypt_users_txt, inputs = [input_text, User_password], outputs = output_text)
demo.queue(default_enabled = True).launch(debug = True)