Esempio n. 1
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 decode_token(token, secret_key, salt, max_age_in_seconds=ONE_DAY_IN_SECONDS):
    fernet = Fernet(to_bytes(secret_key))
    cleartext = fernet.decrypt(token, ttl=max_age_in_seconds)
    token_salt, json_data = cleartext.split(b'\0', 1)
    if token_salt != to_bytes(salt):
        raise InvalidToken('bad token')
    return json.loads(json_data.decode('utf-8'))
Esempio n. 3
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)
Esempio n. 4
0
def _bootstrap(secrets):
    """
    Decrypt secrets and return a dict of secrets.
    """
    if not secrets:
        logging.info('SECRETS_BOOTSTRAP not set, skipping bootstrapping.')
        return {}
    if secrets.startswith('file://'):
        try:
            with open(secrets[7:], 'r') as f:
                _secrets = json.load(f)
        except IOError:
            logging.error(
                'Failed to load file specified in SECRETS_BOOTSTRAP.'
            )
            return {}
    else:
        _secrets = json.loads(secrets)
    key = cryptolib.decrypt_datakey(
        base64.b64decode(_secrets['data_key']),
        {'type': 'bootstrap'}
    )
    f = Fernet(key)
    decrypted_secrets = yaml.safe_load(
        f.decrypt(_secrets['secrets'].encode('utf-8'))
    )
    logging.info('Loaded SECRETS_BOOTSTRAP.')
    return decrypted_secrets
Esempio n. 5
0
def sso_lander_view(group):
    """
    Log a user into the system using a signed and encrypted get argument "token".

    Here a ttl of 60 seconds is life. See
    https://cryptography.io/en/latest/fernet/#cryptography.fernet.Fernet.decrypt.
    """
    secret = redis_cli.get('secret:{}'.format(group))
    if not secret:
        return 'group not found', 404
    fernet = Fernet(secret)

    token = request.args.get('token', '').encode('utf8')
    try:
        data = fernet.decrypt(token, ttl=60)
    except InvalidToken:
        return '403: Invalid Token', 403

    try:
        data = json.loads(data.decode('utf8'))
    except JSONDecodeError:
        return '400: problem parsing json', 400
    data['referrer'] = request.referrer
    session.update(
        profile=data,
        group=group,
    )

    group_key = 'info:{}'.format(group)
    redis_cli.lpush(group_key, '{nm} ({rt}) logged in at {dt:%Y-%m-%d %H:%M:%S}'.format(dt=datetime.now(), **data))
    return redirect('/')
Esempio n. 6
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)
Esempio n. 7
0
def addcrypted2():
    package = flask.request.form.get(
        "package", flask.request.form.get("source", flask.request.form.get("referer"))
    )
    crypted = flask.request.form["crypted"]
    jk = flask.request.form["jk"]

    crypted = standard_b64decode(unquote(crypted.replace(" ", "+")))
    jk = js2py.eval_js(f"{jk} f()")

    try:
        key = bytes.fromhex(jk)
    except Exception:
        return "Could not decrypt key", 500

    obj = Fernet(key)
    urls = obj.decrypt(crypted).replace("\x00", "").replace("\r", "").split("\n")
    urls = [url for url in urls if url.strip()]

    api = flask.current_app.config["PYLOAD_API"]
    try:
        if package:
            api.add_package(package, urls, 0)
        else:
            api.generate_and_add_packages(urls, 0)
    except Exception:
        return "failed can't add", 500
    else:
        return "success\r\n"
