예제 #1
0
def demonstration():
    wire = RSA()

    print("\nThis program will now walk you through the encryption process...")
    input = raw_input("Please enter a string to encrypt: ")

    print("\nYou entered '%s'." % (input))
    print("Your public key is: %d" % (wire.publicKey))
    print("Your private key is: %d" % (wire.privateKey))
    print("Your modulus value is: %d" % (wire.modValue))
    raw_input("Press any key to see how encryption works...")

    print(
        "\nTo encrypt a string, allow X to equal the ASCII value of a given character. Then use the following formula:"
    )
    print("EncryptedASCII = (X ^ PublicKey) % ModulusValue")
    print("This results in each character being encrypted as follows:")
    encryptedCharacters = wire.encrypt(input)
    for i in range(0, len(encryptedCharacters)):
        print("\t%s: %d" % (input[i], encryptedCharacters[i]))
    raw_input("Press any key to see how decryption works...")

    print(
        "\nTo decrypt a string, allow X to equal the encrypted value of a given character. Then use the following formula:"
    )
    print("DecryptedASCII = (X ^ PrivateKey) % ModulusValue")
    print(
        "\nWhen decrypted, the output should be the same as your initial input!"
    )
    print("'%s' is your original string!" %
          (wire.decrypt(encryptedCharacters)))
예제 #2
0
class MainWindow(QMainWindow, ui.Ui_MainWindow):
    
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        
        p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489
        q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917
        self.rsa = RSA(p, q)
        
        self.connect(self.button_e, SIGNAL("clicked()"), self.encrypt)
        self.connect(self.button_d, SIGNAL("clicked()"), self.decrypt)
        #self.connect(self.button_e, SIGNAL("clicked()"), lambda:QMessageBox.information(self,"No",u"浮云"))
    
    def encrypt(self):
        message = unicode(self.line_e_m.text()).strip()
        if not message:
            QMessageBox.critical(self, u"错误", u"请输入明文")
        else:
            ciphertext = self.rsa.encryptString(message)
            self.text_e_c.setPlainText(QString(unicode(ciphertext)))
    
    def decrypt(self):
        ciphertext = unicode(self.text_d_c.toPlainText()).strip()
        if not ciphertext:
            QMessageBox.critical(self, u"错误", u"请输入密文")
        else:
            try:
                message = self.rsa.decrypt(ciphertext)
            except:
                self.line_d_m.setText(u"无法解密该密文")
            else:
                self.line_d_m.setText(unicode(message))
class rsaOracle(object):
    def __init__(self):
        self.rsa = RSA(1024)

    def get_public_key(self):
        return self.rsa.get_public_key()

    def get_parity(self, ciphertext):
        return self.rsa.decrypt(ciphertext)[-1] & 1
예제 #4
0
class oracle:
    def __init__(self):
        self.rsa = RSA()
        self.pub, self.private = self.rsa.keygen(l=512)

    def getPubKey(self):
        return self.pub

    def isEven(self, num):
        return ord(self.rsa.decrypt(num, self.private)[-1]) & 1 == 0
예제 #5
0
class oracle:

	def __init__(self):
		self.rsa = RSA()
		self.pub, self.private = self.rsa.keygen(l=512)

	def getPubKey(self):
		return self.pub

	def isEven(self, num):
		return ord(self.rsa.decrypt(num, self.private)[-1]) & 1 == 0
예제 #6
0
class RSA_server() :
	def __init__(self, keylen) :
		self.rsa = RSA(keylen)
		self.received_texts = set()

	def get_public_key(self) :
		return self.rsa.get_public_key()

	def decrypt(self, text) :
		if text in self.received_texts : return None
		self.received_texts.add(text)

		return self.rsa.decrypt(text)
예제 #7
0
class LocalOracle(Oracle):
    def __init__(self, plaintext, mode):
        Oracle.__init__(self, mode)
        from rsa import RSA
        from secret import p, q, e
        self._rsa = RSA(p, q, e)
        self._ciphertext = self._rsa.encrypt(bytes_to_long(plaintext))
        self._rsa.set_firewall()

    def call(self, number):
        Oracle.call(self, number)
        if self._mode == Oracle.MODE_DECRYPT:
            return self._rsa.decrypt(number)
        if self._mode == Oracle.MODE_ENCRYPT:
            return self._rsa.encrypt(number)
