def decryptTimingTest(fname, smallprimes, verysmallprimes, gens):
    
    rsaKey = rsa.RSA(smallprimes,verysmallprimes)
    
    decryptTimes = []
    
    for i in range(len(gens)):
        rsaKey.setKeys(gens[i][0], gens[i][1], gens[i][2])
        
        decryptTimes.append([])
        decryptTimes[i].append(gens[i][0])
        decryptTimes[i].append(gens[i][1])
        
        print(str(i+1) + ") e = "+str(gens[i][0])+", d = "+str(gens[i][1])+", n = "+str(gens[i][2]))
        #raw_input("start")
        
        sTime = time.time()
        decrypt(fname,rsaKey,False,False)
        eTime = time.time() - sTime
        
        print "Elapsed time = " + str(eTime) + " s"
        print ''
        
        decryptTimes[i].append(eTime)
        
    return decryptTimes
Example #2
0
def getBalance(user):
    amount = 0
    data = open('ledger.txt').readlines()
    for i in range(len(data)):
        if (int((decrypt(data[i].split()).split())[0]) == user):
            amount += float((decrypt(data[i].split()).split())[1])
    return amount
Example #3
0
def CBC_decrypt(cipher, key):
    words = cipher
    print(
        "********************************DECRYPTING*********************************"
    )
    orgi, decrypted_block = decrypt((words[0:4]), key)

    unXoredBlock = xor_two_str(deBlocker(decrypted_block), IV)
    orginal = [
        unXoredBlock[:4], unXoredBlock[4:8], unXoredBlock[8:12],
        unXoredBlock[12:16]
    ]

    for k in range(4, len(words), 4):
        orgi, decrypted_block = decrypt((words[k:k + 4]), key)
        unXoredBlock = xor_two_str(
            words[k - 4] + words[k - 3] + words[k - 2] + words[k - 1],
            deBlocker(decrypted_block))

        orginal.append(unXoredBlock[:4])
        orginal.append(unXoredBlock[4:8])
        orginal.append(unXoredBlock[8:12])
        orginal.append(unXoredBlock[12:16])
        # print("decryption number " + str(k))
    print("size of orginal = ", len(orginal))

    return orginal
Example #4
0
def decrypt_dir(directory, key):
    if not os.path.exists(os.path.join(directory.decode(), "encrypted.txt")):
        print("this directory has not been encrypted, no need to decrypt")
    else:
        os.remove(os.path.join(directory.decode(), "encrypted.txt")
                  )  # removes the marker file to show its no longer en
        for file in os.listdir(directory):
            filename = os.fsdecode(file)
            # if filename.endswith(".png") or filename.endswith(".txt"):  # only selects two types of files
            if check_file(filename):
                print(os.path.join(directory.decode(), filename))
                decrypt(os.path.join(directory.decode(), filename), key)
                continue
            else:
                continue
Example #5
0
def db_connection_string():
    main_dir = os.getcwd()
    os.listdir(os.path.join(main_dir,'auth'))
    db_auth = {'dbname.txt':'key_dbname.txt',
            'db_pass.txt':'key_db_pass.txt',
            'host.txt':'key_host.txt',
            'dbuser.txt':'key_dbuser.txt'}
    filename = {}
    for i in db_auth.keys():
        with open(r'auth/' +i, 'r') as readfile:
            filename['{}'.format(i.split('.')[0])]= json.load(readfile)

    file_key = {}
    for i in db_auth.keys():
        with open(r'auth/' +db_auth[i], 'r') as readfile:
            file_key['{}'.format(db_auth[i].split('.')[0])]= json.load(readfile)

    db_auth = {}
    for i in filename.keys():
        db_auth[i] = decrypt(eval(filename[i]),eval(file_key['key_'+i])).decode("utf-8")

    connection = mysql.connector.connect(host=db_auth['host'], 
                                            user=db_auth['dbuser'],
                                            port=3306,
                                            passwd=db_auth['db_pass'], 
                                            db='Expense')
    return connection
