def main():
    filename = input("Input file name: ")
    enc_filename = "enc_" + filename
    dec_filename = "dec_" + filename 

    rsa = RSA(512)

    print("Start encrypting '{0}' ...".format(filename))
    rsa.encrypt(filename, enc_filename)
    print("Encrypting done. Results saved in file: '{0}'".format(enc_filename))
    print("Start decrypting '{0}' ...".format(enc_filename))
    rsa.decrypt(enc_filename, dec_filename)
    print("Decrypting done. Results saved in file: '{0}'".format(dec_filename))
Exemple #2
0
    def encrypt(self):
        """
        Encryption method.
        :return: symmetric algorithm object
        """
        # message is encrypted by the given symmetric algorithm
        if self._algorithm == "AES":
            sym_alg = AES_DES3(self._key_type, self._message, self._mode)
            self._path = Constants.aes_secret_key_path
        else:
            sym_alg = AES_DES3(self._key_type, self._message, self._mode,
                               False)
            self._path = Constants.des3_secret_key_path

        # encryption
        key, cipher = sym_alg.encrypt()
        self._cipher = cipher

        # key is encrypted by the RSA asymmetric algorithm
        rsa = RSA(self._rsa_key, key, True)
        crypt_key = rsa.encrypt()
        self._crypt_key = crypt_key
        Helper.write_envelope([self._algorithm, 'RSA'], [key, crypt_key],
                              base64.b64encode(cipher), bytes.hex(crypt_key),
                              Constants.envelope_path)

        return sym_alg
def send():
    messageS = my_msg.get()
    my_msg.set("")
    messageS = NAME + ": " + messageS
    print(Fore.BLUE, end='')
    print(messageS)
    msg_list.insert(tkinter.END, messageS)
    messageS = RSA.encrypt(messageS, public_key_2)
    CLIENT.send(messageS.encode("utf8"))
Exemple #4
0
def send():
    msg = my_msg.get()
    my_msg.set("")
    msg = NAME + ": " + msg
    print(Fore.BLUE, end='')
    print(msg)
    msg_list.insert(tkinter.END, msg)
    msg = RSA.encrypt(msg, public_key_1)
    CLIENT.send(msg.encode("utf8"))
Exemple #5
0
def task():
    CHANCE = 5
    RRRSA = RSA(1024)
    print(f"My public key: {RRRSA.e}, {RRRSA.N}")

    for _ in range(10):
        try:
            print(MENU)
            choice = input("Your choice: ")

            if choice == "1":
                m = int(input("Your message: "))
                c = RRRSA.encrypt(m)
                print(f"Your cipher: {c}")

            elif choice == "2":
                c = int(input("Your message: "))
                d = int(input("Your decryption exponent: "))
                m = RRRSA.decrypt(c, d)
                print(f"Your message: {m}")

            elif choice == "3":
                RRRSA.gen_ed(1024)
                print(f"My new public key: {RRRSA.e}, {RRRSA.N}")

            elif choice == "4":
                if CHANCE:
                    CHANCE -= 1
                    flag = int.from_bytes(FLAG, 'big')
                    encflag = RRRSA.encrypt(flag)
                    print(f"encflag: {encflag}")
                else:
                    print("Nope, only 5 chances to get encflag.")

            else:
                print("Bye!")
                exit(0)

        except Exception as e:
            print(e)
            print("Error!")
            exit(-1)
Exemple #6
0
def test2():
    rsa = RSA()
    rsa.e = 3
    rsa.d = 2011
    rsa.n = 3127
    message = "hello"

    print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n))
    print("Message: " + message)

    enc = rsa.encrypt(message)
    print("Encrypted message: " + enc)
    dec = rsa.decrypt(enc)
    print("Decrypted message: " + dec)

    sig = "andres"
    print("Signature: " + sig)
    dec2 = rsa.decrypt(sig, True)
    print("Generated Signature: " + dec2)
    auth = rsa.encrypt(dec2, True)
    print("After Authentication: " + auth)
