Esempio n. 1
0
 def decrypt_file(self, file_name):
     aes = AESCipher(self.key)
     with open(file_name, 'rb') as file:
         text = file.read()
     dec = aes.decrypt(text)
     with open(file_name, 'wb') as file:
         file.write(dec)
Esempio n. 2
0
    def process_outgoing_message(self, msg_raw, originates_from_console=False):
        '''
        Process an outgoing message before Base64 encoding

        :param msg_raw: raw message
        :return: message to be sent to the server
        '''

        # if the message has been typed into the console, record it, so it is never printed again during chatting
        if originates_from_console == True:
            self.update_send_ctr()
            # message is already seen on the console
            cipher = AESCipher(self.symm_key)
            encrypted_msg = cipher.encrypt(msg_raw)

            str_to_sign = MESSAGE_CODE + '|' + encrypted_msg + '|' + str(
                self.send_counter)
            sig = self.sign(str_to_sign)
            msg_raw = str_to_sign + '|' + sig
            m = Message(owner_name=self.manager.user_name, content=msg_raw)
            self.printed_messages.append(m)

        # process outgoing message here
# example is base64 encoding, extend this with any crypto processing of your protocol
        encoded_msg = base64.encodestring(msg_raw)

        # post the message to the conversation
        self.manager.post_message_to_conversation(encoded_msg)
Esempio n. 3
0
  def __init__(self):
    self.blocks = []

    key_for_md5_aes = '#TCC2019-N2N#'
    self.aes = AESCipher(key_for_md5_aes)

    # Carregando com paramêtros de acesso para desenvolvedor
    

    # Instanciando um gerenciador do banco de dados TCC
    self.conexao_bd = conexao_servidor.TCC

    cursor_ultimo_bloco = self.conexao_bd.HBase.aggregate([
      {
        "$sort": {
          "timestamp": -1
        },
        
      }, {"$limit": 1}
    ])
    last_block_from_collection = list(cursor_ultimo_bloco)

    if(len(last_block_from_collection) > 0):
      print('Retomando o blockchain a partir de uma hash no banco de dados.')

      self.set_genesis_block(True,last_block_from_collection[0])
    else:
      self.set_genesis_block()
Esempio n. 4
0
 def encrypt_payload(self, decrypted_payload, user_id):
     aeskey = self.get_token(user_id)
     aesiv = self.get_iv(user_id)
     aesc = AESCipher(aeskey)
     aesc.set_iv(aesiv)
     encrypted_bytes = aesc.encrypt(decrypted_payload)
     return encrypted_bytes
Esempio n. 5
0
def run_client(port):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((HOST, port))

    cred = s.recv(RECV_SIZE)
    while True:
        try:
            pub, sig = unpack_cred(cred)
            break
        except:
            cred += s.recv(RECV_SIZE)

    if not verify_cred(pub, sig):
        return

    key = RSA.importKey(pub)
    rsa = PKCS1_OAEP.new(key)

    sess_key = secrets.token_bytes(KEY_SIZE)
    enc_sess_key = rsa.encrypt(sess_key)

    s.sendall(pickle.dumps(enc_sess_key))

    cipher = AESCipher(sess_key)
    messages = []
    data = recvall(s)
    while data:
        chunk = pickle.loads(data)
        data = data[len(pickle.dumps(chunk)):]
        messages.append(cipher.decrypt(chunk))

    with open('msgs.txt', 'wb') as f:
        f.write(b''.join(messages))
Esempio n. 6
0
def get_data(image_data, bits_to_rewrite_count, key):
    cipher = AESCipher(key)

    image_bytes_count = int(math.ceil(64 * 8 / bits_to_rewrite_count))

    i_str = StringIO()
    for i in range(image_bytes_count):
        i_str.write(H.get_bits(image_data[i])[-bits_to_rewrite_count:])
    bin_enc_size = i_str.getvalue()[:64 * 8]

    i_bytes = BytesIO()
    for i in range(64):
        i_bytes.write(bytes([int(bin_enc_size[8 * i:8 * i + 8], 2)]))
    enc_size = i_bytes.getvalue()

    size = int(cipher.decrypt(enc_size))

    shift = image_bytes_count

    image_bytes_count = int(math.ceil(size * 8 / bits_to_rewrite_count))

    for i in range(image_bytes_count):
        i_str.write(H.get_bits(image_data[i + shift])[-bits_to_rewrite_count:])
    bin_enc_data = i_str.getvalue()[64 * 8:(size + 64) * 8]

    i_bytes = BytesIO()
    for i in range(size):
        i_bytes.write(bytes([int(bin_enc_data[8 * i:8 * i + 8], 2)]))
    enc_data = i_bytes.getvalue()

    data = cipher.decrypt(enc_data).encode()
    return data