Example #6
0
def mailto(email_address):
    username = decrypt(eval(user), eval(key_user)).decode("utf-8")
    password = decrypt(eval(panda), eval(key_panda)).decode("utf-8")
    fromaddr = username
    Body = """<!DOCTYPE html>
                <html>
                <head>
                <style>
                body {
                        color: red;
                }
                h4 {
                        color: #1E162F;
                        font-size: 20px;
                }
                h5 {
                        color: rgb(0,0,255);
                        font-size: 15px;
                }
                
                p {
                        color: rgb(0,0,255)
                }
                </style>
                </head>
                <body>
                 <h4> Decoded </h4>
                 
                </body>
                </html>
                """

    Body += u'<h5> Hi {name},</h5>'.format(name=email_address.split('@')[0])

    msg = MIMEMultipart()
    Mail_Body = MIMEText(Body, 'html')
    msg.attach(Mail_Body)
    msg['From'] = username
    msg['To'] = email_address
    msg['Subject'] = "Decoded"

    send_mail(username=username,
              password=password,
              from_addr=fromaddr,
              to_addrs=email_address,
              msg=msg)
Example #7
0
def de():

    try:
        file = open("keys.txt", "r")
    except:
        file = open("keys.txt", "w")

    text = [[pos + 1, x] for pos, x in enumerate(file.read().split()[1::2])]
    file.seek(0)
    keys = [int(x) for x in file.read().split()[::2]]
    if len(text) == 0:
        print("Keys.txt is empty, text has to be encrypted first...")
        time.sleep(1)
        refresh()
        main()

    else:
        print("\t{} |{}".format("Pos", "Encrypted value"))
        for x in text:
            print("\t{}".format(x))
        print("\nEnter the position of text you wish to be decrypted\n")

        while True:
            try:
                inp = int(input("> ")) - 1
                file.seek(0)
                line = file.readlines()[inp]
                break
            except:
                continue
        print("\nThe decrypted text is: {}".format(
            '\033[1m' + decrypt(text[inp][1], keys[inp]) + '\033[0m'))

        while True:
            inp = input(
                "\nDo you wish to delete the text from keys.txt? (Y/N) > ")
            if inp in ["y", "Y", "YES", "no"]:
                file.seek(0)
                lines = file.readlines()
                file.close()

                file = open("keys.txt", "w")
                for x in lines:
                    if x != line:
                        file.write(x)
                file.close()
                print("\nEntry deleted from keys.txt")
                break
            elif inp in ["n", "N", "NO", "no"]:
                file.close()
                break
            else:
                continue

    time.sleep(1)
    refresh()
Example #8
0
def decryptmsg(privatekey, file, master):
    global message
    file = file[:-1]
    recover_data(file, "file_output.txt", 2)
    with open("file_output.txt") as readfile:
        todecrypt = readfile.read()
    try:
        message = decrypt(todecrypt, privatekey)
        messagebox.showinfo("Music Encrypt", "Decrypted Successfully!")
        master.switch_frame(Message)
    except Exception as e:
        messagebox.showinfo("Error", "Incorrect Decryption !")
Example #9
0
 def decrypt(self):
     try:
         textboxValue = self.textEditEncryptedText2.toPlainText()
         inputComboBox = self.comboBoxPilihJenis.currentText()
         solve = decrypt()
         solve.setValue(inputComboBox, textboxValue)
         self.textEditPlainText2.setText(solve.getValue())
     except Exception:
         inputComboBox = self.comboBoxPilihJenis.currentText()
         pesan = "Input Tidak Valid!\nInput harus berupa " + inputComboBox
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Warning)
         msg.setText("Warning")
         msg.setInformativeText(pesan)
         msg.setWindowTitle("Warning")
         msg.exec_()
Example #10
0
def buildBlocks():
    with open('ledger.txt', 'r') as ledgerFile:
        ledgerdata = ledgerFile.readlines()
    with open('hashtable.txt', 'r') as hashFile:
        hashdata = hashFile.readlines()

    for i in range(len(ledgerdata)):
        transaction = decrypt(ledgerdata[i].split()).split()
        if (i == 0):
            continue
        blockChain.append(
            Block(blockChain[-1].hash, int(transaction[0]),
                  float(transaction[1]), i))
        if (blockChain[i].hash != hashdata[i].strip('\n')):
            print("THE BLOCKCHAIN WAS TAMPERED WITH")
            break
Example #11
0
def main():
    out = io.open(outFile, "w", encoding="utf-8")
    out2 = io.open(outFile2, "w", encoding="utf-8")
    random1 = generateRandomNumber(maxRandomNumber)
    random2 = generateRandomNumber(maxRandomNumber)

    prime1 = findNearPrime(random1)
    prime2 = findNearPrime(random2)

    privata, publica = generateKeys(prime1, prime2)
    print(privata, publica)

    textToEncrypt = readFromFile(fileToRead)
    encryptedData = encrypt(textToEncrypt, privata)
    print("crypted", encryptedData)
    out.write(encryptedData)
    decryptedData = decrypt(encryptedData, publica)
    out2.write(decryptedData)
    # #print("decrypted", decryptedData)
    out.close()
    out2.close()
