Example #1
0
 def test_bytes_password(self):
     ptext = decrypt(b'password', encrypt(b'password', b'message'))
     assert ptext == b'message', ptext
     ptext = decrypt('password', encrypt(b'password', b'message'))
     assert ptext == b'message', ptext
     ptext = decrypt(b'password', encrypt('password', b'message'))
     assert ptext == b'message', ptext
Example #2
0
 def test_unicode_ciphertext(self):
     u_ciphertext = b'some string'.decode('utf8')
     try:
         decrypt('password', u_ciphertext)
         assert False, 'expected error'
     except DecryptionException as e:
         assert 'bytes' in str(e), e
Example #3
0
 def test_bad_password(self):
     ctext = bytearray(encrypt('password', 'message'))
     try:
         decrypt('badpassword', ctext)
         assert False, 'expected error'
     except DecryptionException as e:
         assert 'Bad password' in str(e), e
Example #4
0
 def get_profile(self, profile, pwd):
     self.c.execute("SELECT * FROM profiles WHERE profile=?", (profile,))
     res = self.c.fetchone()
     uname = simplecrypt.decrypt(pwd, res[1]).decode('utf-8')
     api_key = simplecrypt.decrypt(pwd, res[2]).decode('utf-8')
     token = simplecrypt.decrypt(pwd, res[3]).decode('utf-8')
     return (uname, pwd, api_key, token)
Example #5
0
 def test_modification(self):
     ctext = bytearray(encrypt('password', 'message'))
     ctext[10] = ctext[10] ^ 85
     try:
         decrypt('password', ctext)
         assert False, 'expected error'
     except DecryptionException as e:
         assert 'modified' in str(e), e
Example #6
0
 def test_length(self):
     ctext = encrypt('password', '')
     assert not decrypt('password', ctext)
     try:
         decrypt('password', bytes(bytearray(ctext)[:-1]))
         assert False, 'expected error'
     except DecryptionException as e:
         assert 'Missing' in str(e), e