Esempio n. 8
0
def decrypt_creds(dbname, dbuser, dbpass, dbport):
    """
    Decrypt DB creds.

    Default Creds in vars.py are decrypted and returned.
    :return db_name, db_user, db_pass, db_port:
    """
    if (os.path.exists(keyfile)):
        authkey = open(keyfile, 'rb').read()
        # print(authkey)
    else:
        print ("Key File '{}' 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)

    db_name = (f.decrypt(byte_dbname)).decode()
    db_user = (f.decrypt(byte_dbuser)).decode()
    db_pass = (f.decrypt(byte_dbpass)).decode()
    db_port = (f.decrypt(byte_dbport)).decode()

    print("DBNAME = {} DBUSER = {} DBPASS = {} DBPORT = {}"
          .format(db_name, db_user, db_pass, db_port))

    return (db_name, db_user, db_pass, db_port)
Esempio n. 9
0
def get_creds(dbname, dbuser, dbpass, dbport):
    """
    Decrypt creds.

    Creds are provided as arguments to this routine,
    decrypted and returned.
    :param dbname:
    :param dbuser:
    :param dbpass:
    :param dbport:
    :return db_name, db_user, db_pass, db_port:
    """
    if (os.path.exists(keyfile)):
        authkey = open(keyfile, 'rb').read()
        # print(authkey)
    else:
        print("Key File '{}' 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)

    db_name = (f.decrypt(byte_dbname)).decode()
    db_user = (f.decrypt(byte_dbuser)).decode()
    db_pass = (f.decrypt(byte_dbpass)).decode()
    db_port = (f.decrypt(byte_dbport)).decode()
    # print("DBNAME = {} DBUSER = {} DBPASS = {} DBPORT = {}"\
    # .format(db_name, db_user, db_pass, db_port))
    return (db_name, db_user, db_pass, db_port)
Esempio n. 10
0
def unlock(path=None):
    """
    Decrypts all of the files in a given directory with provided password.
    This is most commonly used during the startup sequence of Lemur
    allowing it to go from source code to something that can communicate
    with external services.

    Path defaults ~/.lemur/keys

    :param: path
    """
    key = prompt_pass("[!] Please enter the encryption password")

    if not path:
        path = os.path.expanduser('~/.lemur/keys')

    dest_dir = os.path.join(path, "decrypted")
    source_dir = os.path.join(path, "encrypted")

    if not os.path.exists(dest_dir):
        sys.stdout.write("[+] Creating decryption directory: {0}\n".format(dest_dir))
        os.makedirs(dest_dir)

    for root, dirs, files in os.walk(source_dir):
        for f in files:
            source = os.path.join(source_dir, f)
            dest = os.path.join(dest_dir, ".".join(f.split(".")[:-1]))
            with open(source, 'rb') as in_file, open(dest, 'wb') as out_file:
                f = Fernet(key)
                data = f.decrypt(in_file.read())
                out_file.write(data)
                sys.stdout.write("[+] Writing file: {0} Source: {1}\n".format(dest, source))

    sys.stdout.write("[+] Keys have been unencrypted!\n")
Esempio n. 11
0
 def test_verify(self, secret, now, src, ttl_sec, token, backend,
                 monkeypatch):
     f = Fernet(secret.encode("ascii"), backend=backend)
     current_time = calendar.timegm(iso8601.parse_date(now).utctimetuple())
     monkeypatch.setattr(time, "time", lambda: current_time)
     payload = f.decrypt(token.encode("ascii"), ttl=ttl_sec)
     assert payload == src.encode("ascii")
Esempio n. 12
0
 def decrypt(self, password):
     """
     Return the plain text token after decrypting it using the password.
     """
     fernet = Fernet(crypto.derive_fernet_key(password, self.salt))
     return encoding.force_str(
         fernet.decrypt(encoding.force_bytes(self.encrypted)))
Esempio n. 13
0
def decrypt(data, symmetric_key=None, private_key=None):
    """
    Decrypts data with symmetric key or public key.
    """
    if symmetric_key:
        try:
            fernet = Fernet(symmetric_key)
            return fernet.decrypt(data)
        except InvalidToken:
            raise errors.AuthenticationError(
                message=_('Invalid credentials'))

    elif private_key:
        try:
            private_key_obj = load_pem_private_key(
                data=private_key,
                password=None,
                backend=default_backend()
            )
            return private_key_obj.decrypt(
                data,
                padding.OAEP(
                    mgf=padding.MGF1(algorithm=hashes.SHA1()),
                    algorithm=hashes.SHA1(),
                    label=None
                )
            )
        except ValueError:
            raise errors.AuthenticationError(
                message=_('Invalid credentials'))
Esempio n. 14
0
def get_oracle_password():
    """
    Return my oracle password
    
    Uses cryptography.fernet to unencrypt password.
    
    """
   
    key = get_key()
    
    # read password
    try:
        f2 = open(password_dir+password_file, 'rb')
    except IOError as e:
        if e.strerror == 'No such file or directory':
            print("Could not find password file")
            sys.exit()
        else:
            raise e
    token=f2.read()
    f2.close()

    # decript password
    f = Fernet(key)
    password = f.decrypt(token).decode('utf-8')

    return password
Esempio n. 15
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()
Esempio n. 16
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.")
Esempio n. 17
0
def encrypted_read(file, key):
    """
    Read an encrypted file.

    Parameters
    ----------
    file : str
    key : str

    Returns
    -------
    d : bytes
        The decrypted data.
    """
    logging.info("opening encrypted file `{}`".format(file))
    with open(file, 'rb') as openf:
        data = openf.read()

    f = Fernet(key)

#    return io.BytesIO(f.decrypt(data))
#    return f.decrypt(data)

    logging.debug("decrypting...")
    try:
        d = f.decrypt(data)
        logging.debug("decryption complete")
    except InvalidToken:
        logging.exception("Key Mismatch with file! Unable to decrypt!")
        raise

    return d
Esempio n. 18
0
def getReaction(rid):
    ''' Lookup a reaction via either rethinkdb or redis '''
    # Pull from redis first
    cache = lookupRedis("reaction", rid)
    # Resolve issues form race condition during editing of reactions
    if "lastrun" in cache:
        if cache['lastrun'] is None or cache['lastrun'] is "None":
            # Reset lastrun to 0 if it is not present or set to None
            cache['lastrun'] = 0
    else:
        cache['lastrun'] = 0

    # Pull from RethinkDB second
    try:
        results = r.table('reactions').get(rid).run(rdb_server)
        if results['lastrun'] is None:
            results['lastrun'] = 0
        results['cacheonly'] = False
        if int(cache['trigger']) > results['trigger']:
            results['trigger'] = int(cache['trigger'])
        if float(cache['lastrun']) > float(results['lastrun']):
            results['lastrun'] = float(cache['lastrun'])
        if "encrypted" in results:
            if results['encrypted'] is True:
                crypto = Fernet(config['crypto_key'])
                results['data'] = json.loads(crypto.decrypt(bytes(results['data'])))
    except (RqlDriverError, RqlRuntimeError, socket.error) as e:
        results = cache
        results['cacheonly'] = True
        logger.critical("RethinkDB is unaccessible, reaction %s was pulled from cache" % rid)
        logger.critical("RethinkDB Error: %s" % e.message)
    return results
Esempio n. 19
0
def sql_call():
    print("Connecting to Database and Running Query")
    host = "emaildata.cqlai0yteoyb.us-east-1.redshift.amazonaws.com"
    port = 5439
    database = "eds"
    user = "******"

    f = open('eds_key.txt', r)
    key = f.read()
    f.close()
    f = open('eds_password.txt', r)
    cipher_text = f.read()
    f.close()
    cipher_suite = Fernet(key)
    password = cipher_suite.decrypt(cipher_text)

    conn = psychopg2.connect(database=database, user=user, host=host, port=port, password=password, sslmode='allow')
    cur = con.cursor(name = "conquer")

    query = "SELECT * FROM email WHERE from_domain = 'googlemail.com' AND message_time >= CURRENT_DATE -10 LIMIT 3"

    print(query)
    cur.execute(query)

    resultsTable = cur.fetchmany(10)
    for row in resultsTable:
        print(row)

    conn.close()
Esempio n. 20
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
Esempio n. 21
0
    def test_formatter(self):

            for prefix in ['±±±', 'abc']:

                with LogCapture() as lc:

                    data = '{}{}'.format(prefix, uuid4().hex)
                    key = genkey()
                    fernet = Fernet(key)

                    level = logging.INFO
                    format = '%(levelname)s - %(message)s'
                    formatter = EncryptedLogFormatter(key, format)

                    handler = logging.StreamHandler()
                    handler.setFormatter(formatter)

                    logger = logging.getLogger('')
                    logger.addHandler(handler)
                    logger.setLevel(level)

                    logger.info(data)

                    encrypted = list(lc.records)[0].msg
                    encrypted = encrypted.split(log_prefix)[1]
                    decrypted = fernet.decrypt(encrypted.encode('utf8')).decode('utf8')

                    self.assertEquals(data, decrypted)
Esempio n. 22
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)
    def test_no_hkdf(self):
        """Can supply use_hkdf=False to avoid HKDF."""
        k1 = Fernet.generate_key()
        f = fields.EncryptedTextField(key=k1, use_hkdf=False)
        fernet = Fernet(k1)

        assert fernet.decrypt(f.fernet.encrypt(b'foo')) == b'foo'
Esempio n. 24
0
    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()
Esempio n. 25
0
 def decrypt(self, save_content=False):
     if self.encryption_key is None:
         raise LocalConfigFileError('Cannot decrypt content, missing encryption key.')
     if self.config.get('content') is None:
         raise LocalConfigFileError('Cannot decrypt content, content is empty.')
     if self.is_encryptable == False:
         raise LocalConfigFileError('Cannot decrypt, improper configuration.')
     if self.config.get('is_encrypted') == False:
         return self.config.get('content')
     
     f = Fernet(self.encryption_key)
     if self.config.get('is_binary') == True:
         decr_content = f.decrypt(self.config.get('content'))
     elif self.config.get('is_binary') == False:
         decr_content = f.decrypt(self.config.get('content').encode('utf-8')).decode('utf-8')
     else:
         raise LocalConfigFileError('Could not tell if file is binary or text. Aborting.')
     if save_content == True:
         try:
             self.config['content'] = decr_content
             self.config['content_length'] = len(decr_content)
             self.config['is_encrypted'] = False
         except:
             raise
     return decr_content
    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
Esempio n. 27
0
    def get_data(self, user):
        if not self.current_revision:
            raise Http404
        if not self.is_readable_by_user(user):
            log(
                _("{user} tried to access '{name}' without permission").format(name=self.name, user=user.username),
                actor=user,
                level="warn",
                secret=self,
            )
            raise PermissionError(
                _("{user} not allowed access to '{name}' ({id})").format(id=self.id, name=self.name, user=user.username)
            )
        f = Fernet(settings.TEAMVAULT_SECRET_KEY)
        log(
            _("{user} read '{name}'").format(name=self.name, user=user.username),
            actor=user,
            level="info",
            secret=self,
            secret_revision=self.current_revision,
        )
        self.current_revision.accessed_by.add(user)
        self.current_revision.save()
        self.last_read = now()
        self.save()

        plaintext_data = f.decrypt(self.current_revision.encrypted_data.tobytes())
        if self.content_type != Secret.CONTENT_FILE:
            plaintext_data = plaintext_data.decode("utf-8")
        return plaintext_data
Esempio n. 28
0
def get_viewcams():
    page = request.args.get('page', 1, type=int)
    email = SVSuserReg.query.filter_by(emid=g.current_user.emid).first()
    pagination = SVSIpCamReg.query.filter_by( u_id = email.id ).order_by(SVSIpCamReg.camregdate.desc()).paginate(page, per_page=current_app.config['SVS_PAGE_PHOTO'],error_out=False)
    regcams = pagination.items
    for cams in regcams:
        camkey = cams.key
        bcamskey = bytes(camkey)
        camurlhash = cams.camurl_hash
        bcamurlhash = bytes(camurlhash)
        f = Fernet(bcamskey)
        finalurl = f.decrypt(bcamurlhash)
        cams.camurl_hash = finalurl
    prev = None
    if pagination.has_prev:
        prev = url_for('api_5.get_viewcams', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api_5.get_viewcams', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in regcams],
        'prev': prev,
        'next': next,
        'count': pagination.total
    })
