Example #1
0
  def create(self, tmpfilename, uploadfile):
	
	dbxuploadfilepath = self.cwd + "/" + uploadfile
	encfilename = tmpfilename + ".enc"

	'''generate 256-bit random key for symmetric encryption'''
	key = os.urandom(32)
	mycipherutil.encrypt_file(key, tmpfilename, encfilename)
	
	'''upload encrypted file'''
       	f = open(encfilename, 'rb')
	response = self.dbxclient.put_file(dbxuploadfilepath, f)
	f.close()

	'''put shadow file with owner'''
	shadowfile = dbxuploadfilepath + ".sdw"
	shadowfilelocal = tmpfilename + ".sdw"
     	'''Encrypt above key using owner's public key '''
     	cipher = PKCS1_OAEP.new(RSA.importKey(self.pbkey))
        encryptedkey = cipher.encrypt(key)
        dictentry = {self.username:base64.encodestring(encryptedkey)}
	with open(shadowfilelocal, "w+") as sdw:
	     		json.dump(dictentry, sdw)
	
	with open(shadowfilelocal, "r") as sdw:
	   	        response = self.dbxclient.put_file(shadowfile, sdw)
	   		#print(("Upload status:" ,  response))
	
	return
Example #2
0
  def open(self, filename, dnfile):

	'''expecting a relative path in filename'''
	dbxdwnfilepath = self.cwd + "/" + filename
	shadowfile = dbxdwnfilepath + ".sdw"

	with self.dbxclient.get_file(shadowfile) as df:
   		permtable = json.load(df)

   	if not self.username in  permtable.keys():
		print('You donot have permissions to do this operation')
		return
	else:

   		b64cipherkey = permtable[self.username]
   		encryptedkey = base64.decodestring(b64cipherkey)

		'''Decrypt above key using owner's private key '''
		cipher = PKCS1_OAEP.new(RSA.importKey(self.prkey))
		decryptedkey = cipher.decrypt(encryptedkey)

		f = open(dnfile, 'wb')
		with self.dbxclient.get_file(dbxdwnfilepath) as df:
		     f.write(df.read())

		f.close()
	
		'''decrypt'''
		decfilename = dnfile + ".dec"
		mycipherutil.decrypt_file(decryptedkey, dnfile, decfilename)
		print("File Downloaded")
 def reset(self, num_to_reset, on_index):
     i = on_index
     while i >= 0 and num_to_reset > 0:
         if self.targets[i].normal == True:
             self.targets[i] = Cipher(randint(1, 7), True, i)
         else:
             self.targets[i] = Cipher(randint(1, 7), False, i)
         i = i - 1
         num_to_reset = num_to_reset - 1
Example #4
0
 def __init__(self, encoded_str):
     self.letters = "abcdefghijklmnopqrstuvwxyz "
     self.c = Cipher(self.letters)
     self.best = self.c
     self.s = encoded_str
     print("About to build trigram map")
     self.t = TriGram()
     print("built trigram map")
     self.prior = 1
     self.p = self.get_prob_log(self.c)
     self.best_p = self.p
     print("Initial perm prob log is " + str(self.p))
Example #5
0
def connection():
    global conn
    s.listen(1)
    conn, address = s.accept()
    if type(address) == tuple:
        ChatWindow.config(state=NORMAL)
        ChatWindow.delete("0.0", END)
        ChatWindow.config(state=DISABLED)

    while 1:
        data = conn.recv(1024)

        message1 = data.decode("utf-8")

        message = Cipher.decrypt(message1, key=4)

        ChatWindow.config(state=NORMAL)

        ChatWindow.insert(INSERT, "client : " + message)
        ChatWindow.config(state=DISABLED)

        today = date.today()
        d = today.strftime("%B %d, %Y")
        t1 = datetime.now()
        t2 = t1.strftime("%H:%M:%S")

        cr.execute(
            '''INSERT INTO receive_message (date ,time, receive) VALUES(?,?,?)''',
            (d, t2, message1))
        db.commit()

    conn.close()
def receive():


    while 1:
        try:

            data = s.recv(1024)

            message1 = data.decode("utf-8")
            message = Cipher.decrypt(message1, key=4)


            ChatWindow.config(state = NORMAL)

            ChatWindow.insert(INSERT, "Server : " + message)
            ChatWindow.config(state =DISABLED )

            today = date.today()
            d = today.strftime("%B %d, %Y")
            t1 = datetime.now()
            t2 = t1.strftime("%H:%M:%S")

            cr.execute('''INSERT INTO receive_message (date ,time, receive) VALUES(?,?,?)''', (d, t2, message1))
            db.commit()


        except ConnectionResetError:
            t = messagebox.showinfo("MSG" , "SERVER OFFLINE")
            if t == "ok":
                root.destroy()