예제 #8
0
def decrypt():
    data = list(map(int, request.form.get('data').split(',')))
    d = request.form.get('d')
    n = request.form.get('n')

    if not data or not d or not n:
        return 'Bad Request', 400

    if len(d) > 5 or len(n) > 5:
        return 'Bad Request', 400

    try:
        decrypted_data = RSA.decrypt(data=data, d=int(d), n=int(n))
    except Exception as e:
        return 'Bad Request', 400
    return {'decrypted_data': decrypted_data}
예제 #9
0
 def decrypt_file(self, filenames):
     for fp in filenames:
         if os.path.exists(fp):
             file_lines = []
             with open(fp, 'r') as to_decrypt:
                 file_lines = to_decrypt.readlines()
             encrypted_message = file_lines[3]
             decrypted_message = RSA.decrypt(encrypted_message, self.n,
                                             self.d)
             new_fp = 'decrypt_' + fp
             with open(new_fp, 'w') as out:
                 out.write(decrypted_message)
             print("Saved decrypted_message to " + new_fp)
         else:
             print("Error: Could not decrypt " + fp +
                   ". File does not exist!")
예제 #10
0
class Peer:
    def __init__(self, addr, port):
        self.ip=addr
        self.port=port
        self.node = socket.socket()
        self.crypt=RSA()
        tuple=self.crypt.prime_tuple()
        p, q = tuple
        n=p*q
        e=self.crypt.public_key(tuple)
        self.pub_k=(e, n)
        d=self.crypt.private_key(tuple, e)
        self.priv_k=(d, n)
        print(self.pub_k)

    def connection(self):
        self.node.connect((self.ip, self.port))
        counter=0
        while True:
            query_en=self.node.recv(2048)
            if query_en:
                query=query_en.decode("utf-8")
                if query in ["Enter username: "******"Enter password: "******"Enter public key: "]:

                    response=input(query)
                    type(response)
                    self.node.sendall(str.encode(response))
                    counter+=1

            if counter==3:
                break

        message=(self.node.recv(2048)).decode("utf-8")
        if message=="Name a group that you would want to create or join: ":
            group=input(message)
            type(group)
            if group is not "":
                self.node.sendall(str.encode(group))
                data=self.node.recv(2048)
                if data:
                    encoded=data.decode("utf-8")
                    res=self.crypt.decrypt(encoded, self.priv_k)
                    print(res)
        self.node.close()
예제 #11
0
    def showDialog(self):

        self.anchor = int(self.le1.text())
        self.accuracy = int(self.leac.text())
        if (self.anchor < self.accuracy):
            QMessageBox.about(self, "ERROR", "need threshold > accuracy")
        else:
            self.text = self.le2.text()
            rsa1 = RSA(self.anchor, self.accuracy, self.text)
            rsa1.create_key()
            self.ciphertext = rsa1.encrypt([rsa1.e, rsa1.n], rsa1.text)
            self.plaintext = rsa1.decrypt([rsa1.d, rsa1.n], self.ciphertext)
            self.ciphertext = [chr(a) for a in self.ciphertext]
            a = ''.join(self.ciphertext)
            self.le3.setText(str(self.text))
            self.le4.setText(str(a))
            self.le5.setText(str(self.plaintext))
            self.lep.setText(str(rsa1.p))
            self.leq.setText(str(rsa1.q))
            self.len.setText(str(rsa1.n))
            self.lee.setText(str(rsa1.e))
            self.led.setText(str(rsa1.d))