def FDStart():
    camtab = SVSIpCamReg.query.filter_by(u_id = current_user.id).first()

    dkey = camtab.key
    bdkey=bytes(dkey)
    f = Fernet(bdkey)
    bcamurl = bytes(camtab.camurl_hash)
    camurl =f.decrypt(bcamurl)
    url=str(camurl)
    if camtab.FDstore == 1:
        cam = Cam(url)
        #cam.start()
        cam.run()
        emid = SVSuserReg.query.filter_by(emid=current_user.emid).first()
        camid = SVSIpCamReg.query.filter_by(u_id = current_user.id).first()
        camfaces = SVSFaceTab.query.filter_by(cam_id = camid.u_id , u_id = emid.id ).all()

        '''for rec in camfaces:
            camfacesimag=rec.Face_image
            #response = make_response(camfacesimag)
            #response.headers["Content-type"] = "image/jpeg"
            #response.headers['Content-Disposition'] = 'attachment; filename=img.jpg'
            #rec.Face_imagenew = response
            rec.Face_imagenew = send_file(io.BytesIO(camfacesimag),attachment_filename='logo.png',mimetype='image/png')
        return render_template('FaceDetect/FaceShow.html',allface = camfaces)'''

    else:
       print("I am in else none")
Esempio n. 30
0
def backfill_plaintext_hashes(apps, schema_editor):
    SecretRevision = apps.get_model('secrets', 'SecretRevision')
    f = Fernet(settings.TEAMVAULT_SECRET_KEY)
    for srev in SecretRevision.objects.all():
        plaintext_data = f.decrypt(srev.encrypted_data.tobytes())
        srev.plaintext_data_sha256 = sha256(plaintext_data).hexdigest()
        srev.save()
def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)
# ## Cargamos nuestra clave privada de un fichero.pem
# ## Load our private key from a .pem file

# with open ('clave_privada_cliente.pem','rb') as key_file:
#     private_key_client = serialization.load_pem_private_key(
#         key_file.read(),
#         password = None,
#         backend = default_backend()
#     )

file = open('clave_test', 'r')
keylist = file.readlines()
key_aux = keylist[0]
key = str.encode(key_aux)
f = Fernet(key)

#########################################################################
##                           MAIN LOOP                                 ##
#########################################################################

while True:

    correcto = False  # var to check if the user input is correct
    query = False  # var to check if the message is a query
    input("\n Pulsa enter para desplegar el menu ")

    imprimir_niveles()

    ## Capturamos la entrada del teclado y comprobamos si es una entrada válida
    ## take the input from console until there is a valid input
