def __init__(self, dir=None, key='', passphrase=None, cipher=utils.AESCipher):
        super(LocalRsaProvider, self).__init__(cipher=cipher)
        self.dir = dir or os.path.join(os.path.expanduser('~'), _LOCAL_RSA_TMP_DIR)

        utils.makedir_p(self.dir)

        priv_key_full_path = os.path.join(self.dir, key + self.PRIV_KEY_FILE)
        pub_key_full_path = os.path.join(self.dir, key + self.PUB_KEY_FILE)
        try:
            if os.path.exists(priv_key_full_path) and os.path.exists(pub_key_full_path):
                with open(priv_key_full_path, 'rb') as f:
                    self.__decrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase))

                with open(pub_key_full_path, 'rb') as f:
                    self.__encrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase))

            else:
                private_key = RSA.generate(2048)
                public_key = private_key.publickey()

                self.__encrypt_obj = PKCS1_OAEP.new(public_key)
                self.__decrypt_obj = PKCS1_OAEP.new(private_key)

                with open(priv_key_full_path, 'wb') as f:
                    f.write(private_key.exportKey(passphrase=passphrase))

                with open(pub_key_full_path, 'wb') as f:
                    f.write(public_key.exportKey(passphrase=passphrase))
        except (ValueError, TypeError, IndexError) as e:
            raise ClientError(str(e))
Beispiel #2
0
def reset_user_invalid_keys(user, admin_rsa):
	""" Legacy, recrypts all encrypted objects with user's new pubkey(s) """
	otype, oid = ContentType.objects.get_for_model(user), user.id
	ipubs = OwnerPublicKey.inactive.filter(owner_type=otype, owner_id=oid, active=False)
	for ipub in ipubs:
		adminclearkey = PKCS1_OAEP.new(admin_rsa).decrypt(b64decode(ipub.admincipher))
		# import inactive key
		irsa = import_rsa(ipub.adminscopy, adminclearkey)
		# get matching active public key for user
		apub = OwnerPublicKey.objects.get(owner_type=otype, owner_id=oid,
							keytype=ipub.keytype, active=True)
		# import new active publickey
		apublickey = import_rsa(apub.publickey)
		# update encrypted objects encrypting via new active public key
		for encobj in EncryptedObject.objects.filter(opub=ipub):
			clearkey = PKCS1_OAEP.new(irsa).decrypt(b64decode(encobj.cipherkey))
			encobj.cipherkey = b64encode(PKCS1_OAEP.new(apublickey).encrypt(clearkey))
			encobj.opub = apub  # point encobj's opub to new pubkey
			encobj.save()
	apubs = OwnerPublicKey.objects.filter_pubkey(owner=user)
	# reset user's private keys outside their own pubkeys if any, eg. practice locations
	privs = UserPrivateKey.objects.filter(
			user=user, credtype=CRED_WEBAPP).exclude(opub__in=apubs)
	reset_keys(privs, admin_rsa)
	# and remove inactive public keys
	ipubs.delete()
Beispiel #3
0
 def __generate(self, keydata):
     '''
     Generate the pycrypto rsa object
     '''
     if keydata:
         if 'components' not in keydata:
             raise ValueError('Invalid keydata, no components')
         key = RSA.construct(keydata['components'])
         if key.has_private():
             self.priv = key
             self.pub = key.publickey()
             self.sign_key = PKCS1_PSS.new(self.priv)
             self.verify_key = PKCS1_PSS.new(self.pub)
             self.decrypter = PKCS1_OAEP.new(self.priv)
         else:
             self.pub = key
             self.verify_key = PKCS1_PSS.new(self.pub)
         self.keydata = keydata
     else:
         self.priv = self._gen_key()
         self.pub = self.priv.publickey()
         self.sign_key = PKCS1_PSS.new(self.priv)
         self.verify_key = PKCS1_PSS.new(self.pub)
         self.keydata = self._gen_keydata(self.priv)
         self.decrypter = PKCS1_OAEP.new(self.priv)
     self.encrypter = PKCS1_OAEP.new(self.pub)
     self.max_msg_size = self.get_max_msg_size()
     self.enc_chunk_size = self.get_enc_chunk_size()