예제 #12
0
def demonstration():
	wire = RSA()

	print("\nThis program will now walk you through the encryption process...")
	input = raw_input("Please enter a string to encrypt: ")
	
	print("\nYou entered '%s'." % (input))
	print("Your public key is: %d" % (wire.publicKey))
	print("Your private key is: %d" % (wire.privateKey))
	print("Your modulus value is: %d" % (wire.modValue))
	raw_input("Press any key to see how encryption works...")
	
	print("\nTo encrypt a string, allow X to equal the ASCII value of a given character. Then use the following formula:")
	print("EncryptedASCII = (X ^ PublicKey) % ModulusValue")
	print("This results in each character being encrypted as follows:")
	encryptedCharacters = wire.encrypt(input)
	for i in range(0, len(encryptedCharacters)):
		print("\t%s: %d" % (input[i], encryptedCharacters[i]))
	raw_input("Press any key to see how decryption works...")
	
	print("\nTo decrypt a string, allow X to equal the encrypted value of a given character. Then use the following formula:")
	print("DecryptedASCII = (X ^ PrivateKey) % ModulusValue")
	print("\nWhen decrypted, the output should be the same as your initial input!")
	print("'%s' is your original string!" % (wire.decrypt(encryptedCharacters)))
예제 #13
0
 def test_decrypt_encrypt(self, p, q, e, m):
     rsa = RSA(p, q, e)
     self.assertEqual(m, rsa.decrypt(rsa.encrypt(m)))
예제 #14
0
        rsa = RSA(p, q, e)
    elif use_own_values == "2":
        rsa = RSA.get_random_rsa()
    elif use_own_values == "3":
        run = False
        break

    show_values = ask_input("show_values")

    if show_values == "1":
        rsa.show_values()

    continue_with_instance = "1"

    while continue_with_instance == "1":
        print()
        action = ask_input("action")
        print()

        if action == "1":
            word = input('Choose a word: ')
            print('Word encrypted: {}'.format(rsa.encrypt(word)))

        elif action == "2":
            values = input('Input the word encrypted values: ')
            values = list(map(int, values.split(', ')))

            print('Word decrypted: {}'.format(rsa.decrypt(values)))

        continue_with_instance = ask_input("continue_with_instance")
        run = continue_with_instance != "3"
예제 #15
0
class RsaTest(object):

    # Constructor
    # Populates all verified outcomes
    def __init__(self):
        self.publicKey = 65535
        self.privateKey = 14440774790529487
        self.modValue = 15725236647914011
        self.message = "Indiana"
        self.verifiedResults = [
            6203455842774329L, 10449696731316258L, 10444098371056832L,
            13641245043391240L, 7463814312856899L, 10449696731316258L,
            7463814312856899L
        ]

    # Runs each tests and displays status of each
    def run(self):
        self.rsa = RSA()

        if (self.testGCD() == False):
            print("\nGCD TEST FAILED!")
            return
        else:
            print("\nGCD TEST PASSED!")

        if (self.testInvMod() == False):
            print("MODULAR INVERSE TEST FAILED!")
            return
        else:
            print("MODULAR INVERSE TEST PASSED!")

        if (self.testIsPrime() == False):
            print("PRIMALITY TEST FAILED!")
            return
        else:
            print("PRIMALITY TEST PASSED!")

        if (self.testGeneratePrimePair() == False):
            print("PRIME PAIR GENERATION TEST FAILED!")
            return
        else:
            print("PRIME PAIR GENERATION TEST PASSED!")

        if (self.testEncryption() == False):
            print("ENCRYPTION TEST FAILED!")
            return
        else:
            print("ENCRYPTION TEST PASSED!")

        if (self.testDecryption() == False):
            print("DECRYPTION TEST FAILED!")
            return
        else:
            print("DECRYPTION TEST PASSED!")

    # Runs three tests to ensure Greatest COmmon Denominator functions properly
    def testGCD(self):
        if (self.rsa.gcd(12, 40) != 4):
            return False
        if (self.rsa.gcd(100, 1000) != 100):
            return False
        if (self.rsa.gcd(44, 99) != 11):
            return False
        return True

    # Runs three tests to verify that inverse modulus works properly
    def testInvMod(self):
        if (self.rsa.invMod(12, 35) != 3):
            return False
        if (self.rsa.invMod(111, 1321) != 1202):
            return False
        if (self.rsa.invMod(45, 91) != 89):
            return False
        return True

    # Runs three tests to verify primality function works correctly
    def testIsPrime(self):
        if (self.rsa.isPrime(1255567) != True):
            return False
        if (self.rsa.isPrime(7) != True):
            return False
        if (self.rsa.isPrime(7233) != False):
            return False
        return True

    # Verifies that a random prime pair is generated so that p > q and p != q
    def testGeneratePrimePair(self):
        self.rsa.generatePrimePair()
        a = self.rsa.primePair["p"]
        b = self.rsa.primePair["q"]
        if (self.rsa.isPrime(a) == False):
            return False
        if (self.rsa.isPrime(b) == False):
            return False
        if (b >= a):
            return False
        return True

    # Verifies that the encryption algorithm works correctly
    def testEncryption(self):
        self.rsa.publicKey = self.publicKey
        self.rsa.privateKey = self.privateKey
        self.rsa.modValue = self.modValue
        if (self.rsa.encrypt(self.message) != self.verifiedResults):
            return False
        return True

    # Verifies that the decryption algorithm works correctly
    def testDecryption(self):
        self.rsa.publicKey = self.publicKey
        self.rsa.privateKey = self.privateKey
        self.rsa.modValue = self.modValue
        if (self.rsa.decrypt(self.verifiedResults) != self.message):
            return False
        return True
