def unlockWithPassphrase(self, passphrase): passphrase_round1 = pbkdf2_hmac('sha256', passphrase, self.attrs[b"DPSL"], self.attrs[b"DPIC"], 32) passphrase_key = pbkdf2_hmac('sha1', passphrase_round1, self.attrs[b"SALT"], self.attrs[b"ITER"], 32) for classkey in self.classKeys.values(): if b"WPKY" not in classkey: continue if classkey[b"WRAP"] & _WRAP_PASSPHRASE: k = _AESUnwrap(passphrase_key, classkey[b"WPKY"]) if not k: return False classkey[b"KEY"] = k return True
def try_password(password, iosFlag, dpsl, dpic, salt, iter, kb): if iosFlag: password = pbkdf2_hmac('sha256', password, dpsl, dpic, 32) code = pbkdf2_hmac('sha1', password, salt, iter, 32) for classkey in kb.classKeys.values(): k = classkey["WPKY"] if classkey["WRAP"] & WRAP_PASSCODE: k = AESUnwrap(code, classkey["WPKY"]) if not k: break if classkey["WRAP"] & WRAP_DEVICE: if not kb.deviceKey: continue k = AESdecryptCBC(k, kb.deviceKey) else: return password
def GenerateMHT(leavess): global keyPair global mt global RootSigFile global salts global lvs global Iter root_hash = [] root_signature = [] SaltedHashes = [] tmplvs = [] for x in lvs: salt = os.urandom(64) w = pbkdf2_hmac('sha256', x.encode(), salt, Iter) w = w.hex() tmplvs.append(w) salts.append(salt) mt.add_leaf(tmplvs) mt.make_tree() root = mt.get_merkle_root() root_hash.append(int.from_bytes(sha256((str(root).encode())).digest(), byteorder='big')) print("root_hash",root_hash) root_signature.append(pow(root_hash[0], keyPair.d, keyPair.n)) print("root_signature", root_signature) SaveRootSignature(RootSigFile, root_signature)
def pbkdf2(password, salt, iterations, dklen=0, digest=None): if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
def get_description_key(user_token, salt, account_name): m = sha512() m.update(account_name.encode('utf-8')) m.update(user_token.encode('utf-8')) account_id = m.digest() key = pbkdf2_hmac('sha256', account_id, salt.encode('utf-8'), 100000) return key
def hash_account_name(user_token, salt, account_name): m = sha512() m.update(user_token.encode('utf-8')) m.update(account_name.encode('utf-8')) account_id = m.digest() return b64encode( pbkdf2_hmac('sha256', account_id, salt.encode('utf-8'), 100000)).decode('utf-8')
def encode(self, password, salt, iterations=None): assert password assert salt and '$' not in salt if not iterations: iterations = self.iterations hash = pbkdf2_hmac(self.digest, force_bytes(password), force_bytes(salt), iterations) hash = hash.encode('base64').strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
def generate(self, value): """Takes a source value and produces a key and public helper This method should be used once at enrollment. Note that the "public helper" is actually a tuple. This whole tuple should be passed as the helpers argument to reproduce(). :param value: the value to generate a key and public helper for. :rtype: (key, helper) """ if isinstance(value, (bytes, str)): value = np.fromstring(value, dtype=np.uint8) key = np.fromstring(urandom(self.length), dtype=np.uint8) key_pad = np.concatenate((key, np.zeros(self.sec_len, dtype=np.uint8))) nonces = np.zeros((self.num_helpers, self.nonce_len), dtype=np.uint8) masks = np.zeros((self.num_helpers, self.length), dtype=np.uint8) digests = np.zeros((self.num_helpers, self.cipher_len), dtype=np.uint8) for helper in range(self.num_helpers): nonces[helper] = np.fromstring(urandom(self.nonce_len), dtype=np.uint8) masks[helper] = np.fromstring(urandom(self.length), dtype=np.uint8) # By masking the value with random masks, we adjust the probability that given # another noisy reading of the same source, enough bits will match for the new # reading & mask to equal the old reading & mask. vectors = np.bitwise_and(masks, value) # The "digital locker" is a simple cyrpto primitive made by hashing a "key" # xor a "value". The only efficient way to get the value back is to know # the key, which can then be hashed again xor the ciphertext. This is referred # to as locking and unlocking the digital locker, respectively. for helper in range(self.num_helpers): d_vector = vectors[helper].tobytes() d_nonce = nonces[helper].tobytes() digest = pbkdf2_hmac(self.hash_func, d_vector, d_nonce, 1, self.cipher_len) digests[helper] = np.fromstring(digest, dtype=np.uint8) ciphers = np.bitwise_xor(digests, key_pad) return (key.tobytes(), (ciphers, masks, nonces))
def build_key_from_password(password): ''' the password need to have high entropy, meaning difficult to predict. For added #security, i add a "salt", which increases the entropy. In this code, i use the RNG to produce the salt that we used to produce 32 bytes key. And key is build using pbkdf2 with sha512,8 bytes salt ''' #salt 8 byte size salt = b'gshadhin' iterations = 10000 # Stands for "Password-based key derivation function 2" hash_bin = pbkdf2_hmac('sha256', password.encode('utf-8'), salt, iterations, 16) key = binascii.hexlify(hash_bin) return key
def reproduce(self, value, helpers): """Takes a source value and a public helper and produces a key Given a helper value that matches and a source value that is close to those produced by generate, the same key will be produced. :param value: the value to reproduce a key for. :param helpers: the previously generated public helper. :rtype: key or None """ if isinstance(value, (bytes, str)): value = np.fromstring(value, dtype=np.uint8) if self.length != len(value): raise ValueError( 'Cannot reproduce key for value of different length') ciphers = helpers[0] masks = helpers[1] nonces = helpers[2] vectors = np.bitwise_and(masks, value) digests = np.zeros((self.num_helpers, self.cipher_len), dtype=np.uint8) for helper in range(self.num_helpers): d_vector = vectors[helper].tobytes() d_nonce = nonces[helper].tobytes() digest = pbkdf2_hmac(self.hash_func, d_vector, d_nonce, 1, self.cipher_len) digests[helper] = np.fromstring(digest, dtype=np.uint8) plains = np.bitwise_xor(digests, ciphers) # When the key was stored in the digital lockers, extra null bytes were added # onto the end, which makes it each to detect if we've successfully unlocked # the locker. checks = np.sum(plains[:, -self.sec_len:], axis=1) for check in range(self.num_helpers): if checks[check] == 0: return plains[check, :-self.sec_len].tobytes() return None
def validate_proof(proof, target_hash, merkle_root): global lvs global Iter merkle_root = bytearray.fromhex(merkle_root) th = int(target_hash) target_hash = pbkdf2_hmac('sha256', lvs[target_hash].encode(), salts[target_hash], Iter) target_hash = target_hash.hex() target_hash = bytearray.fromhex(target_hash) if len(proof) == 0: return target_hash == merkle_root else: proof_hash = target_hash for p in proof: try: # the sibling is a left node sibling = bytearray.fromhex(p['left']) proof_hash = hash_function(sibling + proof_hash).digest() except: # the sibling is a right node sibling = bytearray.fromhex(p['right']) proof_hash = hash_function(proof_hash + sibling).digest() #print(proof_hash == merkle_root) return proof_hash == merkle_root
def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length)) == derived_key
def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1)
def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key
def hash_user_token_with_salt(user_token, salt): return b64encode( pbkdf2_hmac('sha256', user_token.encode('utf-8'), salt.encode('utf-8'), 100000)).decode('utf-8')