Beispiel #4
0
    def __init__(self, from_file=None, passphrase=None):
        if from_file == None:
            # generate a new pair
            rng = Random.new().read
            key = RSA.generate(4096 * 2, rng)
            self.public_key = IdentityPublicKey(key)
            self.private_key = IdentityPrivateKey(key)
        else:
            # read from file:
            f = open(from_file, "rb")
            contents = f.read(4096 * 1024)  # no more than 4mb
            f.close()
            key = RSA.importKey(contents.decode("utf-8", "ignore"),
                passphrase=passphrase)
            self.public_key = IdentityPublicKey(key)
            if key.has_private():
                self.private_key = IdentityPrivateKey(key)
            else:
                self.private_key = None

            # ensure the minimum required RSA key size is met:
            if self.public_key.size() < ENCRYPT_BIT_MINIMUM or (\
                    self.private_key != None and \
                    self.private_key.size() < ENCRYPT_BIT_MINIMUM):
                self.private_key = None
                self.public_key = None
                raise ValueError("this RSA key doesn't meet the required " +\
                    "minimum bit size for proper encryption")
        if self.private_key != None:
            self.cipher = PKCS1_OAEP.new(self.private_key.key,
                hashAlgo=SHA256)
        else:
            self.cipher = PKCS1_OAEP.new(self.public_key.key,
                hashAlgo=SHA256)
Beispiel #5
0
def share_directory(other_username, dlog):
    with open(dlog, 'rb') as input:
        log = pickle.load(input)

    userList = log['users']
    userList.append(other_username)
    owner_block = log[owner]
    owner = log['owner']
    key = RSA.importKey(open(owner + '.pri').read())
    cipher = PKCS1_OAEP.new(key, SHA256.new())
    owner_block.decrypt_permission_block(cipher)
    file_aes_key = owner_block.get_file_encryption_key()
    file_dsa_key = None
    user_block = AccessBlock(file_aes_key, file_dsa_key)
    other_key = RSA.importKey(open(other_username + '.pub').read())
    other_cipher = PKCS1_OAEP.new(other_key, SHA256.new())
    user_block.encrypt_permission_block(other_cipher)
    log[other_username] = user_block
    file_log_hash = SHA256.new()
    with open(filelog, 'wb') as infile:
        pickle.dump(log, infile, -1)
    length = len(log)
    with open(filelog, 'rb') as outfile:
        picklelog = outfile.read(length)
    file_log_hash.update(picklelog)
    with open(owner + '.dsa', 'rb') as infile:
        owner_msk = pickle.load(infile)
    k = random.StrongRandom().randint(1,owner_msk.q-1)
    sig = owner_msk.sign(file_log_hash.digest(), k)
    with open(filelog, 'a+b') as outfile:
        pickle.dump(sig, outfile, -1)    
Beispiel #6
0
def leftclick(event):
    name = None
    select = None
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 9999
    s.connect((host, port))
    name = listbox1.get("active")


    select =("SELECT name FROM public.people WHERE age = 19 ")
    print (select)
    key = RSA.importKey(open('../public.der').read())
    cipher = PKCS1_OAEP.new(key)
    select = cipher.encrypt(select.encode('utf-8'))
    print("select is " )
    print(select)
    s.send(select)

    names = s.recv(1024)
    print(names)
    keya = RSA.importKey(open('../private.der').read())
    cipher = PKCS1_OAEP.new(keya)
    message = str_to_list(cipher.decrypt(names).decode('utf-8'))
    print(message[0][0])

    s.close()
    text1.insert(1.0, "ваыа")
    name = None
    names=None
Beispiel #7
0
    def msg_received_get(addlist):


        for x in addlist:
             if x[11].startswith(("msg=", "bmsg=", "enc=msg=", "enc=bmsg=")) and x[3] == address:
                #print(x[11])

                connections.send(s, "aliasget", 10)
                connections.send(s, x[2], 10)

                msg_address = connections.receive(s,10)[0][0]

                if x[11].startswith("enc=msg="):
                    msg_received_digest = x[11].lstrip("enc=msg=")
                    try:
                        #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8")

                        (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest)
                        private_key = RSA.import_key(open("privkey.der").read())
                        # Decrypt the session key with the public RSA key
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        session_key = cipher_rsa.decrypt(enc_session_key)
                        # Decrypt the data with the AES session key
                        cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                        msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                    except:
                        msg_received_digest = "Could not decrypt message"

                elif x[11].startswith("enc=bmsg="):
                    msg_received_digest = x[11].lstrip("enc=bmsg=")
                    try:
                        msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8")

                        #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8")
                        (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest)
                        private_key = RSA.import_key(open("privkey.der").read())
                        # Decrypt the session key with the public RSA key
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        session_key = cipher_rsa.decrypt(enc_session_key)
                        # Decrypt the data with the AES session key
                        cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                        msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                    except:
                        msg_received_digest = "Could not decrypt message"


                elif x[11].startswith("bmsg="):
                    msg_received_digest = x[11].lstrip("bmsg=")
                    try:
                        msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8")
                    except:
                        msg_received_digest = "Could not decode message"
                elif x[11].startswith("msg="):
                    msg_received_digest = x[11].lstrip("msg=")


                msg_received.insert(INSERT, ((time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(x[1])))) + " From " + msg_address.lstrip("alias=") + ": " + msg_received_digest) + "\n")