Example #7
0
def pr_sendMail_Plsql(p_sender, p_subject, p_Status_html, p_attchment_path,
                      To_List):
    try:
        p_recipents = To_List
        fp = open(p_Status_html)
        p_html_body = fp.read()
        fp.close()
        print_log('Start of pr_sendMail_Plsql')
        print_log('p_recipents', p_recipents)
        print_log('p_subject', p_subject)
        print_log('p_html_body length ', str(len(p_html_body)))
        p_attchment_path = '*'
        l_conn_str = Cipher.translateMessage(Key, conn_str, 'D')
        connection1 = cx_Oracle.connect(l_conn_str)
        cur1 = connection1.cursor()
        cur1.callproc(
            'pkg_send_mails.pr_send_mails',
            (p_sender, p_recipents, p_subject, p_html_body, p_attchment_path))
        cur1.close()
        connection1.close()
        print_log('completed pr_sendMail_Plsql')
    except:
        print_log('********* Failed in pr_sendMail_Plsql  **********')
        print_log('Unexpected error : {0}'.format(sys.exc_info()[0]))
        traceback.print_exc()
Example #8
0
def get_tests():
    tests = []
    import Cipher; tests += Cipher.get_tests()
    import Hash;   tests += Hash.get_tests()
    import PublicKey; tests += PublicKey.get_tests()
#    import Random; tests += Random.get_tests()
#    import Util;   tests += Util.get_tests()
    return tests
Example #9
0
def get_tests():
    tests = []
    import Cipher; tests += Cipher.get_tests()
    import Hash;   tests += Hash.get_tests()
    import PublicKey; tests += PublicKey.get_tests()
#    import Random; tests += Random.get_tests()
#    import Util;   tests += Util.get_tests()
    return tests
Example #10
0
def get_tests(config={}):
    tests = []
    import Cipher; tests += Cipher.get_tests(config=config)
    import Hash;   tests += Hash.get_tests(config=config)
    import Protocol; tests += Protocol.get_tests(config=config)
    import PublicKey; tests += PublicKey.get_tests(config=config)
    import Random; tests += Random.get_tests(config=config)
    import Util;   tests += Util.get_tests(config=config)
    return tests
Example #11
0
 def __init__(self, file_open='', password=''):
     super(PyPherDecipher, self).__init__()
     self.setupUi(self)
     self.cipher = Cipher.Cipher()
     self.file = file_open
     self.passw = password
     self.go_back.clicked.connect(self.back)
     self.save.clicked.connect(self.check)
     self.password.clicked.connect(self.set_new)
     self.delete_file.clicked.connect(self.delete)
Example #12
0
class CryptoGibbs:
    def __init__(self, encoded_str):
        self.letters = "abcdefghijklmnopqrstuvwxyz "
        self.c = Cipher(self.letters)
        self.best = self.c
        self.s = encoded_str
        print("About to build trigram map")
        self.t = TriGram()
        print("built trigram map")
        self.prior = 1
        self.p = self.get_prob_log(self.c)
        self.best_p = self.p
        print("Initial perm prob log is " + str(self.p))

    def set_prior(self, new_prior):
        self.prior = new_prior
        self.best_p = self.get_prob_log(self.best)
        self.p = self.get_prob_log(self.c)

    def get_prob_log(self, cipher):
        s = cipher.unscramble(self.s)
        fs = self.t.freqs(s, self.prior)
        return sum([log(f) for f in fs])

    def jump_for(self, iters):
        def rand_log():
            x = random.random()
            while x <= 0.0:
                x = random.random()
            return log(x)

        for i in range(iters):
            u = rand_log()
            candidate = self.c.rand_mutation()
            pc = self.get_prob_log(candidate)
            if (u < pc - self.p):
                self.c = candidate
                self.p = pc
            if (pc > self.best_p):
                self.best_p = pc
                self.best = candidate
        print("Current guess is " + self.c.unscramble(self.s))
        print("Best guess was " + self.best.unscramble(self.s))
 def __init__(self, x):
     #hex limit is how many hex ciphers (non-normal ciphers) are allowed
     self.hex_limit = int(x * .3333)
     self.targets = []
     self.hex_chance_upper = 5
     x_2 = int(x / 5)
     #The first several will be normal ciphers
     for i in range(0, int(x_2)):
         self.targets.append(Cipher(randint(1, 7), True, i))
     for i in range(x_2, x):
         #50% chance to make hex cipher if hex limit is not yet met
         if self.hex_limit > 0 and randint(0, self.hex_chance_upper) == 0:
             self.hex_limit -= 1
             self.targets.append(Cipher(randint(1, 7), False, i))
         else:
             self.targets.append(Cipher(randint(1, 7), True, i))
         self.hex_chance_upper -= 1
         if self.hex_chance_upper < 1:
             self.hex_chance_upper = 1
Example #14
0
def random_generator(seeds):
    np.random.seed(seeds)
    k = np.random.rand(seeds).tolist()
    for i in range(0, seeds):
        temp = int((k[i] * 100000) / 37)
        if (check_prime(temp)):
            if (check_even(temp)):
                temp = (temp * temp)
            else:
                temp = (temp * temp) / ((seeds - 1) * 100)
        else:
            if (check_even(temp)):
                temp = temp * (100 - seeds) / (seeds**2)
            else:
                temp = temp * (temp**(0.5)) / ((seeds - 1)**2)
        k[i] = int(temp)
    cyp = Cipher.chiper("Hi there.", round(stat.mean(k)))
    dcyp = Cipher.dechiper(cyp, round(stat.mean(k)))
    print(cyp, dcyp)