예제 #16
0
 def verify(self,msg,sign,key):
   pkcs15 = PKCS15()
   rsa = RSA()
   dgst = hashlib.sha1(message).digest()
   return pkcs15.unpad("\x00"+rsa.decrypt(sign,key)) == dgst #把密文sign和key通过解密函数解密出来,然后在填充之后的包里把msg恢复出来对比一下
예제 #17
0
 Alice = RSA("Alice", 256)
 Bob = RSA("Bob", 256)
 public_Bob = Bob.public_key
 public_Alice = Alice.public_key
 Alice.getpublickey(public_Bob)
 print("Info about Alice")
 Alice.info()
 Bob.getpublickey(public_Alice)
 print("Info about Bob")
 Bob.info()
 print("Test encryption and decryption")
 open = random.randint(1000000, 9999999999)
 print("Open text: ", open)
 cypher = Alice.encrypt(open)
 print("Encrypted by Alice: ", cypher)
 message = Bob.decrypt(cypher)
 print("Decrypted by Bob: ", message)
 print("Test signature and verification")
 signa = Bob.Sign(open)
 print("Message: {}\nSignature: {}".format(signa[0], signa[1]))
 Ver = Alice.Verify(signa)
 print("Verification: ", Ver)
 print("Test for sending keys")
 key = Alice.send_key()
 if key == None:
     key = Bob.send_key()
     get = Alice.Receive(key)
     print(get)
     print("Key from Bob to Alice")
     print("Key: {}".format(get[0]))
     print("Validation: ", get[1])