Example #12
0
from decrypt import *
from encrypt import *

if __name__ == '__main__':
    secretCode = input("Enter a secret passphrase:")
    p = int(input("Enter a prime number: "))
    q = int(input("Enter a different prime number: "))

    print("Generating your public/private keys now . . .")

    public, private = genkeys(p, q)

    print("Public key is ", public)
    print("Private Key key is ", private)

    encryptedMsg = encrypt(private, secretCode)

    print("Cypher # is: ", ''.join(map(lambda x: str(x), encryptedMsg)))
    print("=================================================================")
    print("Decrypting message with public key ", public, " . . .")
    print("Your message is:")
    print(decrypt(public, encryptedMsg))
def show():
    enc = decrypt(e1.get())
    e = "".join(map(str, enc))
    blank.insert(0, e)
def main():
    #Control variables. Used for testing purposes. 
    #   If the RSA public and private key values are above ~2000, the encryption and decryption  
    #   calculations can take a very long time, especially on large image files.
    #If both vars are set False, the possible p and q values are between 373 and 997.
    smallprimes = True      #p and q between 101 and 367
    verysmallprimes = True  #p and q between 59 and 179
    
    #rsaTest() and rsa.verify() variables
    #   Both of these methods can take a very long time if smallprimes and verysmallprimes are set to False.
    vruns = 10
    numTestRuns = 50   #Number of loops to execute if `Run RSA test on current key` is selected
        
    
    if len(sys.argv) == 2:
        fname = sys.argv[1] 
        runAutoTest(fname)
    else:
        rsaGen = False
        done = False
        
        while done == False:
            op = int(displayMenu(smallprimes, verysmallprimes, vruns, numTestRuns))
            if op == 1:                                         #Generate RSA key
                rsaKey = rsa.RSA(smallprimes,verysmallprimes)
                rsaGen = True
                e,d,n = rsaKey.getKeys()
                print 'public key : ' + str(e)
                print 'private key: ' + str(d)
                print 'mod        : ' + str(n)
                print 'Press enter to continue...'
                raw_input("") #pause so that the keys can be seen
            elif op == 2:                                       #Import RSA key from file
                rsaKey = rsa.RSA(True,True)
                keyfname = raw_input("Enter key filename: ")
                keyFile = open(keyfname, "r")
                keys = keyFile.read().split("/")
                e = int(keys[0])
                d = int(keys[1])
                n = int(keys[2])
                print "Verifying RSA key pairs..."
                if rsa.verify(e,d,n,vruns) == True:
                    rsaKey.setKeys(e,d,n)
                    rsaGen = True
                    print ''
                    print "RSA key file \'" + keyfname + "\' successfully imported."
                    print ''
                    print 'public key : ' + keys[0]
                    print 'private key: ' + keys[1]
                    print 'mod        : ' + keys[2]
                    raw_input("Press enter to continue...") #pause so that the keys can be seen
                else:
                    printInvalidRSA()
            elif op == 3:                                       #Enter existing RSA key
                rsaKey = rsa.RSA(True,True)
                eIn = int(raw_input("Enter public key : "))
                dIn = int(raw_input("Enter private key: "))
                nIn = int(raw_input("Enter mod value  : "))
                print "Verifying RSA key pairs..."
                if rsa.verify(eIn,dIn,nIn,vruns) == True:
                    rsaKey.setKeys(eIn,dIn,nIn)
                    rsaGen = True
                    print "RSA keys set."
                    print 'Press enter to continue...'
                    raw_input("")
                else:
                    printInvalidRSA()
            elif op == 4:                                       #Save current key to file
                if rsaGen == True:
                    keyfname = raw_input("Enter filename for key: ")
                    keyDir = "keys/"
                    if not os.path.exists(keyDir): #Create `./keys/` directory if it doesn't already exist
                        os.makedirs(keyDir)
                    rsaKey.writeKeysToFile(keyDir + keyfname)
                else:
                    print "No RSA keys defined."
            elif op == 5:                                           #Encrypt image
                if rsaGen == True:
                    imageFile = raw_input("Enter image filename: ")
                    encfname = encrypt(imageFile,rsaKey,True,True)
                    print "Encrypted file saved to " + encfname
                    raw_input("Press enter to continue...")
                else:
                    print "No RSA keys defined."
            elif op == 6:                                           #Decrypt file
                if rsaGen == True:
                    encFile = raw_input("Enter encrypted file name: ")
                    decfname = decrypt(encFile,rsaKey,True,True)
                    if decfname != None:
                        print "Decrypted image saved to " + decfname
                        raw_input("Press enter to continue...")
                    else:
                        print "Decryption aborted."
                        print ''
                        raw_input("Press enter to continue...")
            elif op == 7:                                               #Run RSA test on currently loaded keys
                if rsaGen == True:
                    print "Verifying current RSA key..."
                    e,d,n = rsaKey.getKeys()
                    if rsa.verify(e,d,n,vruns) == True:
                        print "Done."
                        print ''
                        print "Testing quaternary encrypt/decrypt algorithm using current keys..." 
                        testRSA(rsaKey, numTestRuns)
                    else:
                        printInvalidRSA()
                else:
                    print "No RSA keys defined."
            elif op == 8:
                if rsaGen == True:
                    print "Verifying current RSA key..."
                    e,d,n = rsaKey.getKeys()
                    if rsa.verify(e,d,n,vruns) == True:
                        print "Done."
                        raw_input("Press enter to continue...")
                    else:
                        printInvalidRSA()
            elif op == 9:
                tests = 20#int(raw_input("Number of tests: "))#100
                ind = 0
                #print 'Running ' + str(tests) + ' tests...'
                print ''
                
                keys = rsaGenerationTest(smallprimes, verysmallprimes, tests, ind)
                keys = keys + rsaGenerationTest(True, False, tests/2, ind)
                keys = keys + rsaGenerationTest(False,False,tests/5, ind)
                keys.sort(key=lambda x: x[0])
                
                encryptTimes = encryptTimingTest("sample_160px.jpg", smallprimes, verysmallprimes, keys)
                
                #decryptTimes = decryptTimingTest("output/sample_160px")
                
                #for i in keys:
                #    print 'public key:  ' + str(i[0])
                #    print 'private key: ' + str(i[1])
                #    print 'mod: ' + str(i[2])
                #    print ''
                for i in encryptTimes:
                    print str(i[0]) + ", " + str(i[1]) + ", " + str(i[2])
                raw_input("Press enter to continue...")
            elif op == 10:            #Quit
                done = True
            else:                                           #Input is not a valid option (1-8)
                print "Invalid option selected."    