Beispiel #8
0
 def setUp(self):
     #logging.basicConfig(level=logging.DEBUG)
     logging.basicConfig(level=logging.ERROR)
     #self._t0 = int(time.time())
     self._key = RSA.generate(2048)
     self._encrypt = PKCS1_OAEP.new(self._key.publickey())
     self._decrypt = PKCS1_OAEP.new(self._key)
     self._t0 = time.time()
Beispiel #9
0
 def __init__(self, public_key_file, private_key_file):
     with open(public_key_file,'rb') as pkf:
         pubkey_string = pkf.read()
         self.public_key = RSA.importKey(pubkey_string)
     with open(private_key_file,'rb') as pkf:
         privkey_string = pkf.read()
         self.private_key = RSA.importKey(privkey_string)
     self.public = PKCS1_OAEP.new(self.public_key)
     self.private = PKCS1_OAEP.new(self.private_key)
     self.signer = PKCS1_v1_5.new(self.private_key)
     self.verifier = PKCS1_v1_5.new(self.public_key)
Beispiel #10
0
    def msg_sent_get():

        for row in c.execute("SELECT recipient,openfield,timestamp FROM transactions WHERE address = ? AND (openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ?) ORDER BY timestamp DESC;", (address,) + ("msg=" + '%',) + ("bmsg=" + '%',) + ("enc=msg=" + '%',) + ("enc=bmsg=" + '%',)):
            try:
                # get alias
                c2.execute("SELECT openfield FROM transactions WHERE openfield LIKE ? AND address = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;", ("alias=" + '%', row[0],))  # asc for first entry
                msg_recipient = c2.fetchone()[0]
                # get alias
            except:
                msg_recipient = row[0]

            if row[1].startswith("enc=msg="):
                msg_sent_digest = row[1].lstrip("enc=msg=")
                try:
                    #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8")
                    (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest)
                    private_key = RSA.import_key(open("privkey.der").read())
                    # Decrypt the session key with the public RSA key
                    cipher_rsa = PKCS1_OAEP.new(private_key)
                    session_key = cipher_rsa.decrypt(enc_session_key)
                    # Decrypt the data with the AES session key
                    cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                    msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                except:
                    msg_sent_digest = "Could not decrypt message"

            elif row[1].startswith("enc=bmsg="):
                msg_sent_digest = row[1].lstrip("enc=bmsg=")
                try:
                    msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8")
                    #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8")
                    (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest)
                    private_key = RSA.import_key(open("privkey.der").read())
                    # Decrypt the session key with the public RSA key
                    cipher_rsa = PKCS1_OAEP.new(private_key)
                    session_key = cipher_rsa.decrypt(enc_session_key)
                    # Decrypt the data with the AES session key
                    cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                    msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")
                except:
                    msg_sent_digest = "Could not decrypt message"

            elif row[1].startswith("bmsg="):
                msg_sent_digest = row[1].lstrip("bmsg=")
                try:
                    msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8")
                except:
                    msg_received_digest = "Could not decode message"

            elif row[1].startswith("msg="):
                msg_sent_digest = row[1].lstrip("msg=")

            msg_sent.insert(INSERT, ((time.strftime("%Y/%m/%d,%H:%M:%S", time.gmtime(float(row[2])))) + " To " + msg_recipient.replace("alias=", "") + ": " + msg_sent_digest) + "\n")