예제 #18
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        loadUi(os.getcwd() + '/gui.ui', self)
        self.constraint_input()
        self.connect_buttons()
        self.elgamal = Elgamal()
        self.rsa = RSA()
        self.dh = DiffieHellman()
        self.mode = None
        self.format = None

    def constraint_input(self):
        self.onlyInt = QIntValidator()

        self.RSA_key_e_value.setValidator(self.onlyInt)
        self.RSA_key_d_value.setValidator(self.onlyInt)
        self.RSA_key_n_value.setValidator(self.onlyInt)
        self.RSA_sess_n_value.setValidator(self.onlyInt)
        self.RSA_sess_g_value.setValidator(self.onlyInt)
        self.RSA_sess_x_value.setValidator(self.onlyInt)
        self.RSA_sess_y_value.setValidator(self.onlyInt)

        self.EG_key_p_value.setValidator(self.onlyInt)
        self.EG_key_g_value.setValidator(self.onlyInt)
        self.EG_key_x_value.setValidator(self.onlyInt)
        self.EG_key_y_value.setValidator(self.onlyInt)
        self.EG_sess_n_value.setValidator(self.onlyInt)
        self.EG_sess_g_value.setValidator(self.onlyInt)
        self.EG_sess_x_value.setValidator(self.onlyInt)
        self.EG_sess_y_value.setValidator(self.onlyInt)

        self.RSA_output_text.setReadOnly(True)
        self.EG_output_text.setReadOnly(True)

    def connect_buttons(self):
        # Main menu buttons
        self.rsabutton.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(1))
        self.egbutton.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(2))

        # RSA buttons
        self.RSA_key_savebutton.clicked.connect(self.rsa_save_key)
        self.RSA_act_execbutton.clicked.connect(self.rsa_execute)
        self.RSA_key_genbutton.clicked.connect(self.rsa_generate_key)
        self.RSA_key_filebutton.clicked.connect(self.rsa_import_key)
        self.RSA_act_decbutton.clicked.connect(self.set_mode_dec)
        self.RSA_act_encbutton.clicked.connect(self.set_mode_enc)
        self.RSA_input_filebutton.clicked.connect(self.rsa_get_input_file)
        self.RSA_fmt_txtbutton.clicked.connect(self.set_format_txt)
        self.RSA_fmt_filebutton.clicked.connect(self.set_format_file)
        self.RSA_returnbutton.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(0))
        self.RSA_sess_genbutton.clicked.connect(
            self.rsa_diffiehellman_generate_key)

        # Elgamal buttons
        self.EG_key_savebutton.clicked.connect(self.elgamal_save_key)
        self.EG_act_execbutton.clicked.connect(self.elgamal_execute)
        self.EG_key_genbutton.clicked.connect(self.elgamal_generate_key)
        self.EG_key_filebutton.clicked.connect(self.elgamal_import_key)
        self.EG_act_decbutton.clicked.connect(self.set_mode_dec)
        self.EG_act_encbutton.clicked.connect(self.set_mode_enc)
        self.EG_input_filebutton.clicked.connect(self.elgamal_get_input_file)
        self.EG_fmt_txtbutton.clicked.connect(self.set_format_txt)
        self.EG_fmt_filebutton.clicked.connect(self.set_format_file)
        self.EG_returnbutton.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(0))
        self.EG_sess_genbutton.clicked.connect(
            self.eg_diffiehellman_generate_key)

    # DIFFIE HELMAN STUFF
    def rsa_diffiehellman_generate_key(self):
        self.dh.generate_parameters()
        n, g, x, y = self.dh.get_parameters()
        self.RSA_sess_n_value.setText(str(n))
        self.RSA_sess_g_value.setText(str(g))
        self.RSA_sess_x_value.setText(str(x))
        self.RSA_sess_y_value.setText(str(y))
        sess_key = self.dh.get_session_key()
        self.RSA_sess_result.setText(str(sess_key))

    def eg_diffiehellman_generate_key(self):
        self.dh.generate_parameters()
        n, g, x, y = self.dh.get_parameters()
        self.EG_sess_n_value.setText(str(n))
        self.EG_sess_g_value.setText(str(g))
        self.EG_sess_x_value.setText(str(x))
        self.EG_sess_y_value.setText(str(y))
        sess_key = self.dh.get_session_key()
        self.EG_sess_result.setText(str(sess_key))

    # RSA STUFF
    def rsa_save_key(self):
        fileNamePub, _ = QFileDialog.getSaveFileName(
            None, "Save RSA Public Key", "", "Public Key File (*.pub)")
        fileNamePri, _ = QFileDialog.getSaveFileName(
            None, "Save RSA Private Key", "", "Private Key File (*.pri)")
        # self.rsa.generate_key()
        self.rsa.save_generated_keys(fileNamePub, fileNamePri)

    def rsa_set_public_key(self):
        e = int(self.RSA_key_e_value.text())
        n = int(self.RSA_key_n_value.text())
        self.rsa.set_public_key(e, n)

    def rsa_set_private_key(self):
        d = int(self.RSA_key_d_value.text())
        n = int(self.RSA_key_n_value.text())
        self.rsa.set_private_key(d, n)

    def rsa_execute(self):
        self.rsa_set_public_key()
        self.rsa_set_private_key()
        st = time.time()
        if self.mode == 'enc':
            if self.format == 'txt':
                self.rsa.get_input(
                    bytes(self.RSA_input_text.toPlainText(),
                          'UTF-8',
                          errors='ignore'))
                self.rsa.encrypt()
                self.RSA_output_text.setText(self.rsa.get_cipher_text())
                # print("RSA get cipher text: ", bytes(self.rsa.get_cipher_text(), 'UTF-8'))
            elif self.format == 'file':
                if self.rsa_inpfile == None:
                    self.display_value_error("File belum dipilih")
                    return
                assert self.rsa_inpfile is not None
                self.rsa.enc_from_file(self.rsa_inpfile)
                self.rsa.encrypt()
                fileName, _ = QFileDialog.getSaveFileName(
                    None, "Save Encrypted File", "", "All Files (*)")
                print("tes({})".format(fileName))
                if fileName == "":
                    return
                self.rsa.enc_write_file(fileName)
                # Print file size
                self.RSA_size_value.setText(
                    str(os.path.getsize(fileName) / 1000))
            else:
                self.display_value_error("Format belum dipilih")
                return
        elif self.mode == 'dec':
            if self.format == 'txt':
                check = self.RSA_input_text.toPlainText()
                print("RSA_input toPlainText ", check)
                print("length of text = {}".format(len(check)))
                for c in check:
                    print(c, end='')
                print()
                self.rsa.get_input(
                    bytes(self.RSA_input_text.toPlainText(),
                          'UTF-8',
                          errors='ignore'))
                self.rsa.parse_msg_to_enc()
                self.rsa.decrypt()
                self.RSA_output_text.setText(self.rsa.get_plain_text())
            elif self.format == 'file':
                if self.rsa_inpfile == None:
                    self.display_value_error("File belum dipilih")
                    return
                assert self.rsa_inpfile is not None
                self.rsa.dec_from_file(self.rsa_inpfile)
                self.rsa.decrypt()
                fileName, _ = QFileDialog.getSaveFileName(
                    None, "Save Encrypted File", "", "All Files (*)")
                print("tes({})".format(fileName))
                if fileName == "":
                    return
                self.rsa.dec_write_file(fileName)
                # Print file size
                self.RSA_size_value.setText(
                    str(os.path.getsize(fileName) / 1000))
            else:
                self.display_value_error("Format belum dipilih")
                return
        else:
            self.display_value_error("Aksi belum dipilih")
            return

        end = str(time.time() - st)
        # Set time execution
        self.RSA_time_value.setText(end)

    def rsa_generate_key(self):
        self.rsa.generate_key()
        d, n1 = self.rsa.get_private_key()
        e, n2 = self.rsa.get_public_key()
        assert n1 == n2
        self.RSA_key_n_value.setText(str(n1))
        self.RSA_key_d_value.setText(str(d))
        self.RSA_key_e_value.setText(str(e))

    def rsa_import_key(self):
        fileNamePub, _ = QFileDialog.getOpenFileName(
            None, "Import RSA Public Key", "", "Public Key File (*.pub)")
        fileNamePri, _ = QFileDialog.getOpenFileName(
            None, "Import RSA Private Key", "", "Private Key File (*.pri)")
        self.rsa.import_public_key(fileNamePub)
        self.rsa.import_private_key(fileNamePri)
        # display the imported key in the text box
        d, n1 = self.rsa.get_private_key()
        e, n2 = self.rsa.get_public_key()
        assert n1 == n2
        self.RSA_key_n_value.setText(str(n1))
        self.RSA_key_d_value.setText(str(d))
        self.RSA_key_e_value.setText(str(e))

    def rsa_get_input_file(self):
        fileName, _ = QFileDialog.getOpenFileName(None, "Get Input File", "",
                                                  "All Files (*)")
        self.rsa_inpfile = fileName
        fileName = fileName.split('/')[-1]
        self.RSA_inp_file_label.setText("Chosen file: {}".format(fileName))

    # ELGAMAL STUFF
    def elgamal_save_key(self):
        fileNamePub, _ = QFileDialog.getSaveFileName(
            None, "Save Elgamal Public Key", "", "Public Key File (*.pub)")
        fileNamePri, _ = QFileDialog.getSaveFileName(
            None, "Save Elgamal Private Key", "", "Private Key File (*.pri)")
        self.elgamal.generate_key()
        self.elgamal.save_generated_keys(fileNamePub, fileNamePri)

    def elgamal_set_public_key(self):
        p = int(self.EG_key_p_value.text())
        g = int(self.EG_key_g_value.text())
        y = int(self.EG_key_y_value.text())
        self.elgamal.set_public_key(p, g, y)

    def elgamal_set_private_key(self):
        p = int(self.EG_key_p_value.text())
        x = int(self.EG_key_x_value.text())
        self.elgamal.set_private_key(p, x)

    def elgamal_execute(self):
        self.elgamal_set_public_key()
        self.elgamal_set_private_key()
        st = time.time()
        if self.mode == 'enc':
            if self.format == 'txt':
                self.elgamal.get_input(
                    bytes(self.EG_input_text.toPlainText(),
                          'UTF-8',
                          errors='ignore'))
                self.elgamal.encrypt()
                self.EG_output_text.setText(self.elgamal.get_cipher_text())
            elif self.format == 'file':
                self.elgamal.enc_from_file(self.elgamal_inpfile)
                self.elgamal.encrypt()
                fileName, _ = QFileDialog.getSaveFileName(
                    None, "Save Encrypted File", "", "All Files (*)")
                self.elgamal.enc_write_file(fileName)
                # Print file size
                self.EG_size_value.setText(
                    str(os.path.getsize(fileName) / 1000))
            else:
                self.display_value_error("Format belum dipilih")
                return

        elif self.mode == 'dec':
            if self.format == 'txt':
                self.elgamal.get_input(
                    bytes(self.EG_input_text.toPlainText(),
                          'UTF-8',
                          errors='ignore'))
                self.elgamal.parse_msg_to_enc()
                self.elgamal.decrypt()
                self.EG_output_text.setText(self.elgamal.get_plain_text())
            elif self.format == 'file':
                self.elgamal.dec_from_file(self.elgamal_inpfile)
                self.elgamal.decrypt()
                fileName, _ = QFileDialog.getSaveFileName(
                    None, "Save Encrypted File", "", "All Files (*)")
                self.elgamal.dec_write_file(fileName)
                # Print file
                self.EG_size_value.setText(
                    str(os.path.getsize(fileName) / 1000))
            else:
                self.display_value_error("Format belum dipilih")
                return

        else:
            self.display_value_error("Aksi belum dipilih")
            return

        end = str(time.time() - st)
        # Set time execution
        self.EG_time_value.setText(end)

    def elgamal_get_input_file(self):
        fileName, _ = QFileDialog.getOpenFileName(None, "Get Input File", "",
                                                  "All Files (*)")
        self.elgamal_inpfile = fileName
        fileName = fileName.split('/')[-1]
        self.EG_inp_file_label.setText("Chosen file: {}".format(fileName))

    def elgamal_import_key(self):
        fileNamePub, _ = QFileDialog.getOpenFileName(
            None, "Import Elgamal Public Key", "", "Public Key File (*.pub)")
        fileNamePri, _ = QFileDialog.getOpenFileName(
            None, "Import Elgamal Private Key", "", "Private Key File (*.pri)")
        self.elgamal.import_public_key(fileNamePub)
        self.elgamal.import_private_key(fileNamePri)

    def elgamal_generate_key(self):
        self.elgamal.generate_key()
        g, y, p = self.elgamal.get_public_key()
        x, p = self.elgamal.get_private_key()
        self.EG_key_p_value.setText(str(p))
        self.EG_key_g_value.setText(str(g))
        self.EG_key_x_value.setText(str(x))
        self.EG_key_y_value.setText(str(y))

    # OTHER STUFF
    def set_mode_enc(self):
        self.mode = 'enc'

    def set_mode_dec(self):
        self.mode = 'dec'

    def set_format_txt(self):
        self.format = 'txt'

    def set_format_file(self):
        self.format = 'file'

    # VALIDATION STUFF
    def display_value_error(self, err_msg: str):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText("Error")
        msg.setInformativeText(err_msg)
        msg.setWindowTitle("Error")
        msg.setStandardButtons(QMessageBox.Ok)
        retval = msg.exec_()