Esempio n. 33
0
import sys
import os

sys.path.append(os.path.abspath('../'))
from openpyxl import Workbook, load_workbook
from cryptography.fernet import Fernet
from main import dev_manner

wb = load_workbook("cap.xlsx")
page = wb.active

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

f = Fernet(key)


def reg(uad, pad):

    m_row = page.max_row
    #print(m_row)
    for i in range(1, m_row + 1):
        val = page.cell(row=i, column=1)
        fval = val.value
        dec = f.decrypt(fval.encode())
        dam = dec.decode()
        if (dam == uad):
            pval = page.cell(row=i, column=2)
            pal = pval.value
            pdec = f.decrypt(pal.encode())
Esempio n. 34
0
 def decrypt(encrypt_key, encrypted_content):
     return Fernet(encrypt_key).decrypt(encrypted_content.encode()).decode("utf-8")
Esempio n. 35
0
 def encrypt(encrypt_key, content):
     return Fernet(encrypt_key).encrypt(content.encode()).decode("utf-8")
class userThread(threading.Thread):
	def __init__(self,host,portNumber,maxUsersCount):
		self.host=host
		self.maxUsersCount=maxUsersCount
		self.total_user=0
		self.connecting_users=[]#keep track of connecting users
		self.portNumber=portNumber
		self.threads=[]#list of socket thread
		self.users=[]#list of usernames of the connected clients
		self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		self.sock.bind((host,portNumber))
		self.shared_key=b'gWEdcvtXUknmH8li0G_Aj0DrtJPyrg9SP38_zG-0o10='
		self.f=Fernet(self.shared_key)
	def run(self):
		self.sock.listen(5)
		try:
			while True:
				usrsock,addr=self.sock.accept()
				#if maximum number of connection reached, send back the #busy status
				#to the client and close its connection
				if self.total_user==self.maxUsersCount:
					token=self.f.encrypt(b"#busy")
					usrsock.send(token)
					usrsock.close()
				else:
					token=self.f.encrypt(b"#notbusy")
					usrsock.send(token)
					self.threads.append(usrsock)
					self.total_user+=1
					print("Current user count=",self.total_user)
					threading.Thread(target=self.thread_handler,args=(usrsock,)).start()
			self.sock.close()
		except socket.error as err:
			print(err)
			sys.exit()

	def thread_handler(self,usrsock):
		while True:
			try:
				resp=self.f.decrypt(usrsock.recv(1024)).decode()#receiving data
				if resp.startswith('#join'):
					usr=resp.replace('#join','').lstrip()
					if usr in self.users:
						global i
						usr=usr+str(i)
						token=self.f.encrypt(("#usernametaken %s"%usr).encode())
						usrsock.send(token)
						i+=1
					self.broadcast("#newuser %s"%usr,usrsock)
					self.users.append(usr)
					token=self.f.encrypt(("#welcome %s"%usr).encode())
					usrsock.send(token)
		        	#in order to prevent this thread to send 2 packets at the same time
		        	#let it sleep for 1 sec so data can arrive in sequence, not at the same time
					time.sleep(1)
					print("Current connecting users:")
					for usr in self.users:
						print(usr)
					if len(self.users)>1:
						for i in range(0,len(self.users)):
							if self.users[i]!=usr:
								token=self.f.encrypt(("#prevjoined %s"%self.users[i]).encode())
								usrsock.send(token)
							#announce to all the clients that a new user has joined
				if resp.startswith('#status'):
					token=self.f.encrypt("#statusPosted".encode())
					usrsock.send(token)
					status=resp.replace('#status','').lstrip()
					#broadcast status to all other users
					self.broadcast("#newStatus %s:%s"%(usr,status),usrsock)#changed from Ibroadcast, work but doesn't look good, lets try gui!
				if resp.startswith('#Bye'):
					self.broadcast("#Leave %s"%usr,usrsock)
					#broadcast message to all other users saying that a user is leaving
					token=self.f.encrypt("#Bye".encode())
					usrsock.send(token)
					self.threads.remove(usrsock)#remove that user thread
					self.total_user-=1 #subtract 1 from total user
					self.users.remove(usr)#remove username from list
					print("Current user count=",self.total_user)
					self.usr=""#set username to empty
					usrsock.close()
					break
			except IOError as err:
				print(err)
				sys.exit()
#broadcast messages to all clients except the connecting one
	def broadcast(self,message,sock):
		for thread in self.threads:
			if thread!=sock:
				token=self.f.encrypt(message.encode())
				thread.send(token)

	def Ibroadcast(self,message):
		for thread in self.threads:
			token=self.f.encrypt(message.encode())
			thread.send(token)
Esempio n. 37
0
from cryptography.fernet import Fernet

# Saving the key in a separate file for later usage
file = open('key.key', 'rb')  # Open the file as wb to write bytes
key = file.read()  # The key is type bytes still
file.close()

# Open the file to encrypt
f = open('test.txt.encrypted', 'rb')
data = f.read()

# Encrypt data
fernet = Fernet(key)
decrypted = fernet.decrypt(data)
print(decrypted)

# Write the encrypted file
f = open('test.txt.decrypted', 'wb')
f.write(decrypted)
f.close()
import pickle
import cryptography
from cryptography.fernet import Fernet

def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)

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

key = Fernet.generate_key()

username = input("Username: "******"password: "******"test.pkl", "wb")
pickle.dump(e_userpass, outfile)
outfile.close()
infile = open('test.pkl','rb')
z = pickle.load(infile)
Esempio n. 39
0
def password_decrypt(token):
    f = Fernet(bytes(cfgData['key'],encoding))
    phrase = f.decrypt(bytes(token,encoding))
    return phrase.decode(encoding)
def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)
Esempio n. 41
0
def password_key():
     key = Fernet.generate_key()
     return key.decode(encoding)