Esempio n. 7
0
    def __init__(self, transacoes, bloco_ant, next_block=''):

        bloco_anterior_formatado = '{}'.format(bloco_ant)

        self._bloco_ant = bloco_ant
        self._transacoes = AESCipher(bloco_anterior_formatado).encrypt(
            transacoes)
Esempio n. 8
0
def generate_token(user):
    """
        token contains: (generated session key, expiry date) encrypted with system wide shared secret
        ticket contains: ((generated session key), (generated session key, expiry date)) encrypted 
            with clients public key
    """

    expiry_date = (datetime.datetime.now() +
                   datetime.timedelta(minutes=10)).timestamp()

    token = {"gen_session_key": " ", "expiry_date": expiry_date}
    token_serialised = json.dumps(token, cls=DateTimeEncoder)

    cipher = AESCipher(SHARED_SECRET)
    encode_hash_session_key = cipher.encrypt(token_serialised)

    ticket = json.dumps({
        'gen_session_key': user['gen_session_key'],
        'token': encode_hash_session_key
    })

    # encrypting the whole ticket with client's password or public key
    cipher = PKCS1_OAEP.new(user['public_key'])
    encode_hash_ticket = cipher.encrypt(str.encode(ticket))
    return encode_hash_ticket
Esempio n. 9
0
def decrypt_token(ticket, privatekey):
    """
        token contains: (generated session key, expiry date) encrypted with 
        ticket contains: 
    """
    privkey_path = "./client.key"
    pubkey_path = "./client_pub.key"

    # encrypting the whole ticket with client's password or public key

    cipher = PKCS1_OAEP.new(privatekey)

    ticket = cipher.decrypt(ticket)

    ticket = json.loads(ticket)
    print(ticket)

    from AESCipher import AESCipher
    cipher = AESCipher(SHARED_SECRET)

    token = cipher.decrypt(ticket['token'])
    token = json.loads(token)

    print(token, ticket)
    return
	def generate_splits(self):
		aes = AESCipher(self.key)
		cipher = aes.encrypt(self.text)
		message = aes.decrypt(cipher)
		size = 255, len(self.key)
		im = Image.new("1", size, "white")
		pix =  im.load()
		for i in range(len(self.key)):
			for j in range(ord(self.key[i])):
				pix[j, i] = 0
		im.save("original.gif")
		share1 = Image.new("1", size, "white")
		share1pix = share1.load()
		for i in range(len(self.key)):
			for j in range(255):
				x = randint(0,1)
				if x == 0:
					share1pix[j, i] = 0
		share2 = Image.new("1", size)
		share2pix = share2.load()
		for i in range(len(self.key)):
			for j in range(255):
				if pix[j, i] == share1pix[j, i]:
					share2pix[j, i] = 0
				else:
					share2pix[j, i] = 255
		output = [share1, share2, cipher]
		x = Decrypter(cipher, [share1, share2])
		x.decrypt_image()
		return output
Esempio n. 11
0
    def DH(self, sharedKey):
        print '\n############### STARTING D-H ##################'
        # Create AES object with shared key
        cipher = AESCipher(sharedKey)

        #generate key to send to server
        myDiffieHellman = DiffieHellman()
        print 'g^a mod p value is: ', myDiffieHellman.public_key

        print '\n'

        #send key to server
        sendDH = cipher.encrypt(str(myDiffieHellman.public_key))
        print 'Sending encrypted value: ', sendDH.encode('hex')
        self.send(str(sendDH))

        print '\n'

        recvDH = self.waitToRec()

        #decrypt received DH value
        reply = cipher.decrypt(recvDH)
        print 'Received encrypted value: ', recvDH.encode('hex')
        print '\n'
        print 'g^b mod p value is: ', reply
        print '\n'

        #calculate session key
        myDiffieHellman.calc_shared_key(long(reply))
        print "Calculated session key:", myDiffieHellman.key
        self.sessionKey = myDiffieHellman.key

        print '################## D-H OVER ###################\n'