Beispiel #11
0
def messages(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MessageForm(request.POST)
        if 'message' in request.POST:
            # check whether it's valid:
            if form.is_valid():
                # extract data from form.cleaned_data 
                to = form.cleaned_data['message_recipient']
                sender = request.user
                body = form.cleaned_data['message_body']
                e = form.cleaned_data['encrypted']
                # recipient username might not exist
                user = User.objects.filter(username=to)
                if user.exists():
                    if e:
                        u = User.objects.get(username=to)
                        public_key = RSA.importKey(u.reporter.publickey)
                        cipher = PKCS1_OAEP.new(public_key)
                        enc_data = b64encode(cipher.encrypt(body.encode('UTF-8')))
                        body = enc_data
                    m = Message(sender=sender, recipient=user.get(), body=body, encrypted=e)
                    m.save()
            # redirect to same page
            return HttpResponseRedirect('')

        # DELETE MESSAGE: If "delete message" was selected...
        elif 'delete' in request.POST: 
            for d in request.POST.getlist('del'): 
                m = Message.objects.get(id=d) 
                m.delete()

        # DECRYPT MESSAGE: If "decrypt" was selected...
        elif 'decrypt' in request.POST:
            u = User.objects.get(username=request.user)
            private_key = RSA.importKey(u.reporter.privatekey)
            # For each checked message...
            for d in request.POST.getlist('del'): 
                cipher = PKCS1_OAEP.new(private_key)
                m = Message.objects.get(id=d)
                try:
                    m.body = cipher.decrypt(b64decode(m.body)).decode(encoding='UTF-8')
                except:
                    # if invalid ciphertext blob
                    continue
                m.save()
    else:
        form = MessageForm()

    # Prepare messages for rendering...
    messages = Message.objects.filter(recipient=request.user)
    return render(request, 'messages.html', {'form': form, 'messages': messages})
 def initActive(self, self_prv_key, peer_pub_key):
     self.active = True
     
     self.self_prv_key = self_prv_key
     self.peer_pub_key = peer_pub_key
     
     self.self_asym_decrypter = PKCS1_OAEP.new(self.self_prv_key)
     self.peer_asym_encrypter = PKCS1_OAEP.new(self.peer_pub_key)
     
     self.self_signer = PKCS1_PSS.new(self.self_prv_key)
     self.peer_verifier = PKCS1_PSS.new(self.peer_pub_key)             
     return self
Beispiel #13
0
  def share(self, filename, user):

	'''probe if file/dir'''
	folder_metadata = self.dbxclient.metadata(self.cwd + "/" + filename)
	if folder_metadata['is_dir'] :
		isdir = True
	else:
		isdir = False

	''' get shadow file and update permissions'''
	'''Expect only one level in filename i.e. no dir1/dir2/file.txt'''
	if isdir:
		hostdirpath = self.cwd + "/" + filename
		shadowfile = hostdirpath + "/" + filename + ".sdw"
	else:
		shadowfile = self.cwd + "/" + filename + ".sdw"	

	localshadowfile = "users/" + self.username + "/" + filename + ".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:
		''' get the key '''
   		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)

		'''get the public key of user'''
	        row = self.dbhandle.getuser(user) 
		userpbkey = row[0]

	        '''Encrypt above decryptedkey using owner's public key '''
	        usercipher = PKCS1_OAEP.new(RSA.importKey(userpbkey))
	        userencryptedkey = usercipher.encrypt(decryptedkey)

		'''update permissions'''
		permtable[user] = base64.encodestring(userencryptedkey)


	        with open(localshadowfile, "w+") as sdw:
	             json.dump(permtable, sdw)

	        with open(localshadowfile, "r") as sdw:
	   	     response = self.dbxclient.put_file(shadowfile, sdw, overwrite=True)
	   	     #print(("Upload status: ",  response) )
		return
Beispiel #14
0
    def encrypt(self, message):
        # Init RSA with PKCS1_OAEP
        if self.rsa_key is None:
            self.load()       
        pkcs = PKCS1_OAEP.new(self.rsa_key, SHA256.new())

        # Init AES
        iv = self.generate_iv()
        pw = self.generate_pw('My secret password')

        aes_key = AES.new(pw, AES.MODE_CBC, iv)

        cipher = PKCS1_OAEP.new(self.rsa_key, SHA256.new())
        ciphertext = cipher.encrypt(message)
        return ciphertext
Beispiel #15
0
    def encrypt(self, data):
        offset = 0
        encrypted = "".encode()
        fp = open(self.public_key_path, 'rb')
        rsa_key = RSA.importKey(fp.read().decode())
        oaep_encryptor = PKCS1_OAEP.new(rsa_key)
        fp.close()
        print(len(data))
        while offset < len(data):
            chunk = data[offset:offset + self.chunk_size]
            if len(chunk) % self.chunk_size != 0:
                try:
                    chunk += " " * (self.chunk_size - len(chunk))
                except TypeError:
                    chunk = chunk.decode()
                    chunk += " " * (self.chunk_size - len(chunk))
                print('0enc length ' + str(len(chunk)))

            try:
                bin_chunk = chunk.encode()
            except AttributeError:
                # chunk is already here
                bin_chunk = chunk

            print('1enc length ' + str(len(bin_chunk)))

            encrypted_chunk = oaep_encryptor.encrypt(bin_chunk)
            print('11enc length ' + str(len(encrypted_chunk)))

            encrypted += encrypted_chunk
            offset += self.chunk_size

        return encrypted