Esempio n. 42
0
from django.shortcuts import render, redirect
import re
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f=Fernet(key)
# Create your views here.
def view(request):
	if request.method=="GET":
		return render(request, "homepage.html")
		
	if request.method=="POST":
		firstname = request.POST.get('firstname')
		lastname = request.POST.get('lastname')
		middlename = request.POST.get('middlename')
		phonenumber = request.POST.get('phonenumber')
		email = request.POST.get('email')
		place = request.POST.get('place')
		dateofbirth = request.POST.get('dateofbirth')
		listofdata=[firstname, lastname, middlename, phonenumber, email, place, dateofbirth]
		encrypted = []
		basefile = open("base.txt", 'wb')
		proxy = open("proxy.txt", 'a')
		rec=""
		for item in listofdata:
			rec =rec+item+"|"

		proxy.write(rec+"\n")
		#basefile.save()
		for message in listofdata:
			encrypted.append(f.encrypt(message.encode()))
		for item in encrypted:
Esempio n. 43
0
def sendFile(hash, usr_email):
    # server info
    IP = socket.gethostbyname(socket.gethostname())
    PORT = 4455
    ADDR = (IP, PORT)
    FORMAT = "utf-8"
    SIZE = 1024

    # see if there are any contacts
    try:
        FileCredibility.fullStop("contacts.txt")
        with open("contacts.txt", "r") as f:
            contactData = f.readlines()
    except:
        print(
            "No contacts found. Sending a file requires having at least one contact. To add a contact type 'add'\n"
        )
        return

    # create a TCP socket
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # connect to the server
        client.connect(ADDR)
    except:
        print("There are no contacts online. Returning to SecureDrop menu.\n")
        client.close()
        return

    # send my info to the contact
    client.send(usr_email.encode(FORMAT))

    try:
        # get contacts that are online
        onlineContact = client.recv(SIZE).decode(FORMAT)
    except:
        print("\nLost connection to server. Returning to SecureDrop menu.\n")
        client.close()
        return

    # check if online contact is in contact list
    fernet = Fernet(encryption.calculateKey(hash)[0])
    contactFound = False
    marker = False
    for line in contactData:
        if (fernet.decrypt(line[:-1].encode()).decode()
                == onlineContact) and marker:
            contactFound = True
            break
        else:
            marker = True

    # if not in contacts return
    if (contactFound == False):
        print(
            "Someone who is not in your contacts is trying to receive your file. Returning to SecureDrop menu.\n"
        )
        client.close()
        return

    print("The following contacts are online:\n  * " + onlineContact)

    contact = input(
        "\nPlease enter the email of the contact you wish to send a file to>> "
    )

    # check if contact is in contact list
    fernet = Fernet(encryption.calculateKey(hash)[0])
    contactFound = False
    marker = False
    for line in contactData:
        if (fernet.decrypt(line[:-1].encode()).decode() == contact) and marker:
            contactFound = True
            break
        else:
            marker = True

    # if not in contacts return
    if (contactFound == False):
        print(
            "Contact not found in contacts list. Returning to SecureDrop menu.\n"
        )
        client.close()
        return

    # check if contact entered is actually online
    if (onlineContact != contact):
        print("That contact is not online. Returning to SecureDrop menu.\n")
        client.close()
        return

    filename = input("Please enter the name of the file you wish to send>> ")
    if wishToLeave(filename):
        client.close()
        return

    while not os.path.exists(filename):
        print("Cannot find file '" + filename + "'.\n")
        print('You may enter \'quit\' or \'exit\' to leave this prompt.')
        filename = input(
            "Please re-enter the name of the file you wish to send>> ")
        if wishToLeave(filename):
            client.close()
            return

    FileCredibility.updateFiles([filename])

    client.send("ready".encode(FORMAT))
    print("\nWaiting for contact to accept file transfer...")

    try:
        # receive message from server about accepted transfer request
        msg = client.recv(SIZE).decode(FORMAT)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # if message doesnt actually come from the contact you tried sending to
    if contact not in msg:
        print(
            "The response was not from your contact. Returning to SecureDrop menu.\n"
        )
        client.close()
        return

    print(msg)

    # return to main if contact declines the file
    if "declined" in msg:
        print("Returning to SecureDrop menu.\n")
        client.close()
        return

    try:
        # receive the key file name and data
        keyFilename = client.recv(SIZE).decode(FORMAT)
        keyData = client.recv(SIZE).decode(FORMAT)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # save key data
    with open(keyFilename, "w") as keyFile:
        keyFile.write(keyData)
    FileCredibility.updateFiles([keyFilename])

    # print("\nReceiver public key file has been received.")

    # let contact know that key file has been received
    client.send(
        "Receiver public key file has been successfully transferred.".encode(
            FORMAT))

    try:
        # receive signature file name and data
        sigFilename = client.recv(SIZE).decode(FORMAT)
        sigData = client.recv(SIZE)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # save signature data
    with open(sigFilename, "wb") as sigFile:
        sigFile.write(sigData)
    FileCredibility.updateFiles([sigFilename])

    # system auto authenticates

    # let client know that the authentication was successful
    client.send(
        "Receiver signature file has been transferred and authenticated.".
        encode(FORMAT))

    # predict file size:
    predicted_size = predictFileSize(filename)
    client.send(f'size={predicted_size}'.encode(FORMAT))
    large_file = False
    if predicted_size > MAX_RECEIVE_SIZE:
        large_file = True
        print(
            "\nThe file you are encrypting is large. This may take a moment...",
            end='\r')

    # generate sender public key file and encrypt the message filename
    fn = filename.split('.')[0]
    extension = '.' + filename.split('.')[1]
    try:
        sym_key = EncMsg.gen_sender_key_file()
    except cryptography.exceptions.InvalidSignature:
        print(
            '\nr.pub is a forgery! The receiver is not who they say they are!')
        print("Returning to SecureDrop menu.\n")
        client.close()
        return

    if type(sym_key) == int and sym_key == -1:
        print("\ncertificate authority declined to sign public key file")
        print("Returning to SecureDrop menu.\n")
        client.close()
        return
    if EncMsg.gen_send_file(sym_key, fn, extension):
        if large_file:
            print(
                "The file you are encrypting is large. This may take a moment... Success!"
            )
    else:
        print("Failed to encrypt the file. ERROR_26: file too large")

    # send the sender public key filename
    client.send("s.pub".encode(FORMAT))

    # get key data
    FileCredibility.fullStop("s.pub")
    with open("s.pub", "rb") as sender_public_key_file:
        sender_public_key_data = sender_public_key_file.read()

    # send the sender public key data
    client.send(sender_public_key_data)

    try:
        # receive message about successfull public key file transfer
        msg = client.recv(SIZE).decode(FORMAT)
        # print(msg)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # send the sender signature filename
    client.send("s.sig".encode(FORMAT))

    # get signature file data
    FileCredibility.fullStop("s.sig")
    with open("s.sig", "rb") as sender_sig_file:
        sender_sig_data = sender_sig_file.read()

    # send sig file data
    client.send(sender_sig_data)

    try:
        # receive message about successful transfer of sig file
        msg = client.recv(SIZE).decode(FORMAT)
        # print(msg)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # send enc-message filename to server
    client.send(filename.encode(FORMAT))

    # send enc-message file size to server
    filesize = getFileSize(filename.split('.')[0] + '.zok')
    client.send(f'size={filesize}'.encode(FORMAT))

    # get encrypted message data
    fenc = filename.split(".")[0] + ".zok"
    FileCredibility.fullStop(fenc)
    file = open(fenc, "rb")
    data = file.read()
    file.close()

    try:
        decision = client.recv(SIZE).decode(FORMAT)
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return
    if decision == 'n':
        print("\n" + contact +
              " has declined the large file. Returning to SecureDrop menu.\n")
        client.close()
        return

    print(f'\n{filename} sending...', end='\r')
    # send encrypted message data
    client.sendall(data)

    # receive message from server about successful file transfer
    try:
        msg = client.recv(SIZE).decode(FORMAT)
        if ' has been successfully transferred.' in msg:
            print(f'{filename} has been successfully transferred!\n')
        else:
            print("\n" + msg + "\n")
    except:
        print("\n" + contact +
              " has closed the connection. Returning to SecureDrop menu.\n")
        client.close()
        return

    # end connection from server
    client.close()

    return