Esempio n. 12
0
 def encrypt_payload(self, pkt, aes_key, aes_iv):
     #aes_key = b'\x9b\xd9\xcd\xf6\xbe+\x9dX\xfb\xd2\xef>\xd87i\xa0\xca\xf5o\xd0\xac\xc3\xe0R\xf0z\xfa\xb8\xdd\x01?E'
     #aes_iv = b'\xef\xaa)\x9fHQ\x0f\x04\x18\x1e\xb5;B\xff\x1c\x01'
     aesc = AESCipher(aes_key)
     aesc.set_iv(aes_iv)
     encrypted_bytes = aesc.encrypt(pkt)
     return encrypted_bytes
	def decrypt_image(self):
		key = self.get_key_from_image()
		cipher = self.cipher
		aes = AESCipher(key)
		base64_decoded = aes.decrypt(cipher)
		fh = open("decryptedImage.png", "wb")
		fh.write(base64_decoded.decode('base64'))
		fh.close() 
Esempio n. 14
0
 def __init__(self, host, port):
     self.session_key = self.generate_random_key()
     self.host = host
     self.port = port
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.connect((host, port))
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.aes = AESCipher(self.session_key)
Esempio n. 15
0
 def decrypt_payload(self, encrypt_payload, user_id):
     aeskey = self.get_token(user_id)
     aesiv = self.get_iv(user_id)
     aesc = AESCipher(aeskey)
     aesc.set_iv(aesiv)
     decrypted_bytes = aesc.decrypt(encrypt_payload)
     # decrypted_bytes.hex()
     return decrypted_bytes
Esempio n. 16
0
 def handleSynReq(self, resp, serverKey):
     header = resp.split(';')[0]
     if header != 'h':
         Exception, 'header not "h" in wait state - ' + header
     print 'Got syn Req'
     return binascii.unhexlify(
         AESCipher(serverKey).decrypt(resp.split(';')[1])).split(
             ';')  #username,sharedKey,nounce
Esempio n. 17
0
 def save_session(self):
     data = {
         'username': self.username,
         'passwd': self.password
     }
     cipher = AESCipher()
     enc = cipher.encrypt(json.dumps(data))
     with open('session', 'wb') as f:
         f.write(enc)
Esempio n. 18
0
 def save_session(self):
     data = {
         'access_token': self.access_token,
         'refresh_token': self.refresh_token
     }
     cipher = AESCipher()
     enc = cipher.encrypt(json.dumps(data))
     with open('session', 'wb') as f:
         f.write(enc)
Esempio n. 19
0
	def register(self,username):
		if self.state!='start':
			raise Exception,'Can\'t register if the state is not \'start\'!'
		self.nounce = randint(1, 65536)
		self.random_key=binascii.hexlify(os.urandom(32))
		self.server.aes=AESCipher(self.random_key)
		self.username=username
		self.server.send('r;' + self.username + ';' + self.random_key + ';' + str(self.nounce))
		self.state='regReq'
Esempio n. 20
0
 def test_encrypt_decrypt(self):
     config = utils.get_config_parser()
     enc = AESCipher(config.get('AES', 'key'))
     f = open("password.txt", "w+")
     f.write("Password")
     f.close()
     enc.encrypt_file("password.txt", out_filename="password.enc")
     password = enc.decrypt_file("password.enc")
     assert password == "Password", "Failed to decrypt file"
Esempio n. 21
0
	def connect(self,username):
		if self.state!='start':
			raise Exception,'Can\'t connect if the state is not \'start\'!'
		#make it send to the server the username chosen
		self.nounce = randint(1, 65536)
		key=self.loadKey(username)
		self.server.aes = AESCipher(key)
		self.username=username
		self.server.send('c;' + username + ';' + self.server.aes.encrypt(binascii.hexlify(username+';' + str(int(time())))))
		self.state='conReq'