Beispiel #16
0
def rename_directory(username, old_filename, new_filename):
    filelog = oldfilename + '.flog'
    with open(filelog, 'rb') as input:
        log = pickle.load(input)
        sig = pickle.load(input)
        
    block = log[username]

    key = RSA.importKey(open(username + '.pri').read())
    cipher = PKCS1_OAEP.new(key, SHA256.new())
    block.decrypt_permission_block(cipher)
    encrypted_new_filename = encrypt_filename(block.get_file_encryption_key(), new_filename)

    log['encrypted_name'] = encrypted_new_filename

    new_filelog = encrypted_new_filename + '.dlog'
    with open(new_filelog, 'wb') as outfile:
        pickle.dump(log)
    length = len(log)
    with open(new_filelog, 'rb') as infile:
        pickleload = infile.read(length)
    file_log_hash = SHA256.new()
    file_log_hash.update(picklelog)
    with open(username + '.dsa', 'rb') as infile:
        owner_msk = pickle.load(infile)
    k = random.StrongRandom().randint(1,owner_msk.q-1)
    sig = owner_msk.sign(file_log_hash.digest(), k)
    with open(new_filelog, 'a+b') as outfile:
        pickle.dump(sig, outfile, -1)

    return encrypted_new_filename
Beispiel #17
0
def decrypt_master_key(master_key_cipher, private_key):
    """
    Decrypt a secret key with the provided private RSA key.
    """
    key = RSA.importKey(private_key)
    cipher = PKCS1_OAEP.new(key)
    return cipher.decrypt(master_key_cipher)
Beispiel #18
0
def encrypt_master_key(master_key, public_key):
    """
    Encrypt a secret key with the provided public RSA key.
    """
    key = RSA.importKey(public_key)
    cipher = PKCS1_OAEP.new(key)
    return cipher.encrypt(master_key)
Beispiel #19
0
 def testEncryptDecrypt3(self):
         # Verify that OAEP supports labels
         pt = self.rng(35)
         xlabel = self.rng(22)
         cipher = PKCS.new(self.key1024, label=xlabel)
         ct = cipher.encrypt(pt)
         self.assertEqual(cipher.decrypt(ct), pt)
	def encrypt_file_rsa(self):
		ktu = force_integer_input("Key to use:")-1
		try:
			ktu_ac = self.key_list[ktu]
			print('2: SHA-512 with key rotation, hash chain and plaintext feedback')
			print('3: 3AES-EDE in CTR mode with independent keys and IV. 512-bit eq.')
			ver_rsa = 3
			try:
				ver_rsa = int(input('Version: [3] '))
			except ValueError:
				pass
			if ver_rsa == 2:
				kte, fnhd = encrypt_rsa_file_sha512v2()
			elif ver_rsa == 3:
				kte, fnhd = encrypt_rsa_file_aes_ede3_ctr()
			else:
				print('Try again!')
			print(kte)
			fnhd = fnhd + ".rsaheader"
			rsacipher = PKCS1_OAEP.new(ktu_ac,hashAlgo=SHA512)
			ciphered_header = rsacipher.encrypt(kte)
			rsah = open(fnhd,"wb")
			rsah.write(ciphered_header)
			rsah.close()
		except IndexError:
			print("Key not in keystore")
	def create_rsa_header(self, prov_key=None):
		ktu = ask_for_rsa_key(self, False)
		if ktu == None:
			showwarning(title="No Key Available",message="No suitable key for encryption is in Keystore.")
			return False,False,False
		try:
			ktu_ac = self.key_list[ktu]
			# Was 1024 bit previously, don't know why.
			# Reduced to 128 byte to match the PSK key.
			if prov_key == None:
				key_to_encrypt = create_random_key(128)
			else:
				key_to_encrypt = prov_key
			rsa_cipher = PKCS1_OAEP.new(ktu_ac,hashAlgo=SHA512)
			ciphered_key = rsa_cipher.encrypt(key_to_encrypt)
			# decrypted_key = rsa_cipher.decrypt(ciphered_key)
			#print(len(ciphered_key))
			header = bytearray()
			header.append(create_random_upper_half())
			header.extend(ciphered_key)
			header.extend(create_random_key(2047))
			return header, key_to_encrypt, True
		except IndexError:
			showerror(title="Please report this error",message="Keystore selected key out of index.")
			return False, False, False
Beispiel #22
0
def encrypt_string(plaintext):

	chunk_size = 256
	print "Compressing: %d bytes" % len(plaintext)
	plaintext = zlib.compress(plaintext)

	print "Encrypting %d bytes" % len(plaintext)

	rsakey = RSA.import(public_key)
	rsakey = PKCS1_OAEP.new(rsakey)

	encrypted = ""
	offset = 0

	while offset < len(plaintext):
		chunk = plaintext[offset:offset+chunk_size]

		if len(chunk) % chunk_size !=0:
			chunk += " " *(chunk_size - len(chunk))

		encrypted += rsakey.encrypt(chunk)
		offset += chunk_size

	encrypted = encrypted.encode("base64")

	print "Base64 encoded crypto: %d" % len(encrypted)

	return encrypted