Esempio n. 44
0
def password_encrypt(phrase):
    key = Fernet(bytes(cfgData['key'],encoding))
    token = key.encrypt(bytes(phrase,encoding))
    return token.decode(encoding)
Esempio n. 45
0
def decrypt_keypair(data, password):
    key = __generate_key(password)
    cipher_suite = Fernet(key)
    return cipher_suite.decrypt(data)
from cryptography.fernet import Fernet
import os

##this key will be constant
key = b'jAvAN8ZXJKfLs6blqY8dk8BpxlrcdmOxzo4K8LZrWyI='
fernet = Fernet(key)


def encrypt_data(x, y):
    encrypted_email = fernet.encrypt(bytes(x, 'utf-8'))
    encrypted_pass = fernet.encrypt(bytes(y, 'utf-8'))

    with open("data.txt", 'wb') as f:
        f.write(encrypted_email)
        f.write(b'\n')
        f.write(encrypted_pass)
    f.close()


def decrypt_data(token):

    d = fernet.decrypt(token)
    print(d.decode())


##this part will be in our main program
if not (os.path.isfile("data.txt")):
    x = str(input("Please enter email : "))
    y = str(input("Please enter password : "))
    encrypt_data(x, y)
else:
Esempio n. 47
0
 def _init_fernet(clazz):
     if not clazz.fernet:
         if not SECRETS_FERNET_KEY:
             raise ValueError(
                 'Missing environment value: SECRETS_FERNET_KEY')
         clazz.fernet = Fernet(SECRETS_FERNET_KEY.encode())
Esempio n. 48
0
from json import load, dumps, loads
from cryptography.fernet import Fernet
from os.path import join
from sys import path

key = b'1GsKHeGRlS3HcvgCtK5mimWaJBxI2EBDGYAACY9A9TY='
cryptographer = Fernet(key)


def get_server_from_email(email):
    return ("smtp." + email.split("@")[1])


def encode_json_conf(conf):
    new_conf = dumps(conf)
    encoded_new_conf = str(cryptographer.encrypt(new_conf.encode()), 'UTF-8')
    return encoded_new_conf
Esempio n. 49
0
    def __init__(self, parent, username, password):
        super().__init__(parent)

        # ========================================================== VARIABLES and Setting up frame
        self.controller = parent
        self.columnconfigure(index=(0, 1), weight=1)
        self.rowconfigure(index=(0, 1, 2), weight=1)

        self.websiteVariable = tk.StringVar()
        self.userIDVariable = tk.StringVar()
        self.sitePasswordVariable = tk.StringVar()

        self.username = username
        self.password = password

        usernameHash = hashlib.md5(username.encode()).hexdigest()
        userHOME = "Users/UsersInfo/" + str(usernameHash)
        key = makeKEY(f'{username}::{password}'.encode())
        fernetobj = Fernet(key)

        # ========================================================== LAYOUT
        # Title of the frame
        self.titleLabel = ttk.Label(self,
                                    text="~ ADD FIELD ~",
                                    font=ALL_TEXT_FONT)
        self.titleLabel.grid(row=0,
                             column=0,
                             columnspan=2,
                             sticky="EW",
                             padx=(25),
                             pady=(10))

        # Website
        self.websiteLabel = ttk.Label(self,
                                      text="Website: ",
                                      font=ALL_TEXT_FONT)
        self.websiteEntry = ttk.Entry(self,
                                      textvariable=self.websiteVariable,
                                      width="35")
        self.websiteLabel.grid(row=1,
                               column=0,
                               sticky="W",
                               padx=(10, 5),
                               pady=(5))
        self.websiteEntry.grid(row=1,
                               column=1,
                               sticky="E",
                               padx=(5, 10),
                               pady=(5))

        # Login ID for that website
        self.userIDLabel = ttk.Label(self,
                                     text="Login ID: ",
                                     font=ALL_TEXT_FONT)
        self.userIDEntry = ttk.Entry(self,
                                     textvariable=self.userIDVariable,
                                     width="35")
        self.userIDLabel.grid(row=2,
                              column=0,
                              sticky="W",
                              padx=(10, 5),
                              pady=(5))
        self.userIDEntry.grid(row=2,
                              column=1,
                              sticky="E",
                              padx=(5, 10),
                              pady=(5))

        # Password for that website LoginID
        self.passwordLabel = ttk.Label(self,
                                       text="Password: "******"35")
        self.passwordLabel.grid(row=3,
                                column=0,
                                sticky="W",
                                padx=(10, 5),
                                pady=(5))
        self.passwordEntry.grid(row=3,
                                column=1,
                                sticky="E",
                                padx=(5, 10),
                                pady=(5))

        # Back to previous frame
        self.backButton = ttk.Button(self, text="Go back", command=self.goBack)
        self.backButton.grid(row=4,
                             column=0,
                             padx=(5),
                             pady=(5),
                             ipadx=(20),
                             ipady=(10))

        # Save all the entry
        self.saveInfoButton = ttk.Button(
            self,
            text="Save",
            command=lambda: self.saveField(userHOME, fernetobj))
        self.saveInfoButton.grid(row=4,
                                 column=1,
                                 padx=(5, 10),
                                 pady=(5),
                                 ipadx=(20),
                                 ipady=(10))