Example #15
0
	def import_credentials(password, cred_file):
		"""Imports the credentials used for each exchange"""
		self.exchanges = decrypt(password, cred_file)
Example #16
0
from encrypt import *

print("ENCRYPT YOUR NAME")
print("Insert your name and get your own encrypted version!" + "\n")

name = encrypt()

print()

decrypt = input("Do you want to decrypt a name? ")
if "y" in decrypt.casefold():
    from decrypt import *
    decrypt()
else:
    print("Have a good day {}!".format(name))
Example #17
0
    print_menu()  ## Displays menu
    choice = input("Enter your choice [1-3]: ")

    if choice == 1:
        plain_text = input("Enter a string")
        key = int(input("Enter a numerical key"))
        length = strlen(plain_text)
        create_arr(plain_text,length)
        encrypt(arr,key)
        display()
     elif choice == 2:
         cipher_text = input("Enter a string")
         key = int(input("Enter a numerical key"))
         length = strlen(cipher_text)
         create_arr(cipher_text,length)
         decrypt(arr,key)
         display(arr,length)

    elif choice == 3:
        loop = False  # This will make the while loop to end as not value of loop is set to False
    else:
        # Any integer inputs other than values 1-5 we print an error message
        raw_input("Wrong option selection. Enter any key to try again..")







    'host.txt': 'key_host.txt',
    'dbuser.txt': 'key_dbuser.txt'
}
filename = {}
for i in db_auth.keys():
    with open(r'auth/' + i, 'r') as readfile:
        filename['{}'.format(i.split('.')[0])] = json.load(readfile)

file_key = {}
for i in db_auth.keys():
    with open(r'auth/' + db_auth[i], 'r') as readfile:
        file_key['{}'.format(db_auth[i].split('.')[0])] = json.load(readfile)

db_auth = {}
for i in filename.keys():
    db_auth[i] = decrypt(eval(filename[i]),
                         eval(file_key['key_' + i])).decode("utf-8")

app = Flask(__name__)
app.config['DEBUG'] = True

# load the environement variables

load_dotenv('.env')

# set the root and data folder
root_folder = os.getcwd()
data_folder = os.path.join(root_folder, 'data')
# set workbook variables
filename = 'monthly_exp.xlsx'
list_sheet_names = meta.run_config['sheetname']
cost_based_items = [