Beispiel #23
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32+dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
Beispiel #24
0
def main():
	port = 60005
	IP = '127.0.0.1'

	pub_key = """-----BEGIN PUBLIC KEY-----
	MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeNVj2v/gT/eHZm1RSH1w5dkzc
	MyhA/nbSrAV6KWiDCjKKXK1si5+0llK9eUcCf55F5swag1JYzxxVaJQyMFUAImsV
	J+3OMysYLDZCN2tAeYzlSZptPs/JY0KaFRNXinDG9EyaTdpvrC4d72KT8qw5eDwS
	gyR1XwJKoRUGYjki+wIDAQAB
	-----END PUBLIC KEY-----"""


	S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	S.settimeout(5)

	try:
		S.connect((IP, port))
		while 1:
			plaintext = raw_input("What message should we encrypt?: ").rstrip()
			if plaintext == "stop":
				S.close()
				sys.exit(1)
				
			print "Compressing %d bytes" % len(plaintext)
			plaintext = zlib.compress(plaintext)
			print "Encrypting %d bytes" % len(plaintext)
			rsakey = RSA.importKey(pub_key)
			rsakey = PKCS1_OAEP.new(rsakey)
			encrypted = rsakey.encrypt(plaintext)
			S.send(encrypted)

	except Exception, e:
		print "Error: " + str(e)
	def decipherRequest(request):
		key = open('server.pem','r')
		rsa = RSA.importKey(key)
		privdecipher = PKCS1_OAEP.new(rsa)
		key.close()
		deciphered = privdecipher.decrypt(request.decode('hex'))
		return json.loads(deciphered) 
    def redirect(self, encryption_key):
        """Throws an exception that indicates we should redirect.

        This is built to work around AWS' API Gateway's limitations. We want to
        be able to serve both 200s and 302s, but API Gateway only allow one type
        of response code on success. So to serve both 200s and 302s, we need to
        throw an exception for at least one of these, and we choose to do this
        for 302s.

        The next limitation is that when a lambda function throws exceptions, it
        returns a dictionary like
        {
            stackTrace: [],
            errorType: "",
            errorMessage: ""
        }
        so in order to pass the redirect url along, we need to fit it into one
        of these. The API Gateway allows us to read these fields, but not do
        post processing. So we make the error message be exactly the url we
        want.
        """
        # TODO: make sure email and password aren't url encoded.
        cipher = PKCS1_OAEP.new(encryption_key)
        token = json.dumps({"email": self.email, "password": self.password})
        encrypted_token = cipher.encrypt(token)
        # url encoding can handle the encrypted token, but b64 encoding it makes
        # it short and arguably nicer to read
        encoded_encrypted_token = base64.b64encode(encrypted_token)
        fragment = urllib.urlencode({
            "state": self.state,
            "token_type": "bearer",
            "access_token": encoded_encrypted_token
        })
        url = REDIRECT_URI + "#" + fragment
        raise RedirectException(url)
Beispiel #27
0
def rsa_decrypt(data, rsa_priv_key_str):
    """
    When given some `data` and an RSA private key, decrypt the data
    """
    key = RSA.importKey(rsa_priv_key_str)
    cipher = PKCS1_OAEP.new(key)
    return cipher.decrypt(data)
Beispiel #28
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
Beispiel #29
0
    def encryptString(self, inputstr):
        i = 0
        obj = bytearray(5)
        rsaKey, obj = self.createKeyFromString(self.KEY, obj)
        if rsaKey is None:
            return ""

        try:
            bytes = inputstr.encode('utf-8')
            bLen = int(((len(bytes) - 1) / 86)) + 1
            obj2 = bytearray(bLen * 133)
            encryptor = PKCS1_OAEP.new(rsaKey)
            while i < bLen:
                offset = i * 86
                strlen = (len(bytes) - offset if i == (
                bLen - 1) else 86) + offset

                encstr = encryptor.encrypt(bytes[offset:strlen])
                obj2[i * 133:i * 133 + len(obj)] = obj
                obj2[
                i * 133 + len(obj):i * 133 + len(obj) + len(encstr)] = encstr
                i += 1

            return base64.urlsafe_b64encode(obj2)
        except Exception as e:
            print(e)
            return ""
Beispiel #30
0
def read_encrypted_logs(username, filelogs):
    names = []
    my_key = RSA.importKey(open(username + '.pri').read())
    cipher = PKCS1_OAEP.new(my_key, SHA256.new())

    for log in filelogs:
        file_log_hash = SHA256.new()
        with open(log, 'rb') as input:
            dictlog = pickle.load(input)
            sig = pickle.load(input)
        owner = dictlog['owner']
        with open(owner + '.dsapub', 'rb') as input:
            owner_msk = pickle.load(input)
        length = len(dictlog)
        with open(log, 'rb') as outfile:
            picklelog = outfile.read(length)
        file_log_hash.update(picklelog)

        if not owner_msk.verify(file_log_hash.digest(), sig):
            print('invalid file')

        if username in dictlog:
            block = dictlog[username]
            block.decrypt_permission_block(cipher)
            name = decrypt_filename(block.get_file_encryption_key(), log[0:-5])
            names.append(name)
              
    return names