Esempio n. 50
0
def encrypt(data, password):
    key = __generate_key(password)
    cipher_suite = Fernet(key)
    return cipher_suite.encrypt(data)
Esempio n. 51
0
class AccountRegister:
    def __init__(self, secret_key, db_path):
        self._db = JsonFileWrapper(db_path, {'accounts': {}})
        self._data = None
        self._cipher_suite = Fernet(to_bytes(secret_key))

    def create_user(self, username, password):
        self._load()
        if username in self._data['accounts']:
            raise ApiError(code="account_exists")
        self._data['accounts'][username] = {
            'password': self._encrypt(password),
            'apps': []
        }
        self._save()

    def user_exists(self, username):
        try:
            self._assert_user_exists(username)
            return True
        except ApiError:
            return False

    def has_account_for_app(self, username, app):
        self._assert_user_exists(username)
        return username in self._data['accounts'] and app in self._data[
            'accounts'][username]['apps']

    def add_user_app(self, username, app):
        self._assert_user_exists(username)
        apps_list = self._data['accounts'][username]['apps']
        if app not in apps_list:
            apps_list.append(app)
        self._save()

    def remove_user_app(self, username, app):
        self._assert_user_exists(username)
        apps_list = self._data['accounts'][username]['apps']
        if app in apps_list:
            apps_list.remove(app)
        self._save()

    def change_password(self, username, password):
        self._assert_user_exists(username)
        self._data['accounts'][username]['password'] = self._encrypt(password)
        self._save()

    def password_matches(self, username, password):
        self._assert_user_exists(username)
        saved = self._decrypt(self._data['accounts'][username]['password'])
        return saved == to_bytes(password)

    def _assert_user_exists(self, username):
        self._load()
        if username not in self._data['accounts']:
            raise ApiError(code="account_not_found")

    def _encrypt(self, password):
        return self._cipher_suite.encrypt(to_bytes(password))

    def _decrypt(self, password):
        return self._cipher_suite.decrypt(password)

    def _load(self):
        self._data = self._db.load()

    def _save(self):
        self._db.save()
Esempio n. 52
0
from cryptography.fernet import Fernet

key = Fernet.generate_key()

cipher_suit = Fernet(key)

cipher_text = cipher_suit.encrypt(
    b'Text will be encrypted')  #we need byte format

print(cipher_text)

original = cipher_suit.decrypt(cipher_text)

print(original)
Esempio n. 53
0
 def __init__(self, password: str) -> None:
     from cryptography.fernet import Fernet
     hashed = hashlib.sha256(str(password).encode('utf-8'))
     key = base64.urlsafe_b64encode(hashed.digest())
     self.fernet = Fernet(key)
Esempio n. 54
0
    def __init__(self, parent, username, password):
        # mainApp window (side stuff)
        super().__init__(parent)

        # ========================================================== VARIABLES and Setting up frame
        self.controller = parent
        self.columnconfigure(index=(0, 1, 2), weight=1)
        self.controller.geometry("950x450")
        self.controller.resizable(1, 1)

        self.who = tk.StringVar(value=" ")
        self.who.set(value=username)

        self.username = username
        self.password = password

        self.usernameHash = hashlib.md5(self.username.encode()).hexdigest()
        self.userHOME = "Users/UsersInfo/" + str(self.usernameHash)
        self.key = makeKEY(f'{self.username}::{self.password}'.encode())
        self.fernetobj = Fernet(self.key)

        # ============================MENU
        self.menu = tk.Menu(self.controller, tearoff=False)
        self.controller.config(menu=self.menu)
        self.fileMenu = tk.Menu(self.menu, tearoff=False, font=ALL_MENU_FONT)
        self.submenu = tk.Menu(self.fileMenu,
                               tearoff=False,
                               font=ALL_MENU_FONT)
        self.submenu.add_command(label="Chrome", command=lambda: self.soon())
        self.submenu.add_separator()
        self.submenu.add_command(label="Firefox", command=lambda: self.soon())
        self.fileMenu.add_cascade(label='Import passwords',
                                  menu=self.submenu,
                                  underline=0)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Backup for port",
                                  command=self.backupForPort)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=lambda: exit())
        self.menu.add_cascade(label="<-- File -->", menu=self.fileMenu)
        self.infoMenu = tk.Menu(self.menu, tearoff=False, font=ALL_MENU_FONT)
        self.infoMenu.add_command(label="Dev. info", command=self.devinfo)
        self.infoMenu.add_separator()
        self.infoMenu.add_command(
            label="Encryption used",
            command=lambda: webbrowser.open("http://gestyy.com/ethzyj"))
        self.infoMenu.add_separator()
        self.infoMenu.add_command(
            label="Help",
            command=lambda: webbrowser.open("http://gestyy.com/ethztf"))
        self.menu.add_cascade(label="<-- Info  -->", menu=self.infoMenu)

        # ======================================= LAYOUT SETUP

        # Logged-in Label
        self.loggedinLable = ttk.Label(self,
                                       text=f"Logged-in as: {self.who.get()}",
                                       font=ALL_TEXT_FONT,
                                       foreground="#F2FA00",
                                       background="black",
                                       padding=(5))
        self.loggedinLable.grid(row=0, column=0, columnspan=4, sticky="EW")

        # Generate password button
        self.genPassButton = ttk.Button(self,
                                        text="Generate password",
                                        command=self.generatePassword)
        self.genPassButton.grid(row=1,
                                column=0,
                                padx=(10),
                                pady=(5),
                                ipadx=(10),
                                ipady=(5))

        # show Label
        self.showLabel = ttk.Label(self,
                                   text="\t\t",
                                   font=ALL_TEXT_FONT_Password)
        self.showLabel.grid(row=2,
                            column=0,
                            columnspan=3,
                            padx=(10),
                            pady=(5),
                            ipadx=(10),
                            ipady=(5))

        # Save password button
        self.saveButton = ttk.Button(self,
                                     text="Add new",
                                     command=self.savePasswordEntryWindow)
        self.saveButton.grid(row=1,
                             column=1,
                             padx=(10),
                             pady=(5),
                             ipadx=(10),
                             ipady=(5))

        # View passwords button
        self.viewButton = ttk.Button(self,
                                     text="View passwords",
                                     command=self.viewPasswords)
        self.viewButton.grid(row=1,
                             column=2,
                             padx=(10),
                             pady=(5),
                             ipadx=(10),
                             ipady=(5))