예제 #19
0
파일: main.py 프로젝트: AnaFerreira015/RSA
from rsa import RSA
import src.hub as hub
"""
Universidade Federal de Alagoas - UFAL
Programa para criptografia RSA da matéria de Matemática Discreta

Participantes:
    - Ana Ferreira
    - Frederico Guilherme
    - Lucas Tenório
    - Phyllipe Bezerra
    - Rafael Augusto
"""

if __name__ == "__main__":
    # Opção selecionada no menu
    option = hub.menu()
    rsa = RSA()

    if option == 1:
        print("\n[1] Gerar chave pública")
        rsa.generate_key()
    elif option == 2:
        print("\n[2] Criptografar")
        rsa.encrypt()
    elif option == 3:
        print("\n[3] Descriptografar")
        rsa.decrypt()
    else:
        exit(1)
예제 #20
0
def test_decrypt(p, q, e, cipher, decrypted):
    rsa = RSA(p, q, e)
    assert rsa.decrypt(cipher) == decrypted
예제 #21
0
파일: main.py 프로젝트: ud-flori/RSA
    print('[+] Elapsed time:', stop-start)
    print()
    print("[i] Your public key is: ")
    time.sleep(.5)
    print(rsa_object.get_elements())
    print()
    raw_text = input("Write a message to encrypt: ")
    start = timeit.default_timer()
    rsa_object.encrypt(raw_text)
    stop = timeit.default_timer()
    time.sleep(.2)
    print("[i] Your message has been encrypted.")
    print("[+] Elapsed time:", stop-start)
    time.sleep(1)
    print()
    print("[i] Decoding message...")
    start = timeit.default_timer()
    rsa_object.decrypt()
    stop = timeit.default_timer()
    print("[i] Decoded message with chinese remainder theorem:")
    print("[i] ", rsa_object.decrypted_text)
    print("[+] Elapsed time: ", stop-start)
    print()
    print("[i] Decoded message with Fast Modular Exponentiation:")
    start = timeit.default_timer()
    rsa_object.decrypt2()
    stop = timeit.default_timer()
    print("[i] ", rsa_object.decrypted_text)
    print("[+] Elapsed time: ", stop-start)
    input()
