def config_taskstore(): if len(sys.argv) < 5: print('''Usage for configure taskstore.ini for database connection: python taskstore.py host user password database python taskstore.py host user password database encrypt_key Example: python taskstore.py 172.16.16.16 root xFGt3Swq test (Encrypt key will be taken from environment) python taskstore.py 172.16.16.16 root xFGt3Swq test MyEncrYptKey (Encrypt key taken from param) ''') sys.exit(1) host = sys.argv[1] user = sys.argv[2] password = sys.argv[3] db = sys.argv[4] if len(sys.argv) == 5: secret = os.getenv('SECRET_KEY', 'my_secret_key') #get secret from env else: secret = sys.argv[5] #get secret by param current_path = os.path.dirname(os.path.realpath(__file__)) newfile = os.path.join(current_path, 'taskstore.ini') with open(newfile, 'w') as f: f.write('[db_connection]\n') f.write('host=' + base64.b64encode(encrypt(secret, host)) + '\n') f.write('user='******'\n') f.write('password='******'\n') f.write('db=' + base64.b64encode(encrypt(secret, db))) print('done')
def config_taskstore(): if len(sys.argv) < 5: print('''Usage for configure taskstore.ini for database connection: python taskstore.py host user password database python taskstore.py host user password database encrypt_key Example: python taskstore.py 172.16.16.16 root xFGt3Swq test (Encrypt key will be taken from environment) python taskstore.py 172.16.16.16 root xFGt3Swq test MyEncrYptKey (Encrypt key taken from param) ''') sys.exit(1) host = sys.argv[1] user = sys.argv[2] password = sys.argv[3] db = sys.argv[4] if len(sys.argv) == 5: secret = os.getenv('SECRET_KEY', 'my_secret_key') #get secret from env else: secret = sys.argv[5] #get secret by param current_path = os.path.dirname(os.path.realpath(__file__)) newfile = os.path.join(current_path, 'taskstore.ini') with open(newfile, 'w') as f: f.write('[db_connection]\n') f.write('host='+base64.b64encode(encrypt(secret, host))+'\n') f.write('user='******'\n') f.write('password='******'\n') f.write('db='+base64.b64encode(encrypt(secret, db))) print('done')
def save_db(creds, password=''): creds['password'] = password and hexlify(encrypt(password, creds['password'])) or creds['password'] creds['username'] = password and hexlify(encrypt(password, creds['username'])) or creds['username'] keychain = Keychain() account = getlogin() password = "******" % (creds['username'], JOIN_STRING, creds['password']) return keychain.set_generic_password(KEYCHAIN, account, password, SERVICE_NAME)
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
def splitFile(rawData, password): fileSize = len(rawData) statusOk = True if fileSize == 0: print("File size is 0. Cannot send empty file.") statusOk = False chunkSize, remainder = divmod(fileSize, 4) rawDataChunks = [] print("Encrypting Data... Please wait...") print("This may take a few moments...") for x in range(0, 4): chunkHeader = '{}|chunk|'.format(x + 1) if x == 3: tempChunk = rawData[x * chunkSize:] encryptedChunk = encrypt(password, tempChunk) rawDataChunks.append(chunkHeader.encode() + encryptedChunk) else: tempChunk = rawData[x * chunkSize:(x + 1) * chunkSize] encryptedChunk = encrypt(password, tempChunk) rawDataChunks.append(chunkHeader.encode() + encryptedChunk) dataChunkGroups = [] for x in range(0, 4): if x == 3: dataChunkGroups.append((rawDataChunks[x], rawDataChunks[x - x])) else: dataChunkGroups.append((rawDataChunks[x], rawDataChunks[x + 1])) return rawDataChunks, dataChunkGroups, statusOk
def add_profile(self, profile, uname, pwd, api_key): self.c.execute("SELECT COUNT(*) FROM profiles WHERE profile=?", (profile, )) result = self.c.fetchone() if not result[0] == 0: print("Profile '{}' already exists in Profiles.") else: import VAPy vapy = VAPy.VAPy() token = vapy.get_token(uname, pwd, api_key) if not token: print( "VAPy was unable to retreive a Voat API token with the credentials you provided." ) else: print( "Encrypting and storing Voat API credentials. This may take a moment." ) ctoken = simplecrypt.encrypt(pwd, token) cuname = simplecrypt.encrypt(pwd, uname) capi_key = simplecrypt.encrypt(pwd, api_key) self.c.execute( "INSERT INTO profiles (profile, uname, api_key, token) VALUES (?,?,?,?)", (profile, cuname, capi_key, ctoken)) self.db.commit()
def authenticate(): """Authenticates the current user using OAuth2""" username = None try: access_token = get_access_token() except IOError: os.makedirs(path.join(path.expanduser('~'), SETTINGS_DIR), exist_ok=True) username = save_username() refresh_token, access_token, expiration = oauth_process() save_expiration(expiration) with open( path.join(path.expanduser('~'), SETTINGS_DIR, REFRESH_KEY_FILE), 'wb+') as refresh_key_file: refresh_key_file.write(encrypt(CLIENT_SECRET, refresh_token)) with open( path.join(path.expanduser('~'), SETTINGS_DIR, ACCESS_KEY_FILE), 'wb+') as access_key_file: access_key_file.write(encrypt(CLIENT_SECRET, access_token)) if username is None: try: username = get_username() except IOError: username = save_username() auth_string = _generate_auth_string(username, access_token) imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') imap_conn.authenticate('XOAUTH2', lambda x: auth_string.encode('ascii')) return imap_conn
def upload_file(con): ''' Uploads a file to the container on IBM Bluemix after encrypting it :param con: connection object :return: success message ''' # we use the Tkinter library to show a file selection dialog threshold = 200 container = enter_container() root = tk.Tk() root.withdraw() # print a message print("Opening file selection dialog") # get filepath fileopen = tkFileDialog.askopenfile(initialdir=return_home_path(), title="Select file", mode="rb") abs_path = os.path.abspath(fileopen.name) # get name of file filename = os.path.basename(abs_path) # filename = filename[:-4] + str(v) + filename[-4:] # get contents of file filecontents = fileopen.read() # Check if the File Exist res = check_file(con, filename) print(res[0], res[1]) filename = filename[:-4] + str(res[1]) + filename[-4:] if res[0]: v = int(res[1]) + 1 # con.delete_object(container, filename) filename = filename[:-5] + str(v) + filename[-4:] print("Encrypting file %s" % (filename)) compressed = simplecrypt.encrypt(PASSWORD, filecontents) # print("Size is : ", sys.getsizeof(compressed)) if container == "imagesmall": if sys.getsizeof(compressed) < threshold: print("Uploading files to %s container" % (container)) con.put_object(container, filename, compressed, "text/plain") else: print("Unable to load because less than 200kb") else: print("Uploading files to %s container" % (container)) con.put_object(container, filename, compressed, "text/plain") else: print("Encrypting file %s" % (filename)) compressed = simplecrypt.encrypt(PASSWORD, filecontents) if container == "imagesmall": if sys.getsizeof(compressed) < threshold: print("Uploading files to %s container" % (container)) con.put_object(container, filename, compressed, "text/plain") else: print("Unable to load because less than 200kb") else: print("Uploading files to %s container" % (container)) con.put_object(container, filename, compressed, "text/plain")
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 startSendingGPS(tracker): try: if (tracker.getPairingStatus() and not (tracker.getSessionKeyST() == '')): port = input( "What is the port number to send the GPS coordinates to? ") #nao envia localizacao se o tracker ainda nao estiver emparelhado com um manager client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = 'localhost' address = (host, int(port)) trackerId = str(tracker.getID()) symKey = tracker.getsymKeyMT() sessionKey = tracker.getSessionKeyST() send_dict = {} send_dict["TrackerID"] = trackerId print("Starting to send GPS Location to Server...\n") sleep(1) while True: # tuple with timestamp of GPS coordinates and the actual coordinates --> (time, GPSCoord) tupleTimeGPS = tracker.gpsPackgBuilder() print("\nGPS LOCATION ==> {}\n".format(tupleTimeGPS)) # encrypting only the GPSCoord print("Encrypting GPS Coordinates with symmetric key ...\n") encryptedGPS = simplecrypt.encrypt(symKey, pickle.dumps(tupleTimeGPS)) checkIfSOS(tracker) sosStatus = tracker.getSosStatus() msg = {} msg['GPS Time'] = tupleTimeGPS[0] msg['GPSCoord'] = encryptedGPS print("Encrypting whole package with session key ...\n") encryptedMessage = simplecrypt.encrypt(sessionKey, pickle.dumps(msg)) send_dict["MSG"] = encryptedMessage send_dict["SOS"] = sosStatus send_dict["TimeStamp"] = tupleTimeGPS[0] encryptedPackage = pickle.dumps(send_dict) client.sendto(encryptedPackage, address) else: raise ValueError() except (ValueError, AssertionError): print( "\nYou must pair with a Manager first and then generate a SessionKey...\n" ) createTrackerMenu(tracker)
def right(): plaintext = 'hello world' key = 'python' ciphertext = encrypt(key, plaintext) print ciphertext key = 'password' ciphertext = encrypt(key, plaintext) print ciphertext plaintext = decrypt(key, ciphertext) print plaintext
def dataproxy_resource_update(context, data_dict=None): """ Intercepts default resource_update action and encrypts password for dataproxy type resources Args: context: Request context. data_dict: Parsed request parameters. Returns: see get_action('resource_update'). Raises: Exception: if ckan.dataproxy.secret configuration not set. """ #If not set, default to empty string data_dict['url_type'] = data_dict.get('url_type', '') url_type = data_dict['url_type'] if url_type == 'dataproxy': secret = config.get('ckan.dataproxy.secret', False) if not secret: raise Exception('ckan.dataproxy.secret must be defined to encrypt passwords') #replace password with a _password_ placeholder password = data_dict.get('db_password', '') if password == '': #we don't want to overwrite existing password with empty string resource = Resource.get(data_dict['id']) data_dict['db_password'] = resource.extras['db_password'] else: data_dict['url'] = data_dict['url'].replace(password, '_password_') #encrypt db_password data_dict['db_password'] = hexlify(encrypt(secret, password)) site_url = config.get('ckan.site_url', '127.0.0.1') data_dict['url'] = '{0}/api/3/action/datastore_search?resource_id={1}&downloaded=true'.format(site_url, data_dict['id']) return orig_resource_update(context, data_dict)
def send_broadcast(request): if request.method == 'POST': form = BroadcastForm(request.POST) # validation checking... if form.is_valid(): sender = request.user subject = request.POST['subject'] text = request.POST['body'] encrypted = request.POST.get('encrypted', False) enc_key = request.POST['enc_key'] raw_b = b"" if enc_key == "": enc_key = "N/A" else: #encrypt #encrypt raw_b = encrypt(enc_key, text) text=str(raw_b) pm_broadcast(sender,"", subject, encrypted, raw=raw_b, body=text) return render(request, 'postman/inbox.html', ) else: return render(request, 'broadcast.html', {'message_form': form}) else: form = BroadcastForm() return render(request, 'broadcast.html', {'message_form': form})
def post(self): auth_code = self.request.get('code') auth_header = "Basic " + base64.b64encode(k_client_id + b":" + k_client_secret) params = { "grant_type": "authorization_code", "redirect_uri": k_client_callback_url, "code": auth_code } encoded_params = urllib.urlencode(params) response = urlfetch.fetch(url=k_spotify_accounts_endpoint + "/api/token", payload=encoded_params, method=urlfetch.POST, headers={"Authorization": auth_header}, validate_certificate=True) if response.status_code == 200: token_data = json.loads(response.content) refresh_token = token_data["refresh_token"] encrypted_token = simplecrypt.encrypt(k_encryption_secret, refresh_token) base64_encrypted_token = base64.encodestring(encrypted_token) token_data["refresh_token"] = base64_encrypted_token response.content = json.dumps(token_data) self.response.headers.add_header("Access-Control-Allow-Origin", '*') self.response.headers['Content-Type'] = 'application/json' self.response.status = response.status_code self.response.write(response.content)
def simple_encrypt64(key, cleartext): try: return urlsafe_b64encode(encrypt(key, cleartext)).decode('utf-8') except NameError as e: if 'encrypt' in e.args[0]: return urlsafe_b64encode(cleartext.encode('utf-8')).decode('utf-8') raise e
def encode(msg, m_file, passwd=None): """This functions encodes the given secret into a destination file. Args: msg (str): For encoding commands the message or text file to encode For decoding commands the file to decode m_file (str): For encoding commands the file in which the message will be encoded For decoding commands the password to decrypt the message Kwargs: password (str): For encoding commands the password to encrypt the message """ secret = get_secret_msg(msg) #Convert the destination file into hex so that we can measure its free space with open(m_file, "rb") as dest_file: destination = dest_file.read() if passwd is not None: from simplecrypt import encrypt secret = encrypt(passwd, secret) msg_chars = len(secret) secret = secret.encode('hex') destination = destination.encode('hex') #At this point 'secret'(str) and 'destination'(file) are now hex values(str) #Free space in the destination is currently defined as spaces #We decide if there is enough blank space to just plug in the secret message free_space = size_of_free_space(destination) write_steganized_output_file(free_space, msg_chars, m_file, secret, destination)
def crypt_decrypt_test(message, password, use_zlib=False, show_hex=False): start_time = time.time() text_hex = binascii.hexlify(message) message_digest = get_digest(message) log.debug('Message len: {}, digest: {}'.format(len(message), message_digest)) show_hex and log.debug('text_hex: "{}"'.format(text_hex)) log.debug('') log.debug('Encrypt...') encrypt_text = encrypt(password, message, use_zlib) encrypt_text_hex = binascii.hexlify(encrypt_text) encrypt_message_digest = get_digest(encrypt_text) log.debug('Encrypt message len: {}, digest: {}'.format(len(encrypt_text), encrypt_message_digest)) show_hex and log.debug('encrypt_text_hex: "{}"'.format(encrypt_text_hex)) log.debug('') log.debug('Decrypt...') decrypt_text = decrypt(password, encrypt_text, use_zlib) decrypt_text_hex = binascii.hexlify(decrypt_text) decrypt_message_digest = get_digest(decrypt_text) log.debug('Decrypt message len: {}, digest: {}'.format(len(decrypt_text), decrypt_message_digest)) show_hex and log.debug('decrypt_text_hex: "{}"'.format(decrypt_text_hex)) log.debug('') log.debug('Digest is equal: {}'.format(message_digest == decrypt_message_digest)) log.debug('Total time: {:.3f} seconds'.format(time.time() - start_time))
def okButPressed(self, isEdit, oldSite='',oldUsername=''): try: if not isEdit: self.table.setRowCount(self.table.rowCount()+1) self.username=self.addUI.usrBox.text() self.site=self.addUI.siteBox.text() self.password=self.addUI.passBox.text() bPass=b64encode(encrypt(self.key, self.password)) conn = sqlite3.connect('data') cursor=conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS users_data (userId VARCHAR(100), site VARCHAR(100),username VARCHAR(100) , password VARCHAR(255))") if isEdit: cursor.execute("UPDATE users_data SET site=?, username=?, password=? WHERE userId=? and site=? and username=?",(self.site,self.username,bPass,self.userId,oldSite,oldUsername)) else: cursor.execute("INSERT INTO users_data (userId, site, username, password) VALUES (?,?,?,?)",(self.userId,self.site,self.username,bPass)) conn.commit() conn.close() self.addUI.close() i=self.table.rowCount()-1 if isEdit: i=self.table.selectedIndexes()[0].row() self.table.setItem(i,0,QTableWidgetItem(str(self.site))) self.table.setItem(i,1,QTableWidgetItem(str(self.username))) self.table.setItem(i,2,QTableWidgetItem(str(self.password))) except Exception as e: print(e)
def AESE_conn(): conn = sqlite3.connect('database.db') c = conn.cursor() global password1 password1 = E5.get() plaintext = E6.get() ciphertext = encrypt(password1, plaintext) encoded_cipher = b64encode(ciphertext) E6_1.insert(0, encoded_cipher) def create_table(): c.execute( "CREATE TABLE IF NOT EXISTS AES_encrypt(Date_and_Time text,Plain_text text, Cipher_text text, Password text)" ) def data_entry(): unix = time.time() date = str( datetime.datetime.fromtimestamp(unix).strftime( '%Y-%m-%d %H:%M:%S')) p = plaintext ciph = encoded_cipher pswd = password1 c.execute( "INSERT INTO AES_encrypt(Date_and_Time,Plain_text,Cipher_text,Password) VALUES(?,?,?,?)", (date, p, ciph, pswd)) conn.commit() c.close() conn.close() create_table() data_entry()
def enc(data, passphrase): ciphertext = encrypt(passphrase, data) ciphertext = base64.b64encode(ciphertext) hex_passphrase = codecs.encode(passphrase, 'hex') print 'Data: ', ciphertext print 'Passphrase: ', hex_passphrase return ciphertext
def encrypt_store_data(self, crypt_file_path, password, idea_collection): self.screenmanager.clear_widgets() ser_data = jsonpickle.encode(idea_collection) enc_data = simplecrypt.encrypt(password, ser_data) with open(crypt_file_path, 'wb') as f: f.write(enc_data) self.stop()
def create_config(project_dir, encrypt_pass='******'): config_dir = '%s/.config' % project_dir f = open(config_dir, 'w') print print '------Welcome to DataTools Configuration---------' print print 'Select SQL Flavor' print '[1] - SQLite' print '[2] - MySQL' flavor = int(raw_input('Input Number: ')) print if flavor == 1: info = 'sqlite' info += ':%s.db' % raw_input('Database Name: ') elif flavor == 2: info = 'mysql' info += ':%s' % raw_input('Host: ') info += ':%s' % raw_input('Username: '******':%s' % raw_input('Password: '******':%s' % raw_input('Database Name: ') print print 'Encrypting Config File' f.write(encrypt(encrypt_pass, info)) print 'Config File Complete'
def main(key, password): print 'Uses aes encryption' print 'Key: %s Password: %s' % (key, password) encrypt_one = encrypt(key, password) # python string encrypt_two = encrypt(key, unicode(password)) # unicode encrypt_three = encrypt(key, password.encode('utf8')) # utf8 print 'encrypt_one: %s' % hexlify(encrypt_one) print 'encrypt_twp: %s' % hexlify(encrypt_two) print 'encrypt_three: %s' % hexlify(encrypt_three) print '\nEven though the key and password are the same' print 'Encoding matters' print 'encrypt_one == encrypt_two', encrypt_one == encrypt_two print 'encrypt_one == encrypt_three', encrypt_one == encrypt_three print 'encrypt_two == encrypt_three', encrypt_two == encrypt_three print '\nThe following will be the same for all 3' print 'plaintext: %s' % decrypt(key, encrypt_one)
def submitEmailPassword(): for k in request.forms.keys(): print k, request.forms[k] username = request.forms.get('email') password = request.forms.get('password') password_hashed = base64.urlsafe_b64encode(pbkdf2_sha256.encrypt(password, rounds=NOF_HASH_ROUNDS, salt_size=16)) username_encrypted = base64.urlsafe_b64encode(encrypt(ENCRYPTION_PASSWORD, username)) usersTable = db.table('users') existingUser = usersTable.search(where('key') == username_encrypted) if existingUser: if pbkdf2_sha256.verify(existingUser['values']['password'],password_hashed): pass else: print "wrong login" else: usersTable.insert({'key':username_encrypted, 'values':{'password':password_hashed}}) videosTable = db.table('videos') existing_cookie = request.get_cookie('sebifyme',secret=GLOBAL_COOKIE_SECRET) uid = existing_cookie['uid'] elements = videosTable.search((where('values').has('uploaded_by_uid') == uid) & (where('values').has('uploaded_by_user') == None)) for el in elements: currentValues = el['values'] currentValues['uploaded_by_user'] = username_encrypted videosTable.update({'values':currentValues}, eids=[el.eid]) website_content = template('video',video_name='joke.mp4') return website_content
def getToken(): config = ConfigParser.ConfigParser() config.readfp(open('../config/.sec')) password = config.get('Dolphinnext', 'VERIFY') encrypted = hexlify(encrypt(password, 'OK')) print encrypted return encrypted
def create_save(acc_number): # print("Heyy you called me!!!!!!!!!!!!!!!") conn = sqlite3.connect('database.db') c = conn.cursor() c.execute('select * from user_qr') temp = c.fetchall() try: para1 = len(temp) + 1 except: para1 = 1 print(para1) para2 = random.choice(addr_list) cipher = encrypt(para1, para2) encoded_cipher = str(b64encode(cipher)) c.execute('insert into user_qr values (?,?,?,"available")', (para1, encoded_cipher, acc_number)) conn.commit() qr_path = "static/qr/_" + str(para1) + ".png" url = pyqrcode.create(encoded_cipher) url.png(qr_path, scale=8) print(encoded_cipher) print(type(encoded_cipher))
def click_save(self): raw_text = self.textEdit.toPlainText() t=unicode(raw_text) ciphertext = encrypt('123', t) self.content.text = hexlify(ciphertext) self.content.save() self.textEdit.clear
def main(argv): message = sys.argv[1] password = getpass() cipher = encrypt(password, message) encoded_cipher = b64encode(cipher) print(encoded_cipher)
def dataproxy_resource_create(context, data_dict=None): """ Intercepts default resource_create action and encrypts password if resource is dataproxy type Args: context: Request context. data_dict: Parsed request parameters. Returns: see get_action('resource_create'). Raises: Exception: if ckan.dataproxy.secret configuration not set. """ #If not set, default to empty string url_type = data_dict.get('url_type') if url_type == 'dataproxy': secret = config.get('ckan.dataproxy.secret', False) if not secret: raise Exception('ckan.dataproxy.secret must be defined to encrypt passwords') password = data_dict.get('db_password') #replace password with a _password_ placeholder data_dict['url'] = 'tmpURL' #data_dict['url'].replace(password, '_password_') #encrypt db_password data_dict['db_password'] = hexlify(encrypt(secret, password)) data_dict = orig_resource_create(context, data_dict) site_url = config.get('ckan.site_url', '127.0.0.1') data_dict['url'] = '{0}/api/3/action/datastore_search?resource_id={1}&downloaded=true'.format(site_url, data_dict['id']) return orig_resource_update(context, data_dict)
def lumos_encryption_service(data, encrpytion_key=SECRET_KEY, url_encode=True, encrypt_mode=True): """ Encrpytion service function which takes in a str and encrpytion/decrpytion flag and return a st :param data: plaintext/ciphertext str :param encrpytion_key: key used for encrpytion services :return: str """ if encrypt_mode: service_data = encrypt(encrpytion_key, data) if url_encode: service_data = base64.urlsafe_b64encode(service_data) service_data = service_data else: if url_encode: data = base64.urlsafe_b64decode(data) service_data = decrypt(encrpytion_key, data) service_data = str(service_data, 'utf-8') return service_data
def main(argv): filename_in = sys.argv[1] filename_out = sys.argv[2] password = getpass() with open(filename_in, "r") as input: with open(filename_out, "wb+") as output: lines = input.readlines() line_num = 1 total_lines = len(lines) if line_num > total_lines: print('File contains no lines') sys.exit(2) for line in lines: if ',' not in line: print('Only csv files are supported') sys.exit(2) print(f'Processing line {line_num} out of {total_lines}') words = line.split(',') for i in range(len(words)): word = words[i].replace('\n', '').strip() cipher = encrypt(password, word) encoded_cipher = b64encode(cipher) output.write(encoded_cipher) if i < len(words) - 1: output.write(b',') output.write(b'\n') line_num += 1
def encrypt_file(file_name, key): with open(file_name, 'rb') as fo: plaintext = fo.read() enc = encrypt(plaintext, key) with open(file_name + ".enc", 'wb') as fo: fo.write(enc) os.remove(file_name)
def dataproxy_resource_create(context, data_dict=None): """ Intercepts default resource_create action and encrypts password if resource is dataproxy type Args: context: Request context. data_dict: Parsed request parameters. Returns: see get_action('resource_create'). Raises: Exception: if ckan.dataproxy.secret configuration not set. """ #If not set, default to empty string url_type = data_dict.get('url_type') if url_type == 'dataproxy': secret = config.get('ckan.dataproxy.secret', False) if not secret: raise Exception('ckan.dataproxy.secret must be defined to encrypt passwords') password = data_dict.get('db_password') #replace password with a _password_ placeholder data_dict['url'] = data_dict['url'].replace(password, '_password_') #encrypt db_password data_dict['db_password'] = hexlify(encrypt(secret, password)) return orig_resource_create(context, data_dict)
def encrypt_fn(destroy_this): password = password_var_enc.get() password_conf = password_var_con.get() if password == password_conf: ciphertext = encrypt(password, private_key_readable) pem_file = open("privkey_encrypted.der", 'wb') pem_file.write(base64.b64encode(ciphertext)) pem_file.close() encrypt_b.configure(text="Encrypted", state=DISABLED) destroy_this.destroy() os.remove("privkey.der") lock_b.configure(text="Lock", state=NORMAL) else: mismatch = Toplevel() mismatch.title("Bismuth") mismatch_msg = Message(mismatch, text="Password mismatch", width=100) mismatch_msg.pack() mismatch_button = Button(mismatch, text="Continue", command=mismatch.destroy) mismatch_button.pack(padx=15, pady=(5, 5))
def _set_internal_password(self): for user in self: cipher = encrypt('AIM', user.password) self.env.cr.execute( 'UPDATE res_users_dummy SET internal_password=%s WHERE id=%s', (cipher, user.id) )
def EncryptForFile(key, text_): pad_msg = "$$$$" + text_ # Separator between the text_ and the padder print pad_msg encrypted_text = encrypt(key, pad_msg.rjust( history_file_size, 'S')) # extra will be padded by 'S' char with open(history_file_name, 'wb') as f: f.write(encrypted_text)
def make_configuration_file(backup_directory: str, file_uuids_with_paths: dict, password: str): configuration_file_path = os.path.join(backup_directory, CONFIGURATION_FILE_NAME) configuration_contents = json.dumps(file_uuids_with_paths) encrypted_contents = encrypt(password, configuration_contents) write_file_with_bytes(configuration_file_path, encrypted_contents)
def createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries=0): price = decimal.Decimal(offer.obj['price']) try: pubkey = btcd.validateaddress(mybtc)['pubkey'] multisig = btcd.createmultisig( 2, sorted([offer.obj['pubkey'], pubkey]) ) change_addr = btcd.getrawchangeaddress() except httplib.BadStatusLine: reconnect_btcd(retries) return createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries+1) def create_funding(fee, retries=0): rawtx_hex = mktx(price, multisig['address'], change_addr, fee) try: return btcd.signrawtransaction(rawtx_hex)['hex'] except httplib.BadStatusLine: reconnect_btcd(retries) return create_funding(fee, retries+1) signedtx_hex = create_funding(tx_fee) crypttx = base64.b64encode( simplecrypt.encrypt(cryptkey, signedtx_hex) ) try: signedtx = btcd.decoderawtransaction(signedtx_hex) except httplib.BadStatusLine: reconnect_btcd(retries) return createorder(myidhash, mybtc, offer, cryptkey, tx_fee, retries+1) vout = searchtxops(signedtx, multisig['address'], price) return createordermsgstr(mybtc, offer.hash, offer.obj['vendorid'], myidhash, \ pubkey, multisig, crypttx, signedtx['txid'], \ vout, signedtx['vout'][vout]['scriptPubKey']['hex'] )
def encrypt_coin_string(self): self.password = self.read_key() self.coins = self.coins_managment() self.key = encrypt(self.password, self.coins) self.keyfile = open("coins", "w") self.keyfile.write(self.key) self.keyfile.close()
def dataproxy_resource_create(context, data_dict=None): """ Intercepts default resource_create action and encrypts password if resource is dataproxy type Args: context: Request context. data_dict: Parsed request parameters. Returns: see get_action('resource_create'). Raises: Exception: if ckan.dataproxy.secret configuration not set. """ #If not set, default to empty string url_type = data_dict.get('url_type') if url_type == 'dataproxy' and data_dict.get('db_password') is not None: secret = config.get('ckan.dataproxy.secret', False) if not secret: raise Exception( 'ckan.dataproxy.secret must be defined to encrypt passwords') password = data_dict.get('db_password') #replace password with a _password_ placeholder data_dict['url'] = data_dict['url'].replace(password, '_password_') #encrypt db_password data_dict['db_password'] = hexlify(encrypt(secret, password)) return orig_resource_create(context, data_dict)
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
def log_access_attempt(email, password, ip, successful): LoginAttempt.objects.create(attempt_email=email, attempt_password=hexlify( encrypt(settings.ACCESS_LOG_KEY, password.encode('utf8'))), attempting_ip=ip, successful=successful)
def dataproxy_resource_update(context, data_dict=None): """ Intercepts default resource_update action and encrypts password for dataproxy type resources Args: context: Request context. data_dict: Parsed request parameters. Returns: see get_action('resource_update'). Raises: Exception: if ckan.dataproxy.secret configuration not set. """ #If not set, default to empty string data_dict['url_type'] = data_dict.get('url_type', '') url_type = data_dict['url_type'] if url_type == 'dataproxy': secret = config.get('ckan.dataproxy.secret', False) if not secret: raise Exception( 'ckan.dataproxy.secret must be defined to encrypt passwords') #replace password with a _password_ placeholder password = data_dict.get('db_password', '') if password == '': #we don't want to overwrite existing password with empty string resource = Resource.get(data_dict['id']) data_dict['db_password'] = resource.extras['db_password'] else: data_dict['url'] = data_dict['url'].replace(password, '_password_') #encrypt db_password data_dict['db_password'] = hexlify(encrypt(secret, password)) return orig_resource_update(context, data_dict)
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
def save_secure_data(data): """ Save a data structure such that it can only be read from the user's keychain, while they are logged in, and only with knowledge of the user's hardware ID. """ encrypted_data = simplecrypt.encrypt(get_hardware_id(), data) encoded_data = base64.b64encode(encrypted_data) keyring.set_password("FreshPass Encrypted Log", "log", encoded_data)
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
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
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
def simple_encryptor(password, ciphertext, enc='utf-8', wrapper=None): """ Decrypt ciphertext using password """ if not wrapper: wrapper = base64.b64encode ciphertext = simplecrypt.encrypt(password, ciphertext) return wrapper(ciphertext)
def create_encrypted_key(crypto,password): private_key = bitcoin.random_key() public_key = bitcoin.privtopub(private_key) # encrypt private key here encrypted_private_key=simplecrypt.encrypt(password=password,data=private_key) c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)', (crypto,public_key,0,encrypted_private_key,datetime.datetime.now())) conn.commit() return public_key
def encrypt(self, streamFile): if hasattr(streamFile, 'read'): self.logger.debug("Encrypting file") encrypted = simplecrypt.encrypt_file(self.password, streamFile) self.logger.debug("File encrypted successfully. ") else: self.logger.debug("Encrypting bytes") encrypted = simplecrypt.encrypt(self.password, streamFile) self.logger.debug("Encrypted successfully. ") return encrypted
def commit_log(key, log_file, data): """ Takes the JSON data and dumps it to a string. writes the string to a file using the encrypt simplecrypt method. """ with open(log_file, "wb") as json_file: json_data = json.dumps(data) comp = bz2.compress(json_data) enc_data = encrypt(key, comp) json_file.write(enc_data) return True
def test_timing_encrypt(self): pw = "password" data = "data" cs = create_cipher_storage(pw) curr_time = datetime.datetime.now() for i in range(100): encrypt(pw, data, cs) curr_time = datetime.datetime.now() - curr_time print curr_time / 100 curr_time = datetime.datetime.now() for i in range(10): encrypt(pw, data, cs) curr_time = datetime.datetime.now() - curr_time print curr_time / 10
def test_pre_computed_encrypt(self): pw = "password" data = "data" # Calculate cipher. cs = create_cipher_storage(pw) # encrypted - pre-computed. encrypted_computed = encrypt(pw, data, cs) self.assertTrue(decrypt(pw, encrypted_computed) == data)