Example #7
0
 def test_unicode_plaintext(self):
     ptext = decrypt(u'password', encrypt(u'password', u'message'))
     assert ptext.decode('utf8') == 'message', ptext
     ptext = decrypt(u'password', encrypt(u'password', u'message'.encode('utf8')))
     assert ptext == 'message'.encode('utf8'), ptext
     ptext = decrypt(u'password', encrypt(u'password', u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'))
     assert ptext.decode('utf8') == u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹', ptext
     ptext = decrypt(u'password', encrypt(u'password', u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'.encode('utf8')))
     assert ptext == u'¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹'.encode('utf8'), ptext
def load_db(password=''):
  creds = {}
  keychain = Keychain()
  account = getlogin()
  payload = keychain.get_generic_password(KEYCHAIN, account, SERVICE_NAME)
  if payload and 'password' in payload:
    parts = payload['password'].split(JOIN_STRING)
    if(len(parts) > 1):
      creds['password'] = password and decrypt(password, unhexlify(parts[1])) or parts[1]
      creds['username'] = password and decrypt(password, unhexlify(parts[0])) or parts[0]
  return creds
Example #9
0
def get_config():
    secret = os.getenv('SECRET_KEY', 'my_secret_key')
    current_path = os.path.dirname(os.path.realpath(__file__))
    config = ConfigParser()
    config.read(os.path.join(current_path, 'mail.ini'))
    host = base64.b64decode(config.get('smtp', 'host'))
    user = base64.b64decode(config.get('smtp', 'user'))
    password = base64.b64decode(config.get('smtp', 'password'))
    admin = base64.b64decode(config.get('smtp', 'admin'))
    return (decrypt(secret, host),
        decrypt(secret, user),
        decrypt(secret, password),
        decrypt(secret, admin))
Example #10
0
def get_config():
    secret = os.getenv('SECRET_KEY', 'my_secret_key')
    current_path = os.path.dirname(os.path.realpath(__file__))
    config = ConfigParser()
    config.read(os.path.join(current_path, 'taskstore.ini'))
    host = base64.b64decode(config.get('db_connection', 'host'))
    user = base64.b64decode(config.get('db_connection', 'user'))
    password = base64.b64decode(config.get('db_connection', 'password'))
    db = base64.b64decode(config.get('db_connection', 'db'))
    return (decrypt(secret, host),
        decrypt(secret, user),
        decrypt(secret, password),
        decrypt(secret, db))
Example #11
0
def read_config(file_path):
    """
    Tries to read config from 2 types of files.
    If json file is available it will use that one.
    If there is no json file it will use the encrypted file.
    """
    if file_path.endswith(".json"):
        if os.path.isfile(file_path):
            print(green("Load config %s" % (file_path)))
            with open(file_path) as json_config:
                try:
                    return json.load(json_config)
                except Exception, e:
                    abort(red("Cannot read config, is the config correct?. `%s`" % e))
                
        encrypt_file_path = "%s.encrypt" % file_path
        
        if not os.path.isfile(encrypt_file_path):
            abort(red("No config `%s` found." % encrypt_file_path))
        
        with open(encrypt_file_path) as ciphertext:
            password = utils.get_master_password()
            
            try:
                config = decrypt(env.master_password, ciphertext.read()).decode('UTF-8')
            except DecryptionException, e:
                abort(red(e))
            try:
                return json.loads(config)
            except Exception, e:
                abort(red("Cannot read config, is the config correct? `%s`" % e))
Example #12
0
    def decode(cipher):
        "Decodes the validation key."
        # Decryption
        c_text = base64.b64decode(bytes(cipher, 'utf-8'))
        json_str = decrypt(encryption_keys['game_key'], c_text).decode()

        return json.loads(json_str)
Example #13
0
    def do_revoke(self):
        try:
            authid = self.request.get('authid')
            if authid is None or authid == '':
                return "Error: No authid in query"

            if authid.find(':') <= 0:
                return 'Error: Invalid authid in query'

            keyid = authid[:authid.index(':')]
            password = authid[authid.index(':') + 1:]

            if keyid == 'v2':
                return 'Error: The token must be revoked from the service provider. You can de-authorize the application on the storage providers website.'

            entry = dbmodel.AuthToken.get_by_key_name(keyid)
            if entry is None:
                return 'Error: No such user'

            data = base64.b64decode(entry.blob)
            resp = None

            try:
                resp = json.loads(simplecrypt.decrypt(password, data).decode('utf8'))
            except:
                logging.exception('decrypt error')
                return 'Error: Invalid authid password'

            entry.delete()
            return "Token revoked"

        except:
            logging.exception('handler error')
            return 'Error: Server error'
Example #14
0
    def do_revoke(self):
        try:
            authid = self.request.get('authid')
            if authid == None or authid == '':
                return "Error: No authid in query"

            if authid.find(':') <= 0:
                return 'Error: Invalid authid in query'

            keyid = authid[:authid.index(':')]
            password = authid[authid.index(':')+1:]

            entry = dbmodel.AuthToken.get_by_key_name(keyid)
            if entry == None:
                return 'Error: No such user'

            data = base64.b64decode(entry.blob)
            resp = None

            try:
                resp = json.loads(simplecrypt.decrypt(password, data).decode('utf8'))
            except:
                logging.exception('decrypt error')
                return 'Error: Invalid authid password'

            entry.delete()
            return "Token revoked"

        except:
            logging.exception('handler error')
            return 'Error: Server error'
Example #15
0
    def _create_client(self, data):
        """ Creates client from data

            implements some password obfuscation

            :param dict data: dictionary with client params
            :return: Client instance
            :rtype: openerp_proxy.client
        """
        if 'pwd' not in data:
            data = data.copy()
            if self.session.option('store_passwords') and 'password' in data:
                import base64
                encoded_pwd = data.pop('password').encode('utf8')
                crypter, password = base64.b64decode(encoded_pwd).split(b':')
                if crypter == b'simplecrypt':  # pragma: no cover
                    # Legacy support
                    import simplecrypt
                    data['pwd'] = simplecrypt.decrypt(
                        Client.to_url(data), base64.b64decode(password))
                elif crypter == b'plain':
                    # Current crypter
                    data['pwd'] = password.decode('utf-8')
                else:  # pragma: no cover
                    raise Exception("Unknown crypter (%s) used in session"
                                    "" % repr(crypter))
            else:
                # TODO: check if in interactive mode
                data['pwd'] = getpass('Password: ')  # pragma: no cover

        return super(SessionClientManager, self)._create_client(data)
Example #16
0
 def _validate_user_and_passwd():
     u = Config.get_config().user
     p = Config.get_config().passwd
     if user != u:
         raise InvalidUserError(user)
     elif passwd != decrypt('devops', p):
         raise InvalidPasswdError(passwd)
Example #17
0
def decrypt_disclaimers(input, output, fieldsep, rowsep):
    if PASSWORD is None:
        print('You need to set the SIMPLECRYPT_PASSWORD')
        return

    if output is None:
        # timestamp the filename with the datetime it was downloaded
        timestamp = time.strftime(
            '%Y%m%d%H%M', time.gmtime(os.path.getctime(input.name))
        )
        output = 'disclaimers_backup_{}.csv'.format(timestamp)

    encrypted_text = input.read()
    decrypted_text = decrypt(PASSWORD, encrypted_text)
    decrypted_text = str(decrypted_text).lstrip("b'").rstrip("'")
    decrypted_data = decrypted_text.split(fieldsep)

    with open(output, 'wt') as out:
        wr = csv.writer(out)

        for entry in decrypted_data:
            data = entry.split(rowsep)
            wr.writerow([smart_str(datum) for datum in data])

    os.unlink(input.name)

    print(
        '{} records decrypted and written to {}'.format(
            len(decrypted_data) - 1, output
        )
    )
Example #18
0
def item(id):
    myitem = PasswordRecords.query.get_or_404(id)
    site = myitem.displayname
    username = myitem.username
    password = decrypt(globalkey, myitem.password)
    detail = myitem.detail
    return render_template('item.html',name=site,name2="http://" + site,username=username,password=password,detail=detail)
Example #19
0
def get_credentials():
    '''
    Get a SafeConfigParser instance with FACT credentials
    On the first call, you will be prompted for the FACT password

    The folling credentials are stored:
    - telegram
        - token

    - database
        - user
        - password
        - host
        - database

    - twilio
        - sid
        - auth_token
        - number

    use get_credentials().get(group, element) to retrieve elements
    '''
    with resource_stream('fact_credentials', 'credentials.encrypted') as f:
        print('Please enter the current, universal FACT password')
        passwd = getpass()
        decrypted = decrypt(passwd, f.read()).decode('utf-8')

    config = SafeConfigParser()
    config.readfp(StringIO(decrypted))

    return config
Example #20
0
 def test_unicode_plaintext(self):
     def u(string):
         u_type = type(b''.decode('utf8'))
         if not isinstance(string, u_type):
             return string.decode('utf8')
         return string
     u_message = u('message')
     u_high_order = u('¥£€$¢₡₢₣₤₥₦₧₨₩₪₫₭₮₯₹')
     ptext = decrypt('password', encrypt('password', u_message))
     assert ptext.decode('utf8') == 'message', ptext
     ptext = decrypt('password', encrypt('password', u_message.encode('utf8')))
     assert ptext == 'message'.encode('utf8'), ptext
     ptext = decrypt('password', encrypt('password', u_high_order))
     assert ptext.decode('utf8') == u_high_order, ptext
     ptext = decrypt('password', encrypt('password', u_high_order.encode('utf8')))
     assert ptext == u_high_order.encode('utf8'), ptext
Example #21
0
def library_import(args, l, config):
    import json
    from ambry.library.config import LibraryConfigSyncProxy
    from ambry.orm import Account
    from simplecrypt import encrypt, decrypt, DecryptionException

    try:
        jsn = decrypt(args.password, args.config_file.read().decode('base64'))
    except DecryptionException as e:
        fatal(e)
    finally:
        args.config_file.close()

    args.config_file.close()

    d = json.loads(jsn)

    for k, v in d['accounts'].items():
        if v.get('major_type') != 'user' and 'encrypted_secret' in v:
            v['secret'] = Account.sym_decrypt(args.password, v['encrypted_secret'])

    if args.list:
        prt_no_format(json.dumps(d, indent=4))
    else:
        lcsp = LibraryConfigSyncProxy(l)

        lcsp.sync_remotes(d['remotes'], cb=l.logger.info)
        lcsp.sync_accounts(d['accounts'], cb=l.logger.info)

        for vid, v in d['bundles'].items():
            l.logger.info("Check in remote bundle {}, {}".format(vid, v['vname']))
            l.checkin_remote_bundle(vid)
Example #22
0
def read_encrypted(password, filename, string=True):
    with open(filename, 'rb') as input_file:
        ciphertext = input_file.read()
        plaintext = decrypt(password, ciphertext)
        if string:
            return plaintext.decode('utf8')
        else:
            return plaintext
Example #23
0
def size(n):
    plaintext = 'a' * n
    key = 'python'
    ciphertext = encrypt(key, plaintext)
    print n, len(ciphertext)
    plaintext = decrypt(key, ciphertext)
    #print ciphertext
    print '[%s]' % plaintext
Example #24
0
def decrypt_f(args):
    cyper = open(args,'rb').read()
    rey = hashlib.sha256(password).digest()
    for i in range (10000):
        rey = hashlib.sha256(rey).hexdigest()
    l = simplecrypt.decrypt(rey,cyper)
    x = open(args,'wb')
    x.write(l)
Example #25
0
def load_weights(weightfilename, password):
	weights = []
	if os.path.isfile(weightfilename):
		with open(weightfilename, 'r') as weightfile:
			data = base64.b64decode(weightfile.read())
			weight = decrypt(password, data).decode("utf-8")
			weights = json.loads(weight)
	return weights
def returnAllUsers(key):
    # list of dicts to hold info
    returnData = []
    
    # return string contains log info about success/failure/warnings
    returnLog = ""    
    
    # verify db exists or try to create it)
    if not verifyDB():
        returnLog += "Error: could not open or create db"+"\n\t"+dbName+"\n"
        return (returnData, returnLog)
    
    # get every line from file, decypt
    db = open(dbName, 'rb')
    if (not db):
        returnLog += "Error: could not open db in read mode"+"\n\t"+dbName+"\n"
        db.close()
        return (returnData, returnLog)
        
    cryptData = db.read()
    db.close()
    
    if (cryptData == ""):
        returnLog += "Warn: empty db\n"
        db.close()
        return (returnData, returnLog)
    
    
    Data = decrypt(key, cryptData)
    
    # split at new-lines
    Data = Data.split('\n')
    
    if (not len(Data) % 3 == 1):
        returnLog += "Error: len(Data) should always == 1 mod 3. db len is multiple of 3 plus 1\n"
        return (returnData, returnLog)
    
    i=0
    while (i < len(Data)-1):
        userDict={}
        for j in range (3):
            # case userID
            if (j==0):
                userDict['userID']=Data[i]
            # case userPW
            if (j==1):
                userDict['userPW']=Data[i]
            # case userEmail
            if (j==2):
                userDict['userEmail']=Data[i]
            i+=1

        returnData.append(userDict)
    
    
    returnLog += "Success"
    
    return (returnData, returnLog)
Example #27
0
 def fromEncryptedFile(cls, password, file_dir=None, file_name=None, netcode=None): 
     if file_dir is None: 
         file_dir = config.DATA_DIR
     if file_name is None: 
         file_name = config.DEFAULT_WALLET_FILE
     with open(os.path.join(file_dir, file_name), 'rb') as rfile: 
         data = rfile.read() #read with os?
     wallet = json.loads(decrypt(password, data).decode('utf-8'))
     return cls.from_hwif((wallet.get('privkey') or wallet.get('pubkey')), keypath=wallet.get('keypath'), netcode=netcode)
Example #28
0
def load_secure_data():
    """
        Load data stored by save_secure_data.
    """
    encoded_data = keyring.get_password("FreshPass Encrypted Log", "log")
    if encoded_data:
        encrypted_data = base64.b64decode(encoded_data)
        decrypted_data = simplecrypt.decrypt(get_hardware_id(), encrypted_data)
        return decrypted_data
Example #29
0
    def decode_data(self, enc):
        try:
            data = decrypt(settings.SECRET_KEY, base64.decodestring(enc))
            return self.deserialize_data(data)
        except DecryptionException:
            logger.warn(u'Payer decryption error')

        except get_user_model().DoesNotExist:
            logger.warn(u'Payer does not exist')
Example #30
0
def add(username, oath):
    global _accounts
    current_usernames = {}

    with open('.config', 'rb') as tmp_file:
        tmp_data = tmp_file.readline()

        if len(tmp_data) > 0:
            data = str(decrypt(os.environ['cryptkey'], tmp_data).decode('utf-8')).split('~')
            print('data: ' + repr(data))
            for tmp_line in data:
                tmp_str = str(decrypt(os.environ['cryptkey'], tmp_line).decode('utf-8'))
                tmp_username, tmp_oath = tmp_str.split(':', 1)
                current_usernames[tmp_username] = tmp_oath

    current_usernames[username] = oath
    _accounts = current_usernames
    save_accounts()
Example #31
0
            )
        _hashed_password = hashlib.sha224(bytes(_password,
                                                encoding='utf-8')).hexdigest()

        if _hashed_password != _settings.password:
            raise Exception("wrong password")

        threading.Thread(
            target=animations.animate).start()  # launch loading animation
    else:
        _base.metadata.create_all(_engine)
        __user_info = askUserInfos()

        threading.Thread(
            target=animations.animate).start()  # loading animation start

        _settings = Settings(firstname=encrypt(_password, __user_info[0]),
                             lastname=encrypt(_password, __user_info[1]),
                             password=__user_info[2])
        _session.add(_settings)
        _session.commit()

    __firstname = decrypt(_password, _settings.firstname).decode("utf-8")
    animations.done = True
    sys.stdout.write("\rWelcome, " + __firstname + "\n")

    __shell = shell.shell(_session, _password)
    __shell.loop()
    _session.close()
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Example #32
0
 def _decrypt(self, password, contents):
     try:
         return decrypt(password, contents)
     except:
         raise InvalidEncryptionPassword
from simplecrypt import decrypt

passwords = []
with open("passwords.txt", "r") as inp:
    passwords = inp.readlines()

with open("encrypted.bin", "rb") as inp:
    encrypted = inp.read()

print(passwords, encrypted)

for password in passwords:
    print(password[:-1])
    try:
        print(decrypt(password[:-1], encrypted))
    except BaseException:
        print("Nope")
Example #34
0
def appDecrypt(word):
    file = open('.secret', 'r')
    secret_key = file.readline()
    msg = decrypt(secret_key, word).decode('utf-8')
    file.close()
    return (msg)
Example #35
0
def run_tests(args=None):
    """Run the scripts to start end-to-end tests."""

    parsed_args = _PARSER.parse_args(args=args)
    oppia_instance_is_already_running = is_oppia_server_already_running()

    if oppia_instance_is_already_running:
        sys.exit(1)
    setup_and_install_dependencies(parsed_args.skip_install)

    common.start_redis_server()
    atexit.register(cleanup)

    dev_mode = not parsed_args.prod_env

    if parsed_args.skip_build:
        build.modify_constants(prod_env=parsed_args.prod_env)
    else:
        build_js_files(dev_mode,
                       deparallelize_terser=parsed_args.deparallelize_terser,
                       source_maps=parsed_args.source_maps)
    version = parsed_args.chrome_driver_version or get_chrome_driver_version()
    python_utils.PRINT('\n\nCHROMEDRIVER VERSION: %s\n\n' % version)
    start_webdriver_manager(version)

    portserver_process = start_portserver()
    atexit.register(cleanup_portserver, portserver_process)
    start_google_app_engine_server(dev_mode, parsed_args.server_log_level)

    common.wait_for_port_to_be_open(WEB_DRIVER_PORT)
    common.wait_for_port_to_be_open(GOOGLE_APP_ENGINE_PORT)
    ensure_screenshots_dir_is_removed()
    commands = [common.NODE_BIN_PATH]
    if parsed_args.debug_mode:
        commands.append('--inspect-brk')
    # This flag ensures tests fail if waitFor calls time out.
    commands.append('--unhandled-rejections=strict')
    commands.append(PROTRACTOR_BIN_PATH)
    commands.extend(
        get_e2e_test_parameters(parsed_args.sharding_instances,
                                parsed_args.suite, dev_mode))

    p = subprocess.Popen(commands, stdout=subprocess.PIPE)
    output_lines = []
    failure_seen = False
    while True:
        nextline = p.stdout.readline()
        if len(nextline) == 0 and p.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()
        new_output_line = nextline.strip()
        if new_output_line.decode('utf-8') == FAILURE_OUTPUT_STRING:
            failure_seen = True
        output_lines.append(new_output_line)

    flaky_tests_list = []
    google_auth_decode_password = os.getenv('GOOGLE_AUTH_DECODE_PASSWORD')
    if google_auth_decode_password is not None:
        with python_utils.open_file('auth.json.enc', 'rb',
                                    encoding=None) as enc_file:
            with python_utils.open_file('auth.json', 'w') as dec_file:
                ciphertext = enc_file.read()
                plaintext = simplecrypt.decrypt(google_auth_decode_password,
                                                ciphertext).decode('utf-8')
                dec_file.write(plaintext)

        sheets_scopes = ['https://www.googleapis.com/auth/spreadsheets']
        creds = service_account.Credentials.from_service_account_file(
            'auth.json', scopes=sheets_scopes)
        sheet = googleapiclient.discovery.build(
            'sheets', 'v4', credentials=creds).spreadsheets()
        flaky_tests_list = get_flaky_tests_data_from_sheets(sheet)

    suite_name = parsed_args.suite.lower()
    if len(flaky_tests_list) > 0 and p.returncode != 0:
        for i, line in enumerate(output_lines):
            if line.decode('utf-8') == FAILURE_OUTPUT_STRING:
                test_name = output_lines[i + 3][3:].strip().lower()

                # Remove coloring characters.
                ansi_escape = re.compile(
                    r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
                failure_log = ansi_escape.sub('', output_lines[i + 4])
                failure_log = failure_log.strip().lower()
                for index, row in enumerate(flaky_tests_list):
                    flaky_suite_name = row[0].strip().lower()
                    flaky_test_message = row[1].strip().lower()
                    flaky_error_message = row[2].strip().lower()
                    if (suite_name == flaky_suite_name
                            or flaky_suite_name == '[general]'):
                        if (test_name == flaky_test_message
                                or flaky_test_message == 'many'):
                            if flaky_error_message in failure_log:
                                update_flaky_tests_count(sheet, index, row[3])
                                try:
                                    cleanup_portserver(portserver_process)
                                    cleanup()
                                except Exception:  # pragma: no cover
                                    # This is marked as no cover because the
                                    # exception happens due to some processes
                                    # running on the local system, which might
                                    # interfere with the cleanup stuff. This is
                                    # added as a failsafe to make sure that
                                    # even when it throws an exception, the
                                    # test is retried.
                                    pass  # pragma: no cover
                                return 'flake'
    if failure_seen:
        cleanup_portserver(portserver_process)
        cleanup()
        return 'fail'
    return 'pass'
def DecryptFromFile(key):
    with open(history_file_name, 'rb') as f:
        cipher_text = f.read()
    pad, plain_text = decrypt(key, cipher_text).split("$$$$")
    return plain_text
Example #37
0
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                                       MAIN SCRIPT
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
creds_data = input("Enter name of encrypted credentials file (default: encrypted_cred):") or "encrypted_cred"
devices_data = input("Enter name of the devices info file (default: devices_info.csv):") or "devices_info.csv"
password = getpass()
no_of_threads = Pool(int(input("Enter no. of threads(default 3):") or "3"))

start_time = time()
#below json.loads() command converts encrypted_cred_read.read() bytes data to list which is then decrypted using password as salt
devices_raw_data = csv.reader(open(devices_data,'r'))
devices_list = [devices_info for devices_info in devices_raw_data]
pprint(devices_list)
#below json.loads() command converts encrypted_cred_read.read() bytes data to list which is then decrypted using password as salt
creds_list = json.loads(decrypt(password,open(creds_data,'rb').read()))
#thread_list = []

new_device_list = []
devices_info = devices_detail(devices_list,creds_list)
for [k,v] in devices_info.items():
    new_device_list.append((v['device_type'],v['ip'],v['username'],v['password']))
no_of_threads.map(configuring_device,new_device_list)
print('Elapsed time:'+str(time()-start_time)+'sec')
#####################################################################################################################3
=======

driver =get_network_driver('ios')
ios = driver('10.10.2.3','omkar','cisco')

ios.open()
Example #38
0
 def test_python3(self):
     ptext = decrypt(b'password', encrypt(b'password', b'message'))
     assert ptext == b'message', ptext
     ptext = decrypt('password', encrypt('password',
                                         'message')).decode('utf8')
     assert ptext == 'message', ptext
Example #39
0
def decode(password, ciphertext):
    return decrypt(password, ciphertext).decode('utf8')
Example #40
0
 def test_known_3(self):
     # this was generated with python 3.7 and v5.0.0
     ctext = b'sc\x00\x02*$Z4\x96\xa6x\xfa?\x0c\xbbb\x94`\xbfe\xdeD&\r\xc2\xca\x14[(X\xa2\xdf\x8c\xd5<VRr\xb9\x80\x88(sB\xce\x82]\xdd\x92\x90~m#"\xf0\xc7\n\xc1\xf7(\xf3\'\xe1V\xb0GH4\x94TPqL*E'
     ptext = decrypt('password', ctext)
     assert ptext == b'message', ptext
Example #41
0
#!/usr/bin/env python3
import simplecrypt

with open('encrypted.bin', 'rb') as inp:
    encrypted = inp.read()

with open('passwords.txt', 'r') as inp:
    passwords = inp.read().split()

output = None

for password in passwords:
    try:
        output = simplecrypt.decrypt(password, encrypted)
    except simplecrypt.DecryptionException:
        print("Wrong password", password, "skipping...")
    if output is not None:
        print("Decrypted! Right password is", password)
        break

print(output)
Example #42
0
    'encrypted_cert.enc')
dec_cert_path = join(
    os.path.dirname(
        os.path.realpath(__file__)),
    'decrypted_cert.json')

"""
Read encrypted file
"""
with open(enc_cert_path, mode="rb") as file:
    encrypted_cert = file.read()

"""
Decrypt and write decrypted file
"""
decrypted_cert = decrypt(Env.FIREBASE_PRIVATE_KEY(), encrypted_cert)
with open(dec_cert_path, mode="wb") as file:
    file.write(decrypted_cert)

"""
Ensure decrypted JSON certificate is deleted on exit
"""


def delete_decrypt_on_exit():
    os.remove(dec_cert_path)


atexit.register(delete_decrypt_on_exit)

"""
Example #43
0
# Текст задания: https://stepik.org/lesson/24466/step/9?unit=6773

# Алиса владеет интересной информацией, которую хочет заполучить Боб.
# Алиса умна, поэтому она хранит свою информацию в зашифрованном файле.
# У Алисы плохая память, поэтому она хранит все свои пароли в открытом виде в текстовом файле.
# Бобу удалось завладеть зашифрованным файлом с интересной информацией и файлом с паролями, но он не смог понять какой
# из паролей ему нужен. Помогите ему решить эту проблему.
# Алиса зашифровала свою информацию с помощью библиотеки simple-crypt.
# Она представила информацию в виде строки, и затем записала в бинарный файл результат работы метода
# simplecrypt.encrypt.
# Вам необходимо установить библиотеку simple-crypt, и с помощью метода simplecrypt.decrypt узнать, какой из паролей
# служит ключом для расшифровки файла с интересной информацией.
# Ответом для данной задачи служит расшифрованная интересная информация Алисы.

import simplecrypt

with open('passwords.txt', 'r') as f:
    passwords = [i.strip() for i in f.readlines()]

with open('encrypted.bin', 'rb') as f:
    line = f.read()
    for passw in passwords:
        try:
            print(simplecrypt.decrypt(passw, line).decode('utf8'))
            break
        except simplecrypt.DecryptionException:
            pass
Example #44
0
 def test_known_2(self):
     # this was generated with python 3.3 and v4.0.0
     ctext = b'sc\x00\x02g)x\x7f\xbf\xc8\xe5\xff\roR\x9b\x0e#X\xb8eW=\x93,\x85I{\x9a{\x9d\x07\xf4TUj\xfek/\xed\xff\xde\xaa|\\`\x1a\xc1\xf9\x81\x12\x0blE\r$\x827\x1b\xe9Gz\xf2\x87T\xd1gW\x9ez\xd9Y{\x80\x1a'
     ptext = decrypt('password', ctext)
     assert ptext == b'message', ptext
import time
import getpass
import os
from simplecrypt import decrypt
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream

## Import Passwords - Importing Passwords from a file stored elsewhere on my computer
sys.path.append('C:/Users/GTayl/Desktop/Finance Modeling')
from passwords_encrypted import twitter_streaming as pwd
master_password = getpass.getpass()

# Email Integration
from Email_Integration import send_mail
from passwords_encrypted import Gmail as email_act
email_account = email_act['email']
email_password = decrypt(master_password,
                         email_act['password']).decode('utf-8')

## Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = decrypt(master_password, pwd['access_token']).decode('utf-8')
ACCESS_SECRET = decrypt(master_password, pwd['access_secret']).decode('utf-8')
CONSUMER_KEY = decrypt(master_password, pwd['consumer_key']).decode('utf-8')
CONSUMER_SECRET = decrypt(master_password,
                          pwd['consumer_secret']).decode('utf-8')

## Authorizing a session with Twitter
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_stream = TwitterStream(auth=oauth)
iterator = twitter_stream.statuses.sample()

## Creating a File
file_date = datetime.date.today()
Example #46
0
 def test_python27(self):
     ptext = decrypt('password', encrypt('password', 'message'))
     assert ptext == 'message', ptext
     # this needs to be commented out when testing with 3.0 (syntax error)
     ptext = decrypt(u'password', encrypt(u'password', u'message'))
     assert ptext == u'message', ptext
Example #47
0
def desencripta(key, encoded_cipher):
    cipher = b64decode(encoded_cipher)
    return decrypt(key, cipher)
Example #48
0
Ответом для данной задачи служит расшифрованная интересная информация Алисы.

Примечание:
Для того, чтобы считать все данные из бинарного файла, можно использовать, например, следующий код:

with open("encrypted.bin", "rb") as inp:
    encrypted = inp.read()

форк PyCrypto, который ставится на любую машину без проблем: https://github.com/Legrandin/pycryptodome

Для установки simplecrypt:
1. pip install pycryptodome
2. pip install simple-crypt
'''

from simplecrypt import encrypt, decrypt, DecryptionException

f = open("passwords.txt", "r")

with open("encrypted.bin", "rb") as inp:
    encrypted = inp.read()

for line in f:
    passwd = line.rstrip()
    try:
        plaintext = decrypt(passwd, encrypted)
    except DecryptionException:
        continue
    print(plaintext)

f.close()
Example #49
0
import simplecrypt

with open("encrypted.bin", "rb") as al:
    encrypted = al.read()

with open("keys.txt", "r") as keys:
    for key in keys:
        print(key.strip())
        try:
            print(simplecrypt.decrypt(key.strip(), encrypted))
        except:
            pass
Example #50
0
import simplecrypt
from urllib import request

encrypted = request.urlopen('https://stepic.org/media/attachments/lesson/24466/encrypted.bin').read()
passwords = request.urlopen('https://stepic.org/media/attachments/lesson/24466/passwords.txt').read().strip().split()

for password in passwords:
    try:
        print(simplecrypt.decrypt(password, encrypted))
    except simplecrypt.DecryptionException:
        pass
Example #51
0
import simplecrypt

encrypted = open('encrypted.bin', 'rb').read()
passwords = open('passwords.txt').readlines()

for p in passwords:
    p = p.strip()
    try:
        s = simplecrypt.decrypt(p, encrypted)
    except simplecrypt.DecryptionException:
        continue

    print(s.decode('utf-8'))
Example #52
0
def removeUser(key, userID):
    # return string contains log info about success/failure/warnings removing user
    returnLog = ""

        
    # verify db exists or try to create it
    if not verifyDB():
        returnLog += "Error: could not open or create db"+"\n\t"+dbName+"\n"
        return returnLog
    
    # get every line from file, decypt
    db = open(dbName, 'rb')
    if (not db):
        returnLog += "Error: could not open db in read mode"+"\n\t"+dbName+"\n"
        db.close()
        return returnLog
        
    cryptData = db.read()
    if (not cryptData == ""):
        Data = decrypt(key, cryptData)
        
        # check if user exists
        if (userID in Data):
            # remove id, pw, email upto and including '\n'
            start = Data.index(userID)
            end = Data.find("\n", start)+1 # id
            end = Data.find("\n", end)+1   # pw
            end = Data.find("\n", end)+1   # email
            Data = Data[:start]+Data[end:]
            
            
            
        # if not no user to remove    
        else:
            returnLog += "Warn: userID not in db\n--no user to remove\n"
            db.close()
            return returnLog            
    
    else: #no data in db
        returnLog += "Warn: no existing data in db\n"
        db.close()
        return returnLog



    # encyrpt back to database
    cyrptData = encrypt(key, Data)


    # check the db, clear it, & write back
    db = open(dbName, 'wb')
    if (not db):
        returnLog += "Error: could not open db in write mode"+"\n\t"+dbName+"\n"
        db.close()
        return returnLog
    
    db.write(cyrptData)
    db.close()
    
    returnLog += "Success\n"

    return returnLog
Example #53
0
import simplecrypt
res = ''
with open("C:\\Users\\User\\Downloads\\encrypted.bin", "rb") as inp:
    encrypted = inp.read()

with open("C:\\Users\\User\\Downloads\\passwords.txt") as pas:
    x = pas.read().splitlines()
    for i in x:
        try:
            print(simplecrypt.decrypt(i, encrypted))
        except simplecrypt.DecryptionException:
            print(i)
Example #54
0
 def _decryptFile(cls, password, data):
     import simplecrypt
     return simplecrypt.decrypt(password, data).decode('utf-8')
Example #55
0
 def test_bytes_plaintext(self):
     ptext = decrypt('password', encrypt('password', b'message'))
     assert ptext == b'message', ptext
Example #56
0
from binascii import hexlify
from getpass import getpass
from sys import stdin

from simplecrypt import encrypt, decrypt

# read the password from the user (without displaying it)
password = getpass("password: "******"message: ")
message = stdin.readline()

# encrypt the plaintext.  we explicitly convert to bytes first (optional)
ciphertext = encrypt(password, message.encode('utf8'))

# the ciphertext plaintext is bytes, so we display it as a hex string
print("ciphertext: %s" % hexlify(ciphertext))

# now decrypt the plaintext (using the same salt and password)
plaintext = decrypt(password, ciphertext)

# the decrypted plaintext is bytes, but we can convert it back to a string
print("plaintext: %s" % plaintext)
print("plaintext as string: %s" % plaintext.decode('utf8'))
Example #57
0
 def test_known_0(self):
     # this was generated with python 3.3 and v1.0.0
     ctext = b'sc\x00\x00;\xdf|*^\xdbK\xca\xfe?%\x95\xc0\x1a\xe3\r`\x84F\xec\xc9\x86\x00\x90\x7f\xe7\xd1\xbc\xa5\xb2\x9c\x02\xc0\xb9\xb4\x89\xc5\x95\xa9\xc0\n\xac\x01\xe7\xfb\x07i"B\xb5\xedJ\xe7\xed\x95'
     ptext = decrypt('password', ctext)
     assert ptext == b'message', ptext
Example #58
0
 def test_known_1(self):
     # this was generated with python 3.3 and v3.0.0
     ctext = b'sc\x00\x01jX\xdc\xbdY\ra\xbf\x8e\x17\xec\xfd\xebQ\xa0\xe3\xce\x9b\xe4\xa7\xbd\x9d\x9dJ\x16\x98\x11_IU\x82L\x96\xe7\x96Q\x01\x94\xe6\xe4\xeb8\xc9\xf2\xdd<t(\xe0\xf4\x96jy\xc9\xf5\xc5\xb6\xa0\xc3@R\xd7\x7f\xed\xc0=\x18\xfcX\xf0\xf4'
     ptext = decrypt('password', ctext)
     assert ptext == b'message', ptext
Example #59
0
    def dataproxy_search(self, request_data, resource):
        """Performs actual query on remote database via SqlAlchemy
        Args:
            request_data: Dictionary of parsed request parameters.
            resource: Resource object that is being searched.
        Returns:
            Datastore search compatible JSON object with search results.
        Raises:
            Exception: if ckan.dataproxy.secret configuration not set.
        """
        secret = pylons.config.get('ckan.dataproxy.secret', False)
        if not secret:
            raise Exception(
                'ckan.dataproxy.secret must be defined to encrypt/decrypt passwords'
            )

        table_attr = resource.extras['table']
        schema_name = None

        schema_and_table = table_attr.split('.')  #=> ['schema', 'table']
        table_name = schema_and_table.pop()  #=> 'table'
        if (len(schema_and_table) > 0): schema_name = schema_and_table.pop()

        password = resource.extras['db_password']
        password = decrypt(secret, unhexlify(password))

        connstr = resource.url
        connstr = connstr.replace('_password_', password)

        engine = create_engine(connstr)
        meta = MetaData(bind=engine)
        table = Table(table_name, meta, autoload=True, schema=schema_name)

        conn = engine.connect()
        select_query = select([table])

        filters = request_data.get('filters', None)
        q = request_data.get('q', None)  # Not yet implemented
        plain = request_data.get('plain', None)  # Not yet implemented
        language = request_data.get('language', None)  # Not yet implemented
        limit = request_data.get('limit', None)
        offset = request_data.get('offset', None)
        fields = request_data.get('fields', None)  # Not yet implemented
        sort = request_data.get('sort', None)

        if fields is not None:
            table_fields = self._get_fields(table, fields=fields.split(','))
        else:
            table_fields = self._get_fields(table)

        if limit is not None:
            select_query = select_query.limit(limit)
        if offset is not None:
            select_query = select_query.offset(offset)
        if sort is not None:
            #check if column exists
            sort_column, sort_order = sort.split(' ')
            if sort_order == 'asc':
                select_query = select_query.order_by(
                    getattr(table.c, sort_column))
            if sort_order == 'desc':
                select_query = select_query.order_by(
                    desc(getattr(table.c, sort_column)))
            #else unknown order
        if filters is not None:
            filters = json.loads(
                str(filters))  # Convert unicode object to JSON
            for field, value in filters.iteritems():
                #check if fields exists
                select_query = select_query.where(
                    getattr(table.c, field) == value)
        # if fields is not None:
        #     select_query = select_query.with_only_columns( fields.split(',') )
        #     table_fields = self._get_fields(select_query.columns.items)

        start = time.time()
        result = conn.execute(select_query)
        log.info(' Query took %.3f seconds to run' % (time.time() - start))

        records = list()
        for row in result:
            d = OrderedDict()
            for field in table_fields:
                d[field['id']] = row[field['id']]
            records.append(d)

        # Fetch count of all rows for paging to work
        sql = select([func.count('*')]).select_from(table)
        result_count = conn.execute(sql)
        count = 0
        for row in result_count:
            count = row[0]
        retval = OrderedDict()
        retval['help'] = self._help_message()
        retval['success'] = True
        retval['result'] = OrderedDict()
        retval['result']['resource_id'] = request_data['resource_id']
        retval['result']['fields'] = table_fields
        retval['result']['records'] = records
        if filters is not None:
            retval['result']['filters'] = filters
        if limit is not None:
            retval['result']['limit'] = limit
        if offset is not None:
            retval['result']['offset'] = offset
        if sort is not None:
            retval['result']['sort'] = sort
        if q is not None:
            retval['result']['q'] = ''
        if count:
            retval['result']['total'] = count
        retval['result']['_links'] = self._insert_links(limit, offset)

        return json.dumps(retval, default=alchemyencoder)
import simplecrypt

with open("encrypted.bin", "rb") as inp:
    encrypted = inp.read()
    with open("passwords.txt", "r") as p:
        passwords = p.readlines()
        for i in passwords:
            i = i.strip()
            try:
                print(simplecrypt.decrypt(i,encrypted).decode('utf-8'))
                break
            except simplecrypt.DecryptionException:
                pass