Beispiel #31
0
 def load_key(self, pub_key):
     self.public_key = RSA.importKey(pub_key)
     self.encryptor = PKCS1_OAEP.new(self.public_key)
 def descifrar_clave(self, clave_cifrada):
     # Descifra la clave de sesión con la clave RSA privada
     p_key = RSA.import_key(self.clave_privada)
     cipher_rsa = PKCS1_OAEP.new(p_key)
     clave = cipher_rsa.decrypt(clave_cifrada)
     return clave
Beispiel #33
0
def decrypt_password(password, privkey_path):
    """Decrypts a user password."""
    key = RSA.importKey(open(privkey_path).read())
    RSA_CIPHER = PKCS1_OAEP.new(key)
    return RSA_CIPHER.decrypt(password).decode('ascii')
Beispiel #34
0
#!/usr/bin/python3

from socket import *
from base64 import b64decode, b64encode
from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

s = socket(AF_INET, SOCK_STREAM)
s.connect(('crypto.byteband.it', 7002))
while True:
    x = s.recv(1024)
    print(x)
    x = x.split(b'\n')
    p = x[-6].split(b' ')[-1]
    n = eval(b'0x' + x[-4]) - 1
    assert n % 4 == 0
    n = n // 4

    key = RSA.RsaKey(e=65537, n=n)
    rsa = PKCS1_OAEP.new(key)
    p = rsa.encrypt(b64decode(p))
    s.send(b64encode(p) + b'\n')
Beispiel #35
0
def decrypt(ciphertext, priv_key):
    #RSA encryption protocol according to PKCS#1 OAEP
    cipher = PKCS1_OAEP.new(priv_key)
    return cipher.decrypt(ciphertext)
Beispiel #36
0
client_cert = handle_message(clientsocket).decode()
client_cert = crypto.load_certificate(crypto.FILETYPE_PEM, client_cert)
if not certificate.verify_cert(client_cert):
    print("Client certificate is false, ending connection")
    clientsocket.close()
    sys.exit(1)
print("Client certificate is alright")
client_pubkey = client_cert.get_pubkey()
client_pubkey = RSA.import_key(
    crypto.dump_publickey(crypto.FILETYPE_PEM, client_pubkey))

session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(client_pubkey)
enc_session_key = cipher_rsa.encrypt(session_key)

send(clientsocket, enc_session_key)
print("sending crypted aes key")

cipher = AES.new(session_key, AES.MODE_EAX)

while True:
    data = input("Enter message: ")
    if data:
        ciphertext, tag = cipher.encrypt_and_digest(data.encode())

        send(clientsocket, cipher.nonce + tag + ciphertext)
        cipher = AES.new(session_key, AES.MODE_EAX)
Beispiel #37
0
 def __init__(self, key_size=3072):
     random_generator = Random.new().read
     self.private_key = RSA.generate(key_size, random_generator)
     self.public_key = self.private_key.publickey()
     self.decryptor = PKCS1_OAEP.new(self.private_key)
     self.encryptor = PKCS1_OAEP.new(self.public_key)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

secret_code = "Unguessable"  # rsa key passw

path = os.path.expanduser("~/.ransom/.key")
pem_path = "public_key_gen/rsa_key.bin"

file_in = open(path, "rb")

encoded_key = open(pem_path, "rb").read()
private_key = RSA.importKey(encoded_key, passphrase=secret_code)

cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(file_in.read())

file_out = open(os.path.expanduser("~/.ransom/.clear_key"), 'wb')
file_out.write(session_key)
file_out.close()
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP




with open('EMAIL_ME.txt', 'rb') as f:
    enc_fernet_key = f.read()
    print(enc_fernet_key)

# Private RSA key
private_key = RSA.import_key(open('private.pem').read())

# Private decrypter
private_crypter = PKCS1_OAEP.new(private_key)

# Decrypted session key
dec_fernet_key = private_crypter.decrypt(enc_fernet_key)
with open('PUT_ME_ON_DESKTOP.txt', 'wb') as f:
    f.write(dec_fernet_key)

print(f'> Private key: {private_key}')
print(f'> Private decrypter: {private_crypter}')
print(f'> Decrypted fernet key: {dec_fernet_key}')
print('> Decryption Completed')

Beispiel #40
0
def encrypt(message, pub_key):
    #RSA encryption protocol according to PKCS#1 OAEP
    cipher = PKCS1_OAEP.new(pub_key)
    return cipher.encrypt(message)