Example #15
0
def send_html_gmail(subject, htmlFileName):
    os.chdir(Globals.Work_dir_path)
    l_from = cp.translateMessage(Globals.Key, Globals.email_id, 'D')
    l_passwd = cp.translateMessage(Globals.Key, Globals.email_passwd, 'D')
    with open(htmlFileName,
              mode="rb") as message:  #open report html for reading
        msg = MIMEText(message.read(), 'html', 'html')  # create html message
    msg['Subject'] = subject
    msg['From'] = l_from
    msg['To'] = Globals.To_List
    proxy_host = 'www-proxy-idc.in.oracle.com'
    proxy_port = 80
    smtpObj = ProxySMTP(host='smtp.gmail.com',
                        port=587,
                        p_address=proxy_host,
                        p_port=proxy_port)
    smtpObj.starttls()
    smtpObj.login(l_from, l_passwd)
    smtpObj.send_message(msg)
    smtpObj.close()
Example #16
0
 def getCipher(self):
     if (self.v.get() == 1):
         return cp.VigenereStandard()
     elif (self.v.get() == 2):
         return cp.VigenereFull(matrixName="test")
     elif (self.v.get() == 3):
         return cp.VigenereAutoKey()
     elif (self.v.get() == 4):
         return cp.VigenereExtended()
     elif (self.v.get() == 5):
         return cp.Playfair()
     elif (self.v.get() == 6):
         return cp.SuperEncryption()
     elif (self.v.get() == 7):
         return cp.Affine()
     elif (self.v.get() == 8):
         return cp.Hill()
     elif (self.v.get() == 9):
         return cp.Enigma()
Example #17
0
def get_tests(config={}):
    tests = []
    import Cipher
    tests += Cipher.get_tests(config=config)
    import Hash
    tests += Hash.get_tests(config=config)
    import Protocol
    tests += Protocol.get_tests(config=config)
    import PublicKey
    tests += PublicKey.get_tests(config=config)
    import Random
    tests += Random.get_tests(config=config)
    import Util
    tests += Util.get_tests(config=config)
    return tests
Example #18
0
 def cipher_data(self):
     self.cipher = Cipher.Cipher(self.textEdit.toPlainText(), self.passw)
     ciphered = self.cipher.cipher()
     if not os.stat(self.file)[0] & stat.S_IWRITE:
         # File is read-only, so make it writeable
         os.chmod(self.file, stat.S_IWRITE)
         f = open(self.file, 'w+')
         f.writelines('ciphered\n' + ciphered)
         f.close()
     else:
         f = open(self.file, 'w+')
         f.writelines('ciphered\n' + ciphered)
         f.close()
     # File is writeable, so make it read-only
     os.chmod(self.file, stat.S_IREAD)
def ClickAction():
    EntryText = Entry_Box.get("0.0" , END)
    ChatWindow.config(state = NORMAL)

    Entry_Box.delete("0.0" , END)
    ChatWindow.insert(INSERT , "You :  "+EntryText)
    message = Cipher.encrypt(EntryText, key=4)
    message = message.encode("utf-8")

    s.send(message)
    today = date.today()
    d = today.strftime("%B %d, %Y")
    t1 = datetime.now()
    t2 = t1.strftime("%H:%M:%S")
    cr.execute('''INSERT INTO send_message(Date ,time, send) VALUES(?,?,?)''', (d, t2, message))
    db.commit()
    ChatWindow.config(state = DISABLED)
Example #20
0
 def getCipher(self):
     if (self.v.get() == 1):
         return cp.VigenereStandard()
     elif (self.v.get() == 2):
         return cp.VigenereAutoKey()
     elif (self.v.get() == 3):
         return cp.VigenereRunningKey()
     elif (self.v.get() == 4):
         return cp.VigenereFull(matrixName="test")
     elif (self.v.get() == 5):
         return cp.VigenereExtended()
     elif (self.v.get() == 6):
         return cp.Playfair()
Example #21
0
def main():
    C = cifra.Cipher()
    A = enemy.Adversary_Det()
    if (IND_CPA(C, A)):
        print("Cifra Identidade quebrada! O adversário venceu!")
Example #22
0
 def __init__(self):
     self.defaultEncapsulationList = ['category']
     self.defaultRemovedList = ['postal']
     self.defaultPassword = "******"
     self.cipherObj = Cipher.cipherClass()
     self.setPassword(self.defaultPassword)
Example #23
0
#import


import Cipher


# assertion


assert callable(Cipher.encode_helper)
assert isinstance(Cipher.encode_helper('a','apple'),int)


# assertion


assert callable(Cipher.decode_helper)
assert isinstance(Cipher.decode_helper('a','apple'),int)