import binascii

from rsa import RSA

rsa = RSA()

plaintext_1 = 42
ciphertext_1 = rsa.encrypt(42)
decrypted_1 = rsa.decrypt(ciphertext_1)
print(plaintext_1, ciphertext_1, decrypted_1)
plaintext_2 = "attack"
number = int(binascii.hexlify(plaintext_2.encode()), 16)
ciphertext_2 = rsa.encrypt(number)
decrypted_2 = rsa.decrypt(ciphertext_2)
string = binascii.unhexlify(hex(decrypted_2)[2:]).decode()
print(plaintext_2, ciphertext_2, string)
예제 #23
0
from rsa import RSA
from dh import DHUser, DHSession
from elgamal import EGUser, EGSession

if __name__ == '__main__':
    # RSA
    # CRYPTO-19
    c19 = RSA(17, 11, 7)
    assert c19._d == 23
    assert c19.public_key() == (7, 187)
    assert c19.private_key() == (23, 187)

    # CRYPTO-20
    c = RSA.encrypt(c19.public_key(), 88)
    m = RSA.decrypt(c19.private_key(), c)
    assert c == 11
    assert m == 88

    # Diffie-Hellman
    # CRYPTO-35
    dh_session = DHSession(353, 3)
    dh_user_a = DHUser(dh_session, 97)
    dh_user_b = DHUser(dh_session, 233)
    assert dh_user_a.y == 40
    assert dh_user_b.y == 248

    assert dh_session.session_key(dh_user_a, dh_user_b) == \
        dh_user_a.session_key(dh_user_b.public_key()) == \
        dh_user_b.session_key(dh_user_a.public_key()) == 160
예제 #24
0
 def decrypt(event, param):
     sk = currentUser.secret_key
     param.set(RSA.decrypt(param.get(), sk))
예제 #25
0
 def verify(self, msg, sign, key):
     pkcs15 = PKCS15()
     rsa = RSA()
     dgst = hashlib.sha1(message).digest()
     return pkcs15.unpad("\x00" + rsa.decrypt(
         sign, key)) == dgst  #把密文sign和key通过解密函数解密出来,然后在填充之后的包里把msg恢复出来对比一下