Esempio n. 22
0
 def sendOkMsg(self, peer):
     self.peer = peer
     dhKey, self.nounce = self.peer.aes.decrypt(self.encData).split(';')
     self.peer.send(
         'o;' +
         self.peer.aes.encrypt(self.nounce + ';' + str(self.dh.publicKey))
     )  #+';'+str(peer.sport)))
     self.dh.genKey(int(dhKey))
     self.peer.aes = AESCipher(binascii.hexlify(self.dh.getKey()))
     self.state = 'okSent'
def save_record(account):
    print(request.content_type)
    if not request.json or not 'size' in request.json:
        raise InvalidUsage('Invalid usage of this web-service detected',
                           status_code=400)

    size = int(request.json['size'])
    decoded_compressed_record = request.json.get('data', "")
    symmetricKeyEncrypted = request.json.get('key', "")

    compressed_record = base64.b64decode(decoded_compressed_record)
    encrypted_json_record_str = zlib.decompress(compressed_record)

    pks1OAEPForDecryption = PKS1_OAEPCipher()
    pks1OAEPForDecryption.readDecryptionKey('decryption.key')
    symmetricKeyDecrypted = pks1OAEPForDecryption.decrypt(
        base64.b64decode(symmetricKeyEncrypted))

    aesCipherForDecryption = AESCipher()
    aesCipherForDecryption.setKey(symmetricKeyDecrypted)

    json_record_str = aesCipherForDecryption.decrypt(encrypted_json_record_str)

    record_as_dict = json.loads(json_record_str)

    # Add the account ID to the reading here
    record_as_dict["account"] = account

    #print record_as_dict
    post_id = mongo_collection.insert_one(record_as_dict).inserted_id
    print('Saved as Id: %s' % post_id)

    producer = KafkaProducer(
        bootstrap_servers=['your.kafka.server.com:9092'],
        value_serializer=lambda m: json.dumps(m).encode('ascii'),
        retries=5)
    # send the individual records to the Kafka queue for stream processing
    raw_readings = record_as_dict["data"]
    counter = 0
    for raw_reading in raw_readings:
        raw_reading["id"] = str(post_id) + str(counter)
        raw_reading["account"] = account
        producer.send("car_readings", raw_reading)
        counter += 1

    producer.flush()
    # send the summary to the Kafka queue in case there is some stream processing required for that as well
    raw_summary = record_as_dict["summary"]
    raw_summary["id"] = str(post_id)
    raw_summary["account"] = account
    raw_summary["eventTime"] = record_as_dict["timestamp"]
    producer.send("car_summaries", raw_summary)

    producer.flush()
    return jsonify({'title': str(size) + ' bytes received'}), 201
Esempio n. 24
0
def save(key, entries):
    """ Encrypt the passwords we stored in RAM and write them to the database """
    db = Database()
    cipher = AESCipher(key)
    tmp = []
    for entry in entries:
        entry_2 = cipher.encrypt(entry[2])
        tmp.append([entry[0], entry[1], entry_2.decode()])
    # Write the encrypted passwords to the database
    if (db.update(tmp)):
        print_error("Couldn't save")
Esempio n. 25
0
    def desencriptar(self, mensaje, x_i, y_i):

        clave_segura = self.generar_polinomio(x_i, y_i)

        # Creamos un objeto de tipo AESCipher para poder utilizar los algoritmos de cifrado

        aes = AESCipher()

        mensaje = aes.desencriptar(mensaje, str(clave_segura))

        return mensaje
Esempio n. 26
0
 def load_session(self):
     loaded_session = None
     cipher = AESCipher()
     with open('session', 'rb') as f:
         enc = f.read()
     try:
         plain = cipher.decrypt(enc)
         loaded_session = json.loads(str(plain))
         self.username = loaded_session['username']
         self.password = loaded_session['passwd']
     finally:
         return loaded_session
Esempio n. 27
0
 def decrypt_image(self, k):
     #key = self.get_key_from_image()
     key = k
     cipher = self.cipher
     aes = AESCipher(key)
     base64_decoded = aes.decrypt(cipher)
     #print(type(base64_decoded))
     fh = open("decryptedImage.png", "wb")
     fh.write(base64.b64decode(base64_decoded))
     #fh.write(base64_decoded.decode('base64'))
     fh.close()
     return (base64.b64decode(base64_decoded))