Beispiel #41
0
    if 'ec' != privateFile.readline().rstrip().decode("utf-8"):
        print("Error: Incorrect private certificate, EC required.")
        exit(1)

    #Read in certificate keys
    tmpPubKey = ''
    for line in publicFile:
        tmpPubKey += line.decode("utf-8")

    tmpPrivKey = ''
    for line in privateFile:
        tmpPrivKey += line.decode("utf-8")

    #Generate and encrypt AES key via RSA
    rsaPubKey = RSA.import_key(tmpPubKey)
    rsaCipher = PKCS1_OAEP.new(rsaPubKey)

    key = get_random_bytes(32)
    cipherText = rsaCipher.encrypt(key)

    #Sign encrypted AES key
    ecPrivKey = ECC.import_key(tmpPrivKey)
    ecSigner = DSS.new(ecPrivKey, 'fips-186-3')
    cipherSig = ecSigner.sign(SHA256.new(cipherText))

    #Encrypt directory
    for dirName, subdirlist, filelist in os.walk(rootDir):
        for file in filelist:
            encrypt_file(key, dirName + '/' + file)

    #Write keyfile and signature to files
Beispiel #42
0
public_key = ""

for line in pub_in:
    if line.strip() == "subject:":
        break
    else:
        public_key += line

pub_in.close()

#Get and encrypt AES key

aes_key = get_random_bytes(16)  #256 bit

rsa_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_OAEP.new(rsa_key)
enc_aes_key = cipher_rsa.encrypt(aes_key)

#We will write the encrypted AES key to keyfile

keyfile_out = open("keyfile", "wb")
keyfile_out.write(enc_aes_key)
keyfile_out.close()

#Get private key

priv_in = open(privateKeyPath, "r")

private_key = ""

for line in priv_in:
Beispiel #43
0
def encrypt(message, pub_key):
    cipher = PKCS1_OAEP.new(pub_key)
    return cipher.encrypt(message)
Beispiel #44
0
    def encrypt_oaep(self, data):
        cipher = PKCS1_OAEP.new(self.key)
        ct = cipher.encrypt(data)

        return bytes_to_hex(ct)
Beispiel #45
0
#/usr/bin/env python

from Crypto.PublicKey import RSA, DSA
from Crypto.Random import random, atfork
from Crypto.Cipher import PKCS1_OAEP

import SocketServer,threading,os,time
import socket

from priv import privkey, privkey_enc
# corresponding public keys for clients:
_server_pub_enc = RSA.importKey('-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGRrsdIqf8K39Ncwzsi9k2lr5G\nJ8aEFkYGrYqOQRbU5xOReMj8wWHgnSUC0fjH0gjffGiUC2HfrrNIQvXKGiSBetOu\nIWOmFiESG8IhrPyvLwX53NbMWeCihzbYGJxGyiL0bvDHxqDxzuvteSaEfNm1miPA\nQ9rs5vFnHM0R3kFjdQIDAQAB\n-----END PUBLIC KEY-----')
server_pub_enc = PKCS1_OAEP.new(_server_pub_enc)
server_pub_sig = DSA.construct([6492988819243051335053735606322819439099395961135352303030066825351059776939776358522765113843576255727411249922052441719518573282010295240606387519552263L,5720927070571587652595864015095152811124313453716975619963331476834195150780326792550956895343289380256771573459290257563350163686508250507929578552744739L,6703916277208300332610863417051397338268350992976752494932363399494412092698152568009978917952727431041521105933065433917303157931689721949082879497208537,1022875313346435070370368907571603203095488145799L])

msg = """/------------------------------------------------------------------------------\\
| Welcome to the betting parlor version 2!                                     |
|                                                                              |
| Here's how it works: you choose your betting odds and an amount to bet, and  |
| then you send us your guessed value. We then pick a secure random number.    |
| If random number % odds == guessed value, you win!                           |
|                                                                              |
| In order to address complaints of cheating, your guessed value is sent to us |
| encrypted. Therefore, our random number will not be generated adversarially! |
|                                                                              |
| To encourage use of our service after the issues with version 1, we have     |
| decided to give all new users of the service $100. Wow! Such gratitude!      |
|                                                                              |
| (Oh, and if you win a billion dollars, we'll give you a flag.)               |
\______________________________________________________________________________/
"""
Beispiel #46
0
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

data = "I met aliens in UFO. Here is the map.".encode("utf-8")
file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[
    file_out.write(x)
    for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)
]
file_out.close()
Beispiel #47
0
def decrypt(ciphertext, priv_key):
    cipher = PKCS1_OAEP.new(priv_key)
    return cipher.decrypt(ciphertext)