Exemple #7
0
def test():
    rsa = RSA()
    rsa.e = 3
    rsa.d = 2011
    rsa.n = 3127
    message = "hello"

    print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n))
    print("Message to encrypt/decrypt: " + message)

    enc = rsa.encrypt(message)
    print("Encrypted message: " + enc)
    dec = rsa.decrypt(enc)
    print("Decrypted message: " + dec)
Exemple #8
0
class Alice:
    def __init__(self,x,keys):
        self.x = x
        self.rsa = RSA(keys)
        self.util = Utilities()
        

    def computation(self,bobKey,m1):
        self.m1 = m1
        self.c = self.rsa.encrypt(self.m1,PUKY=bobKey)
        self.c1 = self.c - self.x
        return self.c1
    
    def generateResults(self,z,p):
        if z[self.x ]%p == self.m1 % p :
            return False
        return True
Exemple #9
0
class TestRSAOperations(unittest.TestCase):

    def setUp(self):
        self.p= DynamInt(10)
        self.q = DynamInt(10)
        #self.p.setData("821089628001493")
        #self.q.setData("1872967539195764008553239")   
        
        self.rsa = RSA(0)        
        self.rsa.createkeys(self.p, self.q)
    def test_encdec(self):
        '''
        Test regular encoding and decoding of numbers
        '''
        a = DynamInt()
        a.setData("25")
        rsa = RSA(0)
        rsa.p.setData("11")
        rsa.q.setData("3")
        rsa.e.setData("3")
        rsa.n.setData("33")
        rsa.phi.setData("20")
        rsa.d.setData("7")
        d =  rsa.powmod(a,rsa.e,rsa.n)
        f =  rsa.powmod(d,rsa.d,rsa.n)
        self.assertEqual(a.data, f.data)
        
        
        
    def test_disguise(self):
        strr = "iamaboy"
        rsa = RSA(0)
        num=rsa.disguise(strr)
        self.assertEqual("iamaboy", rsa.reveal(num))
    def test_encryptionDecryption(self):
        # make sure we can encrypt and decrypt
        crypted = self.rsa.encrypt("iam")
        result = self.rsa.decrypt(crypted)
        temp=''
        for i in result:
            temp = temp+i
        self.assertEqual("iam", temp)
Exemple #10
0
def console_mode():
    print 'Welcome to RSA!'
    p, q = _get_primes_from_user()
    if not p or not q:
        bit_len = _get_bit_len_from_user()
    else:
        bit_len = max(p, q).bit_length()
    keys = key_gen.get_RSA_keys(bit_len, p, q)
    rsa_instance = RSA(n=keys[0][1], public_key=keys[0][0], private_key=keys[1][0], key_size=bit_len)
    while True:
        msg = _get_msg_to_enc()
        if msg == 'exit':
            break
        try:
            enc = rsa_instance.encrypt(msg)
            print 'Enc msg is: {}'.format(enc)
            dec = rsa_instance.decrypt(enc)
            print 'Dec msg is: {}'.format(dec)
        except Exception as e:
            print e
Exemple #11
0
class DSA:
    def __init__(self, P, Q):
        self.P = P
        self.Q = Q
        self.encryptor = RSA(self.P, self.Q)
        self.e, self.d, self.n = self.encryptor.generate_keys()

    def get_hash(self, message):

        hash_input = bytes(message, "utf-8")
        hash_digest = SHA1HASH(hash_input).final_hash()

        return hash_digest

    def sign_document(self, input_file):

        with open(input_file) as f:
            message = f.read()

        hash_digest = self.get_hash(message)

        print("Public keys are e:{}, n:{}".format(self.e, self.n))
        print("Private keys are d:{}, n:{}".format(self.d, self.n))

        ciphertext = self.encryptor.encrypt(hash_digest)
        return ciphertext

    def verify_document(self, input_file, ciphertext):

        with open(input_file) as f:
            message = f.read()

        hash_digest = self.get_hash(message)

        plaintext = self.encryptor.decrypt(ciphertext)

        if plaintext == hash_digest:
            return False
        else:
            return True