Esempio n. 28
0
def receive_messages(clientSocket, key) -> None:
    # because each line is sent by pickling
    # it might be better to read from the socket
    # as a stream and let pickle do its job
    cipher = AESCipher(key)

    fileObj = clientSocket.makefile(mode="b")

    with open('msgs.txt', 'wb') as outFile:
        for i in range(0, 10):
            decryptedMessage = decryptMessage(cipher, fileObj)
            outFile.write(decryptedMessage)
Esempio n. 29
0
    def __init__(self):
        """ Initialize ui. Connect ui elements to functions. Initialize LoginAgent """
        super(RubLogin, self).__init__()
        uic.loadUi('design.ui', self)
        self.pushButton_login.clicked.connect(self.login)
        self.pushButton_logout.clicked.connect(self.logout)
        self.checkBox_auto.clicked.connect(self.checkBoxAuto)
        self.checkBox_save.clicked.connect(self.checkBoxSave)
        self.checkBox_auto_onstartup.clicked.connect(
            self.checkBoxAutoOnStartup)
        self.loginAgent = LoginAgent(self.textArea_log,
                                     self.checkBox_fileLogging, self.statusBar)
        self.guiEnabled = True

        aes_key = "Jgj-4f;5$f-d.kg&ghkDe-Fg&kSgZ5pd"
        self.aesCipher = AESCipher(aes_key)

        if len(sys.argv) > 1:
            for x in sys.argv:
                if x == "-nogui":
                    self.guiEnabled = False

        # TODO comment
        try:
            data_file = open("data.bin", "rb")
            self.checkBox_fileLogging.setChecked(pickle.load(data_file))
            self.checkBox_auto.setChecked(pickle.load(data_file))
            self.checkBox_save.setChecked(pickle.load(data_file))
            self.checkBox_auto_onstartup.setChecked(pickle.load(data_file))
            if self.checkBox_save.isChecked():
                self.lineEdit_id.setText(
                    self.aesCipher.decrypt(pickle.load(data_file),
                                           pickle.load(data_file)))
                self.lineEdit_pass.setText(
                    self.aesCipher.decrypt(pickle.load(data_file),
                                           pickle.load(data_file)))
            elif not self.guiEnabled:
                data_file.close()
                self.cl_exit("No login data saved")
            data_file.close()
        except (FileNotFoundError, EOFError):
            if not self.guiEnabled:
                self.cl_exit("No login data saved")

        if self.guiEnabled:
            # systemtray icon
            self.trayIcon = SystemTrayIcon(QtGui.QIcon("logo.png"), self)
            self.show()

        if self.checkBox_auto_onstartup.isChecked():
            self.checkBox_auto.setChecked(True)
            self.login()
Esempio n. 30
0
    def __init__(self, file_path, enc_key):
        self.Path = os.path.abspath(file_path)
        if not os.path.exists(self.Path):
            sys.exit('File does not exist!')
        if not os.path.isfile(self.Path):
            sys.exit(self.Path + ' - is not file!')

        try:
            file = open(file_path, 'rb')
        except Exception:
            sys.exit('Can not open file!')

        try:
            self.File_bytes = file.read()
        except Exception:
            sys.exit('Can not read file!')

        self.File_name = os.path.basename(self.Path)

        file_name_bytes = self.File_name.encode()

        if len(file_name_bytes) > 255:
            sys.exit('File name is too long!')

        self.File_name_len = bytes([len(file_name_bytes)])

        self.Hash_sum = hashlib.md5(self.File_bytes).hexdigest()

        byte_string = self.Hash_sum.encode() \
            + self.File_name_len \
            + file_name_bytes \
            + self.File_bytes

        cipher = AESCipher(enc_key)

        self.Encrypted_file = cipher.encrypt(byte_string.decode())

        # The maximum number that is placed in the block
        self._max_enc_file_size = 9999999999999999999999999999999

        size_enc_file = len(self.Encrypted_file)
        if size_enc_file > self._max_enc_file_size:
            sys.exit('File too large!')
        self.Encrypted_size = cipher.encrypt(str(size_enc_file))

        self.Finally_byte_string = self.Encrypted_size + self.Encrypted_file

        self.Finally_size = len(self.Finally_byte_string)

        self.Binary_string = self.get_binary_string()

        file.close()