def _pbkdf2(password, salt, n_bytes, count): # the form of the prf below is taken from the code for PBKDF2 return PBKDF2(password, salt, dkLen=n_bytes, count=count, prf=lambda p, s: HMAC.new(p, s, HASH).digest())
def generate_aes_encryption_key(password: str, salt: bytes = None) -> Tuple[bytes, bytes]: """ uses PBKDF2 with SHA256 HMAC to derive a 32-byte encryption key from the provided password """ if salt is None: salt = get_random_bytes(8) return PBKDF2(password, salt, 32, count=1000000, hmac_hash_module=SHA256), salt
def __init__(self): # init base class super().__init__() self.login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login Data" self.tmp_login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login_tmp" if os.path.exists(self.login_db_path): shutil.copy2( self.login_db_path, self.tmp_login_db_path ) # making a temp copy since login data db is locked while chrome is running else: print("It seems that no chrome browser is installed! Exiting...") exit(1) self.iv = b' ' * 16 self.password = '******'.encode('utf8') bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': self.password = item.get_secret() break self.key = PBKDF2(password=self.password, salt=b'saltysalt', dkLen=16, count=1) self.cipher = AES.new(self.key, AES.MODE_CBC, IV=self.iv) self.bytechars = [ b'\x01', b'\x02', b'\x03', b'\x04', b'\x05', b'\x06', b'\x07', b'\x08', b'\x09' ]
def test3(self): # Verify that hmac_hash_module works like prf password = b("xxx") salt = b("yyy") for hashmod in (MD5, SHA1, SHA224, SHA256, SHA384, SHA512): pr1 = PBKDF2(password, salt, 16, 100, prf=lambda p, s: HMAC.new(p, s, hashmod).digest()) pr2 = PBKDF2(password, salt, 16, 100, hmac_hash_module=hashmod) self.assertEqual(pr1, pr2)
def encrypt(content: bytes, password: str) -> str: """ Encrypt html content, act like `staticrypt`. Args: content: html content bytes password: password to encrypt and decrypt Returns: The encrypted contend """ salt = urandom(16) iv = urandom(16) key = PBKDF2(password=password, salt=salt, dkLen=32, count=1000) cryptor = AES.new(key, AES.MODE_CBC, iv) pkcs7_content = pad(content, AES.block_size) aes_encrypted_bytes = b64encode(cryptor.encrypt(pkcs7_content)) aes_encrypted_content = (salt.hex() + iv.hex() + aes_encrypted_bytes.decode("utf-8")) hmac_signature = hmac.new(key=sha256( password.encode("utf-8")).hexdigest().encode("utf-8"), msg=aes_encrypted_content.encode("utf-8"), digestmod=sha256).hexdigest() return hmac_signature + aes_encrypted_content
def decrypt_aes_256_cbc_pbkdf2( ciphertext: bytes, password: str, ) -> bytes: """Decrypt an openssl encrypted bytestring: Cipher: AES256-CBC Salted: yes Key Derivation: PKBDF2, with SHA256 digest, 10000 cycles """ SALT_LENGTH = 8 KEY_LENGTH = 32 IV_LENGTH = 16 PBKDF2_CYCLES = 10_000 salt = ciphertext[:SALT_LENGTH] raw_key = PBKDF2(password, salt, KEY_LENGTH + IV_LENGTH, count=PBKDF2_CYCLES, hmac_hash_module=SHA256) key, iv = raw_key[:KEY_LENGTH], raw_key[KEY_LENGTH:] decryption_suite = AES.new(key, AES.MODE_CBC, iv) decrypted_pkg = decryption_suite.decrypt(ciphertext[SALT_LENGTH:]) return _strip_fill_bytes(decrypted_pkg)
def decrypt(secretkey, params): iv = b64decode(params['iv']) salt = b64decode(params['salt']) #~ keylen = params.get('ks', 128) // 8 # FIXME use somewhere? taglen = params.get('ts', 64) // 8 iterations = params.get('iter', 1000) data = b64decode(params['ct']) ciphertext = data[:-taglen] tag = data[-taglen:] if params.get('adata'): raise NotImplementedError('authenticated data support is not implemented') iv = trunc_iv(iv, ciphertext, taglen) hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest() key = PBKDF2(secretkey, salt=salt, count=iterations, prf=hash_func) mode_str = params.get('mode', 'ccm') mode = dict(ccm=AES.MODE_CCM)[mode_str] if mode_str == 'ccm': cipher = AES.new(key, mode=AES.MODE_CCM, nonce=iv, mac_len=taglen) else: cipher = AES.new(key, mode=mode, iv=iv) decrypted = cipher.decrypt_and_verify(ciphertext, tag) return decrypted
def encrypt(plaintext): iv = urandom(16) salt = urandom(8) iterations = 1000 ks = 128 ts = 64 hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest() password = b64encode(urandom(32)) key = PBKDF2(password, salt=salt, count=iterations, prf=hash_func) smalliv = trunc_iv(iv, plaintext, 0) cipher = AES.new(key, mode=AES.MODE_CCM, nonce=smalliv, mac_len=ts // 8) ciphertext = b''.join(cipher.encrypt_and_digest(plaintext)) # OrderedDict because 0bin is a piece of shit requiring "iv" as the first key return password.decode('ascii'), OrderedDict([ ('iv', b64encode(iv).decode('ascii')), ('v', 1), ('iter', iterations), ('ks', ks), ('ts', ts), ('mode', 'ccm'), ('adata', ''), ('cipher', 'aes'), ('salt', b64encode(salt).decode('ascii')), ('ct', b64encode(ciphertext).decode('ascii')), ])
def handleLogin(self): sd = SAHDao() res = sd.select_item2() res2 = sd.select_item_pw() res_salt = sd.select_item_salt() tmp_dict = {} salt_list = [] for i in range(len(res)): dict1 = {res[i][0]: res2[i][0]} tmp_dict.update(dict1) salt_list.append(res_salt[i][0]) dict_list_id = list(tmp_dict.keys()) dict_list_pw = list(tmp_dict.values()) print(dict_list_pw) for i in range(len(dict_list_id)): dict_list_id[i] = dict_list_id[i].strip() salt_index = dict_list_id.index(self.id_name.text()) salt_res_2 = salt_list[salt_index] if self.id_name.text() in dict_list_id: password = self.pw.text() salt = base64.urlsafe_b64decode(salt_res_2) pb = PBKDF2(password, salt, 128, 10000, hmac_hash_module=SHA1) key = base64.b64encode(pb).decode('utf-8') if key in dict_list_pw: self.accept() else: QtWidgets.QMessageBox.warning(self, '비밀번호 오류', '비밀번호가 틀렸습니다.') else: QtWidgets.QMessageBox.warning(self, '아이디오류', '아이디가 틀렸습니다.')
def my_rand(n): # kluge: use PBKDF2 with count=1 and incrementing salt as deterministic PRNG my_rand.counter += 1 return PBKDF2(master_key, "my_rand:%d" % my_rand.counter, dkLen=n, count=1)
def encode_text_from_note(text, password): salt = get_random_bytes(16) key = PBKDF2(password.encode('utf-8'), salt) utfText = text.encode('utf-8') aes = AES.new(key, AES.MODE_CBC) encryptedText = b64encode(aes.encrypt(pad(utfText, AES.block_size))).decode('utf-8') iv = b64encode(aes.iv).decode('utf-8') return encryptedText, iv, b64encode(salt).decode('utf-8')
def __init__(self, entropy, IDString): sp = GetUserName() + b'+@#$%+' + IDString passwdData = encode(SHA256(sp), charMap2) salt = entropy key_iv = PBKDF2(passwdData, salt, count=0x800, dkLen=0x400) self.key = key_iv[0:32] self.iv = key_iv[32:48] self.crp.set_decrypt_key(self.key, self.iv)
def _create_cipher(self, password, salt, IV): """ Create the cipher object to encrypt or decrypt a payload. """ from Cryptodome.Protocol.KDF import PBKDF2 from Cryptodome.Cipher import AES pw = PBKDF2(password, salt, dkLen=self.block_size) return AES.new(pw[:self.block_size], AES.MODE_CFB, IV)
def encrypt_note_content(note_content, password): salt = get_random_bytes(16) key = PBKDF2(password.encode('utf-8'), salt) to_encrypt = note_content.encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) encrypted_note_bytes = cipher.encrypt(pad(to_encrypt, AES.block_size)) iv = b64encode(cipher.iv).decode('utf-8') encrypted_note = b64encode(encrypted_note_bytes).decode('utf-8') return encrypted_note, salt, iv
def decryptutil(password, result): b64 = json.loads(result) json_k = ['nonce', 'salt', 'ciphertext', 'tag'] jv = {k: b64decode(b64[k]) for k in json_k} key = PBKDF2(password=password, salt=jv['salt'], count=1000) cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce']) plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) # A readable client socket has data sys.stdout.write(plaintext.decode("utf-8"))
def encrypt(key, plaintext): if key == '': return b64encode(plaintext.encode()).decode().replace('=', '') salt = get_random_bytes(8) iv = get_random_bytes(16) key = PBKDF2(key.encode(), salt, count=10000, dkLen=16, prf=prf) data, compression = zlib(plaintext) nonce = truncate_iv(iv, len(data) * 8, 64) cipher = AES.new(key, AES.MODE_CCM, nonce=nonce, mac_len=8) ciphertext, tag = cipher.encrypt_and_digest(data) return b64encode(salt + iv + ciphertext + tag + compression).decode().replace('=', '')
def AES_GCM_encrypt(data, password): salt = get_random_bytes(16) # salt for generate key key = PBKDF2(password=password, salt=salt, dkLen=32) cipher = AES.new(key, AES.MODE_GCM) cipher.update(salt) ciphertext, tag = cipher.encrypt_and_digest(data) json_k = ['nonce', 'salt', 'ciphertext', 'tag'] json_v = [ b64encode(x).decode('utf-8') for x in [cipher.nonce, salt, ciphertext, tag] ] result = json.dumps(dict(zip(json_k, json_v))) return result.encode()
def get_cookies(self): salt = b'saltysalt' length = 16 if sys.platform == 'darwin': # running Chrome on OSX my_pass = keyring.get_password('Chrome Safe Storage', 'Chrome') my_pass = my_pass.encode('utf8') iterations = 1003 key = PBKDF2(my_pass, salt, length, iterations) elif sys.platform.startswith('linux'): # running Chrome on Linux my_pass = '******'.encode('utf8') iterations = 1 key = PBKDF2(my_pass, salt, length, iterations) elif sys.platform == 'win32': key = None else: raise BrowserCookieError('Unsupported operating system: ' + sys.platform) for cookie_file in self.cookie_files: with create_local_copy(cookie_file) as tmp_cookie_file: con = sqlite3.connect(tmp_cookie_file) cur = con.cursor() cur.execute('SELECT value FROM meta WHERE key = "version";') version = int(cur.fetchone()[0]) query = 'SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value FROM cookies;' if version < 10: query = query.replace('is_', '') cur.execute(query) for item in cur.fetchall(): host, path, secure, expires, name = item[:5] value = self._decrypt(item[5], item[6], key=key) yield create_cookie(host, path, secure, expires, name, value) con.close()
def decrypt(key, data): data = b64decode(data + '=' * (len(data) % 4)) if key == '': return data.decode() salt = data[:8] iv = data[8:24] key = PBKDF2(key.encode(), salt, count=10000, dkLen=16, prf=prf) ciphertext = data[24:-1] nonce = truncate_iv(iv, len(ciphertext) * 8, 64) cipher = AES.new(key, AES.MODE_CCM, nonce=nonce, mac_len=8) if data[-1] == b'0'[0]: return cipher.decrypt_and_verify(ciphertext[:-8], ciphertext[-8:]).decode() return zlib(cipher.decrypt_and_verify(ciphertext[:-8], ciphertext[-8:])).decode()
def generate_key(password, cipher_suite_id, salt=None): password = _utils.validate_password(password) cipher_suite_id = _utils.validate_cipher_suite_id(cipher_suite_id) if cipher_suite_id == 0: return None salt = salt or bytearray([0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]) cipher_suite = CIPHERS[cipher_suite_id] return PBKDF2( password, salt, dkLen=cipher_suite["key_size"] // 8, )
def AES_GCM_decrypt(result, password): try: b64 = json.loads(result) json_k = ['nonce', 'salt', 'ciphertext', 'tag'] jv = {k: b64decode(b64[k]) for k in json_k} key = PBKDF2(password=password, salt=jv['salt'], dkLen=32) cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce']) cipher.update(jv['salt']) plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) except (ValueError, KeyError): # if fail to decrypt report an error to STDERR and exit sys.stderr.write("Incorrect decryption") return '' else: return plaintext
def encrypted_request_payload(self, request: FfRequest, payload: str) -> str: self.logger.debug('Encrypting request payload') if not self.config.pre_shared_key: raise RuntimeError( 'Cannot encrypt payload without pre_shared_key set') salt = get_random_bytes(16) derived_key = PBKDF2(self.config.pre_shared_key, salt, dkLen=32, count=self.config.pbkdf2_iterations, hmac_hash_module=SHA256) iv = get_random_bytes(12) cipher = AES.new(key=derived_key, mode=AES.MODE_GCM, nonce=iv, mac_len=16) ciphertext, tag = cipher.encrypt_and_digest( bytearray(payload.encode('utf8'))) request.options.append( FfRequest.Option(FfRequest.Option.Type.ENCRYPTION_MODE, 1, bytearray([FfRequest.EncryptionMode.AES_256_GCM ]))) request.options.append( FfRequest.Option(FfRequest.Option.Type.ENCRYPTION_IV, len(iv), bytearray(iv))) request.options.append( FfRequest.Option(FfRequest.Option.Type.ENCRYPTION_TAG, len(tag), bytearray(tag))) request.options.append( FfRequest.Option(FfRequest.Option.Type.KEY_DERIVE_MODE, 1, bytearray([FfRequest.KeyDeriveMode.PBKDF2]))) request.options.append( FfRequest.Option(FfRequest.Option.Type.KEY_DERIVE_SALT, len(salt), bytearray(salt))) self.logger.debug('Encrypted request into %d bytes' % len(ciphertext)) return ciphertext
def import_data(self, input, password): "Imports data into an entrystore" # check and pad password if password is None: raise base.PasswordError # check the data self.check(input) dataversion = self.__parse_header(input[:12]) # handle only version 2 data files if dataversion != 2: raise base.VersionError # Fetch the used 64 bit salt salt = input[12:20] iv = input[20:36] key = PBKDF2(password, salt, 32, count=12000, hmac_hash_module=SHA1) # decrypt the data input = input[36:] if len(input) % 16 != 0: raise base.FormatError cipher = AES.new(key, AES.MODE_CBC, iv) input = cipher.decrypt(input) hash256 = input[0:32] data = input[32:] if hash256 != hashlib.sha256(data).digest(): raise base.PasswordError # decompress data padlen = data[-1] for i in data[-padlen:]: if i != padlen: raise base.FormatError data = zlib.decompress(data[0:-padlen]).decode() # check and import data if data.strip()[:5] != "<?xml": raise base.FormatError entrystore = RevelationXML.import_data(self, data) return entrystore
def __init__(self, password, salt): """ derive the encryption key, the mac signing key and the iv from the passphrase and salt :param password: the inital passphrase :param salt: the rainbow defending salt :return: - nothing - """ master_key = PBKDF2(password=password, salt=salt, dkLen=32, count=65432, prf=Crypter.hmac_sha256) U1 = hashlib.sha256(master_key).digest() U2 = hashlib.sha256(U1).digest() self.enc_key = U1[:16] self.mac_key = U2[:16]
def make_key(crypto_params, salt=None): key = crypto_params.get("key") key_length = crypto_params["key_length"] kd_params = crypto_params["key_derivation"] algorithm = kd_params["algorithm"] salt_bytes = kd_params["salt_bytes"] iteration = kd_params["iteration"] prf = kd_params["prf"] if salt is None: salt = get_random_bytes(salt_bytes) else: assert len(salt) == salt_bytes if key is not None: if crypto_params.get("password") is not None: raise InvalidArgumentError( "only one of crypto.key or crypto.password can be specified.") if type(key) != bytes: raise InvalidArgumentError("crypto.key must be bytes") if len(key) * 8 != key_length: emsg = f"length of crypto.key (={len(key) * 8}) must be same as crypto.key_length(={key_length})" raise InvalidArgumentError(emsg) else: password = get_password(crypto_params) if algorithm == "pbkdf2" or algorithm == "PBKDF2WithHmacSHA256": hmac_hash_module = conv_param( prf, { "HMAC-SHA256": SHA256, "HMAC-SHA384": SHA384, "HMAC-SHA512": SHA512, }, "crypto:key_derivation:prf") key = PBKDF2(password, salt, dkLen=int(key_length / 8), count=iteration, hmac_hash_module=hmac_hash_module) else: logger.error("invalid crypto:key_derivation:algorithm") raise InvalidArgumentError() logger.debug(f"XXX:make_key: salt={hexlify(salt)}") logger.debug(f"XXX:make_key: key={hexlify(key)}") assert len(key) == int(key_length / 8) return key, salt
def __init__(self, password, client=None, fsencoding=sys.getfilesystemencoding()): self._random = Cryptodome.Random.new() if client is None: client = Defaults.getDefault('TARDIS_CLIENT') self.client = client self.salt = hashlib.sha256(client).digest() keys = PBKDF2(password, self.salt, count=20000, dkLen=self._keysize * 2) # 2x256 bit keys self._keyKey = keys[0:self._keysize] # First 256 bit key self._tokenKey = keys[self._keysize:] # And the other one self._fsEncoding = fsencoding
def login(self): """ Executes a login into the web UI """ self._get_challenge_val() # Hash password with challenge_val sha256_full = SHA256.new() sha256_full.update( (self._login_challenge + ':' + self._password).encode('utf-8')) encrypted_password = sha256_full.hexdigest() # Hash only password sha256_passwort = SHA256.new() sha256_passwort.update(self._password.encode('utf-8')) sha256_loginpwd = sha256_passwort.hexdigest() # Get hashed derivedk self._derive_dk = binascii.hexlify( PBKDF2(sha256_loginpwd, self._login_challenge[:16].encode('utf-8'), 16, 1000)) # Finally login json_string = self._open_site( 'data/Login.json', { "csrf_token": "nulltoken", "showpw": 0, "password": encrypted_password, 'challengev': self._login_challenge }) json_object = self.string_to_json(json_string) # Check valid response for x in json_object: if x["vartype"] == "status": if x["varid"] == "login" and x["varvalue"] != "success": raise Exception("Failed to login") if x["varid"] == "status" and x["varvalue"] != "ok": raise Exception("Failed to login") # Set needed cookies self.set_cookie("derivedk", self._derive_dk.decode('utf-8'))
def __init__(self, pwd, nbits=256, force_wz_aes_version=None): if not pwd: raise RuntimeError('%s encryption requires a password.' % WZ_AES) if nbits not in (128, 192, 256): raise RuntimeError( "`nbits` must be one of 128, 192, 256. Got '%s'" % nbits) self.force_wz_aes_version = force_wz_aes_version salt_lengths = { 128: 8, 192: 12, 256: 16, } self.salt_length = salt_lengths[nbits] key_lengths = { 128: 16, 192: 24, 256: 32, } key_length = key_lengths[nbits] aes_strengths = { 128: 1, 192: 2, 256: 3, } self.aes_strength = aes_strengths[nbits] self.salt = Random.new().read(self.salt_length) pwd_verify_length = 2 dkLen = 2 * key_length + pwd_verify_length keymaterial = PBKDF2(pwd, self.salt, count=1000, dkLen=dkLen) self.encpwdverify = keymaterial[2 * key_length:] enckey = keymaterial[:key_length] self.encrypter = AES.new(enckey, AES.MODE_CTR, counter=Counter.new(nbits=128, little_endian=True)) encmac_key = keymaterial[key_length:2 * key_length] self.hmac = HMAC.new(encmac_key, digestmod=SHA1Hash())
def _decrypt_aes_256_cbc_pbkdf2(encrypted_pkg: bytes, encryption_key: str) -> AgentRawData: SALT_LENGTH = 8 KEY_LENGTH = 32 IV_LENGTH = 16 PBKDF2_CYCLES = 100_000 # Adapt OpenSSL handling of salt, key and iv salt = encrypted_pkg[:SALT_LENGTH] raw_key = PBKDF2(encryption_key, salt, KEY_LENGTH + IV_LENGTH, count=PBKDF2_CYCLES, hmac_hash_module=SHA256) key, iv = raw_key[:KEY_LENGTH], raw_key[KEY_LENGTH:] decryption_suite = AES.new(key, AES.MODE_CBC, iv) decrypted_pkg = decryption_suite.decrypt(encrypted_pkg[SALT_LENGTH:]) # Strip of fill bytes of openssl return AgentRawData(decrypted_pkg[0:-decrypted_pkg[-1]])
def Main(): print("\n\n") mpw = input("Enter Master Password: "******"No password database, creating....") newDict = dictToBytes({"": ""}) encrypt(newDict, k) # check usage if len(sys.argv) != 2: print("usage: python pwMan.py <website>") return else: # decrypt passwords file to dictionary try: print("Loading database...") pws = decrypt(k) pws = bytesToDict(pws) except Exception as e: print("Wrong password") return # print value for website or add new value entry = sys.argv[1] if entry in pws: print("entry : " + str(entry)) print("password: "******"No entry for " + str(entry) + ", creating new...") newPass = input("New entry - enter password for " + entry + ": ") pws[entry] = newPass encrypt(dictToBytes(pws), k) print("stored")