Exemple #12
0
class Client(object):
    server = None
    RSA = None

    def __init__(self, host='localhost', port=8080):
        self.host = host
        self.port = port
        self.server = self._init_connection_to_server()
        try:
            self._get_public_key_from_server()
        except:
            raise

    def _init_connection_to_server(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((self.host, self.port))
        return server

    def _get_public_key_from_server(self):
        data = self.server.recv(10240)
        key = self._get_key(data)
        self.RSA = RSA(public_key=key[0], n=key[1])

    def close(self):
        if self.server:
            self.server.close()

    def send_to_server(self, msg):
        self.server.send(str(msg))

    def _get_key(self, data):
        # Parses the received key from the server
        tup_key = eval(data)
        return tup_key[0], tup_key[1]

    def encrypt_msg(self, msg):
        return self.RSA.encrypt(msg.encode('utf-8'))
Exemple #13
0
from RSA import RSA

type1 = RSA(1000)
'''type1.print_vars()
type1.get_public()
type1.get_private()'''

x = type1.encrypt(5)
y = type1.decrypt(x)

print('\nencrypted is: ', x, "\ndecrypted is: ", y)
Exemple #14
0
from RSA import RSA as rsa

program = rsa.RSAProgram()
message = rsa.encrypt(program.modulus, program.encrypt)

print(message)

raw_input('press enter when ready to decrypt').lower()

print(rsa.decrypt(message, program.decrypt, program.modulus))
Exemple #15
0
from values import *
from RSA import RSA

if __name__ == "__main__":
    rsa = RSA(p, q, a)
    rsa.decrypt(rsa.encrypt(message))
    
 def run_RSA(s):
     r = RSA(16)
     c = r.encrypt(s)
     m = r.decrypt(c)
     assert s.hex() == m.hex()
Exemple #17
0
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    text_input2 = ObjectProperty(None)
    text_input3 = ObjectProperty(None)

    def __init__(self):
        super(self.__class__, self).__init__()
        self.isLoaded = False
        self.loaded_file = FILETYPE.UNKNOWN
        self.h = ''
        self.rsaModule = RSA()

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file",
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        if filename[0][-4:] == ".wav":
            self.h = HeaderBuilderWAV()
            self.loaded_file = FILETYPE.WAV
        elif filename[0][-4:] == ".bmp":
            self.h = HeaderBuilderBMP()
            self.loaded_file = FILETYPE.BMP
        else:
            raise ValueError('Not known extension of file')
        self.h.readHeader(os.path.join(path, filename[0]))
        self.text_input.text = str(self.h.header)
        self.dismiss_popup()
        self.isLoaded = True

    def cos(self):
        self.dismiss_popup()

    def display_wav_fft(self, samples, sample_rate, num_channels, fignum):
        #time vector
        n = len(samples)
        k = np.arange(n)
        T = float(n) / sample_rate
        freq = k / T
        freq = freq[range(n / 2)]

        fig, ax = plt.subplots(num_channels, 1)

        for i in range(0, num_channels):
            plt.figure(fignum)

            #calculate fft and normalize results
            if num_channels is 1:
                y = np.fft.fft(samples) / n
                y = y[range(n / 2)]
                plt.plot(freq, abs(y))
                plt.title('Channel {} FFT'.format(i + 1))
                plt.xlabel('Freq (Hz)')
            else:
                y = np.fft.fft(samples[:, i]) / n
                y = y[range(n / 2)]
                ax[i].plot(freq, abs(y))
                ax[i].set_title('Channel {} FFT'.format(i + 1))
                ax[i].set_xlabel('Freq (Hz)')

    def display_bmp_fft(self, samples):
        plt.figure(1)
        fft = fftpack.fft2(samples)
        plt.imshow(np.abs(np.fft.fftshift(fft)), interpolation='nearest')
        plt.show()

    def fourier_transform(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()

            #return Button(text='Hello World')
        else:
            if self.loaded_file is FILETYPE.WAV:
                sample_rate = self.h.header.get_property("SampleRate")
                num_channels = self.h.header.get_property("NumChannels")
                self.display_wav_fft(self.h.data[0:1000], sample_rate,
                                     num_channels, 1)
                plt.show()
            elif self.loaded_file is FILETYPE.BMP:
                self.display_bmp_fft(self.h.data)
                #rsaModule = RSA()
                #enc = rsaModule.encrypt(self.h.data)
                #dec = rsaModule.decrypt(enc)
                #if (self.h.data==dec).all:
                #    print "good"
                #else:
                #    print "bad"

    def encrypt(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        if self.loaded_file is FILETYPE.WAV:
            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="Only BMP files are supported!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        elif self.loaded_file is FILETYPE.BMP:
            file = open(self.h.filename, "rb")
            image = file.read()
            file.close()

            header = image[:54]
            data = image[54:84]
            enc = self.rsaModule.encrypt(
                np.transpose(np.fromstring(data, dtype=np.uint8)))
            dec = self.rsaModule.decrypt(enc)
            print(np.fromstring(data, dtype=np.uint8)[0:10])
            print(dec[0:10])
            print(len(dec))
            print(len(data))
            print([ord(c) for c in data[0:10]])
            print(dec[0:10])
            file = open("example2.bmp", "wb")
            for i in range(len(dec)):
                if dec[i] > 255:
                    print('RSA error')
                    self.moduleRSA = RSA()
                    return

            d = [int(v) for v in dec]
            d2 = [chr(v) for v in d]
            print(d2)
            file.write(header.join(d2))
            file.close()
            print("--------------------------------------")

    def decrypt(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        if self.loaded_file is FILETYPE.WAV:
            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="Only BMP files are supported!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        elif self.loaded_file is FILETYPE.BMP:
            file = open(self.h.filename, "rb")
            image = file.read()
            file.close()
            header = image[:54]
            data = image[54:]
            print(np.fromstring(data, dtype=np.uint8)[0:10])
Exemple #18
0
'''
RSA_OOP_test

@author: Sollazzo Nicholas
@date: March 20th 2017
@version: 1.0
@status: GREEN

'''

from RSA import RSA

rsa = RSA()

print(rsa.dict())

#en = rsa.encrypt(input('>'))

en = rsa.encrypt('das')

print('encrypted:', en)

print('decrypted:', rsa.decrypt(en))
Exemple #19
0
    # Se obtienen las llaves asimetricas ya generadas desde un archivo (por cuestiones de tiempo)
    receptor.getKeys('receptor_keys', llaves[x])
    origen.getKeys('emitter_keys', llaves[x])

    # Lado cifrado
    # Se genera un certificado para las llaves del origen
    cer = Certificate(origen.getPrivateKey(), origen.getPublicKey())
    certificado = cer.getCertificate()
    # Se pasa la llave publica del receptor al origen
    origen.setEntityKey(receptor.getPublicKey())

    ########## Tiempo de cifrado ###############
    # Se cifra con la llave de la otra entidad
    tiempos.medir(f'cifradollave_{x}')
    cypherKey = origen.encrypt(k)
    tiempos.medir(f'cifradollave_{x}')
    ############################################

    # Se cifran los documentos
    for documento in documentos:
        # Se instancia el cifrador simetrico
        aeso = AES(k, iv)

        # Se lee el archivo
        f = open(f'documentos/{documento}', 'rb')
        contenido = f.read()
        f.close()

        ########## Tiempo de cifrado ###############
        # Se cifra el contenido de cada archivo
Exemple #20
0
from RSA import RSA

if __name__ == '__main__':
    rsa = RSA()

    while True:
        inp = input("uzenet: ")

        choice = 999
        while not int(choice) in range(1, 2 + 1):
            print("1) visszafejtes")
            print("2) titkositas")
            choice = input()

        if int(choice) == 1:
            print(rsa.decrypt(int(inp)))
        else:
            print(rsa.encrypt(inp))