Esempio n. 55
0
from cryptography.fernet import Fernet

key = 'TluxwB3fV_GWuLkR1_BzGs1Zk90TYAuhNMZP_0q4WyM='

# Oh no! The code is going over the edge! What are you going to do?
message = b'gAAAAABcNgjBIMM4kniBxy6NP9H78Q7Pmb4pYV1zocfVuvDM44sFHEW0mSi4IGPCD5Jq22xRjJPtEVazmXe-UshwyLDoguTyjvfZkIHjik-fcv7C3ogUoM3zyeNV8wmcgTfPIDAfL61yTBRLvkqCb6ZGuMtdYRXjCUfhWAce7SkhtE5O-w6Uf2xmgaqqUb-Jx16ITZ7rZvmN'

#def main():
f = Fernet(key)
print(f.decrypt(message))


#if __name__ != "__main__":
#    main()
Esempio n. 56
0
 def __init__(self, secret_key, db_path):
     self._db = JsonFileWrapper(db_path, {'accounts': {}})
     self._data = None
     self._cipher_suite = Fernet(to_bytes(secret_key))
Esempio n. 57
0
async def init_cryptography(app):
    cipher_key = Fernet.generate_key()
    salt =  Fernet.generate_key() #base64.urlsafe_b64encode(b'0'*32)
    cipher = Fernet(cipher_key)
    app['cipher'] = cipher
    app['salt'] = salt
def get_decrypted_credentials(cred_filename, ng1key_file, logger):
    """Read in the encrypted user or user-token credentials from a local CredFile.ini file.
    Decrypt the credentials and place all the user credentials attributes into a creds instance.
    :cred_filename: A string that is the name of the cred_filename to read in.
    :ng1key_file: A string that is the name of the ng1's key file to read in.
    :return: If successful, return the creds as a class instance that contains all the params needed to
    connect to the ng1 server via HTTP or HTTPS and authenticate the user. Return False if any error occurrs.
    """
    # Create a creds instance to hold our user credentials.
    creds = Credentials()
    # Retrieve the decrypted credentials that we will use to open a session to the ng1 server.
    try:
        try:  # Open the keyfile containing the key needed to decrypt the password.
            with open(ng1key_file, 'r') as ng1key_in:
                ng1key = ng1key_in.read().encode()  # Read the key as a string.
                fng1 = Fernet(
                    ng1key
                )  # Create an instance of the Fernet class to hold the key info.
        except IOError as e:  # Handle file I/O errors.
            print(
                f"\n[ERROR] Fatal error: Unable to open ng1key file: {ng1key_file}"
            )
            print('Did you run the cred_script_nG1.py first?')
            logger.critical(
                f"[ERROR] Fatal error: Unable to open ng1key file: {ng1key_file}"
            )
            logger.error(f'[ERROR] I/O error({e.errno}):  {e.strerror}.')
        except Exception as e:
            logger.exception(
                f"[ERROR] Fatal error: Unable to open ng1key_file: {ng1key_file}"
            )
            logger.exception(f"Exception error is:\n{e}")
            return False
        with open(cred_filename, 'r') as cred_in:
            lines = cred_in.readlines()
            creds.ng1token = lines[4].partition('=')[2].rstrip("\n")
            #Check to see if we are expected to use an API Token or Username:Password
            # print(f' creds.ng1token is: {creds.ng1token}')
            if len(creds.ng1token
                   ) > 1:  # Yes use a Token rather than a password.
                creds.use_token = True
                creds.ng1token_pl = fng1.decrypt(creds.ng1token.encode(
                )).decode()  # Use the key to decrypt.
                creds.ng1username = lines[2].partition('=')[2].rstrip("\n")
            else:
                creds.use_token = False  # No, do not use a Token, but rather use a password.
                creds.ng1username = lines[2].partition('=')[2].rstrip("\n")
                creds.ng1password = lines[3].partition('=')[2].rstrip("\n")
                creds.ng1password_pl = fng1.decrypt(creds.ng1password.encode(
                )).decode()  # Use the key to decrypt.
            creds.ng1hostname = lines[1].partition('=')[2].rstrip("\n")
            creds.ng1Port = lines[5].partition('=')[2].rstrip("\n")
    except IOError as e:  # Handle file I/O errors.
        logger.error(
            f"[ERROR] Fatal error: Unable to open cred_filename: {cred_filename}"
        )
        logger.error(f'[ERROR] I/O error({e.errno}):  {e.strerror}.')
        return False
    except Exception as e:  # Handle other unexpected errors.
        logger.exception(
            f"[ERROR] Fatal error: Unable to open cred_filename: {cred_filename}"
        )
        logger.exception(f"[ERROR] Exception error is:\n{e}")
        return False

    return creds  # The function was successful.
Esempio n. 59
0
def decrypt(cipher):
    key = b'Nz0Xcsw_up4R6oJA8OqqI34dnRYvPM_pVAgabBNE4xE='
    f = Fernet(key)
    decoded = f.decrypt(cipher)
    return decoded
Esempio n. 60
0
 def _gen_keys(self):
     """Create pair of keys for each wire."""
     for wire in self.wires:
         self.keys[wire] = (Fernet.generate_key(), Fernet.generate_key())