def read_header_contents(header_str, password):
	key_amount = int(header_str[0:4],16)
	pbkdf2_iterations = int(header_str[4:8],16)
	pbkdf2_real_iters = pbkdf2_iterations * 1000
	#print('key amount:',key_amount)
	#print('pbkdf2 iters:',pbkdf2_real_iters)
	hmac_in_hdr = header_str[-128:]
	#print(header_str[4:132])
	k_pbkdf_hmac = hashlib.pbkdf2_hmac('sha512', password.encode(), bytes.fromhex(header_str[8:136]), pbkdf2_real_iters*4)
	hmac_val = hmac.new(k_pbkdf_hmac, header_str[:-128].encode(), hashlib.sha512).hexdigest()
	if hmac_in_hdr == hmac_val:
		hmac_validated = True
	else:
		hmac_validated = False
	#print('read hmac:',hmac_in_hdr)
	#print('calculated hmac:', hmac_val)
	final_key = []
	for i in range(0,key_amount):
		cs = header_str[(i*256)+8:(i*256)+136]
		#print('salt:',cs)
		ck = header_str[(i*256)+136:(i*256)+264]
		#print(hashlib.pbkdf2_hmac('sha512', password.encode(), bytes.fromhex(cs), 10000))
		k_xor_mask = bytes.decode(binascii.hexlify(hashlib.pbkdf2_hmac('sha512', password.encode(), bytes.fromhex(cs), pbkdf2_real_iters)))
		deciphered_key = do_xor_on_hex(k_xor_mask,ck)
		final_key.append(deciphered_key)
	ver = header_str[(key_amount*256)+8:(key_amount*256)+10]
	length = header_str[(key_amount*256)+10:-128]
	#print('version:',ver)
	#print('length:',length)
	fk = "".join(final_key)
	#print('key:', fk)
	return fk, ver, length, hmac_validated
def traiterFormExploitant(myexploitantid, nom=0, email=0, choix=0, admin_password=0, password=0, password_confirm=0, login=0, tel=0 ):
    myexploitantid = int(myexploitantid)
    admin = exploitantfile.Exploitant(0)
    myexploitant = exploitantfile.Exploitant(myexploitantid)
    if binascii.hexlify(hashlib.pbkdf2_hmac('sha256', bytes(admin_password, 'utf-8'), bytes(admin.salt, 'utf-8'), 100000)).decode() == admin.password:
        if choix == "parcelle":
            return modif_parcelles(myexploitant)
        elif choix == "cancel":
            return index(error="Modifications annulées")
        else:
            if not nom: nom = myexploitant.nom
            if not tel: tel = myexploitant.tel
            if not login: login = myexploitant.login
            if not password:
                password = myexploitant.password
            elif password != password_confirm:
                return index('mots de passe différents !')
            else:
                salt = uuid.uuid4().hex
                password = binascii.hexlify(hashlib.pbkdf2_hmac('sha256',bytes(password, 'utf-8'), bytes(salt, 'utf-8'), 100000)).decode()
            if not email: email = myexploitant.mail
            myexploitant.login = login
            myexploitant.mail = email
            myexploitant.nom = nom
            myexploitant.password = password
            myexploitant.tel = tel
            if myexploitantid == -1:
                salt = uuid.uuid4().hex
                myexploitant.salt = salt
                myexploitant.save()
            else:
                myexploitant.update()
            return index('Exploitant mis à jour')
    else:
        return index(error="Mot de passe administrateur incorrect")
示例#3
0
    def test_user_info(self):
        with self.client as c:
            account_data = self.real_user.id
            url = url_for('userinfoview', account_data=account_data)
            # Unauthenticated should return 401
            r = c.get(url)
            self.assertStatus(r, 401)

            client = self._create_client('priviledged_client_id', self.real_user.id, scopes='adsws:internal')
            token = self._create_token('priviledged_client_id', self.real_user.id, scopes='adsws:internal')

            user_id = self.real_user.id
            client_id = client.client_id
            expected_hashed_user_id = binascii.hexlify(hashlib.pbkdf2_hmac('sha256', str(user_id), current_app.secret_key, 10, dklen=32)) if user_id else None
            expected_hashed_client_id = binascii.hexlify(hashlib.pbkdf2_hmac('sha256', str(client_id), current_app.secret_key, 10, dklen=32)) if client_id else None

            # Authenticated requests (using a client that has the required scope)
            # and using an 1) user id
            headers={'Authorization': 'Bearer:{}'.format(token.access_token)}
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            self.assertEqual(r.json['hashed_user_id'], expected_hashed_user_id)
            self.assertEqual(r.json['hashed_client_id'], expected_hashed_client_id)
            self.assertFalse(r.json['anonymous'])
            self.assertEqual(r.json['source'], 'user_id')
            expected_json = r.json

            # 2) access token
            account_data = token.access_token
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'access_token'
            self.assertEqual(r.json, expected_json)

            # 3) client id
            account_data = client.client_id
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'client_id'
            self.assertEqual(r.json, expected_json)

            # 4) session
            #
            # Encode first a session cookie using the current app secret:
            sscsi = SecureCookieSessionInterface()
            signingSerializer = sscsi.get_signing_serializer(current_app)
            session = signingSerializer.dumps({'_id': 'session_id', 'oauth_client': client.client_id})

            account_data = session
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'session:client_id'
            self.assertEqual(r.json, expected_json)
示例#4
0
    def deriveKeysFromUser(self, sid, password):
        # Will generate two keys, one with SHA1 and another with MD4
        key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
        # For Protected users
        tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)
        tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
        key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'), SHA1).digest()[:20]

        return key1, key2, key3
def change_password(filename,password_old,password_new):
	nfname = filename + '.header'
	try:
		nf = open(nfname,'r')
		header_str = nf.read()
		nf.close()
	except FileNotFoundError:
		print("Header is missing!")
		time.sleep(3)
		return "F"
	key_amount = int(header_str[0:4],16)
	pbkdf2_iterations = int(header_str[4:8],16)
	pbkdf2_real_iters = pbkdf2_iterations * 1000
	hmac_in_hdr = header_str[-128:]
	k_pbkdf_hmac = hashlib.pbkdf2_hmac('sha512', password_old.encode(), bytes.fromhex(header_str[8:136]), pbkdf2_real_iters*4)
	hmac_val = hmac.new(k_pbkdf_hmac, header_str[:-128].encode(), hashlib.sha512).hexdigest()
	if hmac_in_hdr != hmac_val:
		hmac_validated = False
		print('Wrong password, or corrupted/tampered header')
		print('If you continue, damage could be irreversible')
		x = input('Press Y to continue, other key to quit ')
		if (x != 'Y') and (x != 'y'):
			return "F"
	else:
		hmac_validated = True
	print('read hmac:',hmac_in_hdr)
	print('calculated hmac:', hmac_val)
	new_header = []
	new_header.append(header_str[0:8])
	for i in range(0,key_amount):
		cs = header_str[(i*256)+8:(i*256)+136]
		ck = header_str[(i*256)+136:(i*256)+264]
		k_xor_mask_d = bytes.decode(binascii.hexlify(hashlib.pbkdf2_hmac('sha512', password_old.encode(), bytes.fromhex(cs), pbkdf2_real_iters)))
		deciphered_key = do_xor_on_hex(k_xor_mask_d,ck)
		k_xor_mask_e = bytes.decode(binascii.hexlify(hashlib.pbkdf2_hmac('sha512', password_new.encode(), bytes.fromhex(cs), pbkdf2_real_iters)))
		reciphered_key = do_xor_on_hex(k_xor_mask_e,deciphered_key)
		new_header.append(cs)
		new_header.append(reciphered_key)
	ver = header_str[(key_amount*256)+8:(key_amount*256)+10]
	length = header_str[(key_amount*256)+10:-128]
	new_header.append(ver)
	new_header.append(length)
	f_header = "".join(new_header)
	k_pbkdf_hmac_n = hashlib.pbkdf2_hmac('sha512', password_new.encode(), bytes.fromhex(f_header[8:136]), pbkdf2_real_iters*4)
	hmac_val_n = hmac.new(k_pbkdf_hmac_n, f_header.encode(), hashlib.sha512).hexdigest()
	nh = []
	nh.append(f_header)
	nh.append(hmac_val_n)
	finalr_head = "".join(nh)
	finalf = open(nfname,'w')
	finalf.write(finalr_head)
	finalf.close()
	print('Done!')
示例#6
0
def key_derive(salt, password, salt_mask, key_sz, key_iter, hmac_key_sz, hmac_key_iter):
    """Derive an encryption key for page encryption/decryption, an key for hmac generation"""
    key = hashlib.pbkdf2_hmac('sha1', password, salt, key_iter, key_sz)

    try:
        hmac_salt = bytearray([x ^ salt_mask for x in salt])
        hmac_key = hashlib.pbkdf2_hmac('sha1', key, hmac_salt, hmac_key_iter, hmac_key_sz)
    except TypeError:   # python2
        hmac_salt = b''
        for x in salt:
            hmac_salt += chr(ord(x) ^ salt_mask)
        hmac_key = hashlib.pbkdf2_hmac('sha1', str(key), hmac_salt, hmac_key_iter, hmac_key_sz)
    return key, hmac_key
示例#7
0
文件: users.py 项目: jennyb/piSpecMon
 def check_user(self, username, password):
     """ Check the given password guess against salt and hash. Returns user
         data if successful, or raises IncorrectPasswordError if unsuccessful.
     """
     username = unicode(username)
     password = unicode(password)
     self._validate_username(username)
     for user in self._iter_users():
         if user.name == username:
             hash_value = pbkdf2_hmac('sha256', password, user.salt, self.rounds)
             if hash_value == user.hash:
                 return user.data
     # fake attempt so hackers can't guess validity of usernames by time taken
     pbkdf2_hmac('sha256', password, b'foo', self.rounds)
     raise IncorrectPasswordError()
示例#8
0
def pbkdf2_hmac_sha512(password, salt):
    password, salt = from_str_to_bytes(password), from_str_to_bytes(salt)
    if hasattr(hashlib, 'pbkdf2_hmac'):
        b = hashlib.pbkdf2_hmac('sha512', password, salt, 2048, 64)
    else:
        b = bin_pbkdf2_hmac('sha512', password, salt, 2048, 64)
    return safe_hexlify(b)
 def test_uploader_metadata_incorrect_key(
         self, app, user, project_public,
         draft_registration_prereg,
         payload, url_draft_registrations):
     sha256 = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
     payload['data']['attributes']['registration_metadata']['q7'] = {
         'value': {
             'uploader': {
                 'value': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                 'extra': [{
                     'data': {},
                     'nodeId': project_public._id,
                     'viewUrl': '/project/{}/files/osfstorage/{}'.format(project_public._id, draft_registration_prereg._id),
                     'selectedFileNames': 'Screen Shot 2016-03-30 at 7.02.05 PM.png',
                     'sha256': binascii.hexlify(sha256)
                 }]
             }
         }
     }
     res = app.put_json_api(
         url_draft_registrations,
         payload, auth=user.auth,
         expect_errors=True)
     assert res.status_code == 400
     assert res.json['errors'][0][
         'detail'] == 'Additional properties are not allowed (u\'selectedFileNames\' was unexpected)'
 def hash_password(self, password: str, for_storage: bool = False) -> bytes:
     """Encode a password."""
     hashed = hashlib.pbkdf2_hmac(
         'sha512', password.encode(), self._data['salt'].encode(), 100000)
     if for_storage:
         hashed = base64.b64encode(hashed)
     return hashed
    def generate(self, master_password, domain, username='', length=10, iterations=4096):
        """
        This method does all the work. It calculates a password with PBKDF2 and convert_bytes_to_password.
        4096 iterations will give you a password in ~0.04s. If you have a fast computer you can increase this
        to make it harder to hack your masterpassword.

        :param master_password:
        :type master_password: str
        :param domain:
        :type domain: str
        :param username:
        :type username: str
        :param length:
        :type length: int
        :param iterations:
        :type iterations: int
        :return: a password
        :rtype: str
        """
        if len(self.password_characters) > 0:
            hash_string = domain + username + master_password
            hashed_bytes = pbkdf2_hmac('sha512', hash_string.encode('utf-8'), self.salt, iterations)
            return self.convert_bytes_to_password(hashed_bytes, length)
        else:
            print('Für das Passwort stehen keine Zeichen zur Verfügung. Sie sollten die Einstellungen ändern.')
            return ''
示例#12
0
 def POST(self):
     login = forms.Login(action='/login', _class='form-signin')
     login.data = self.request.post
     if login.is_valid():
         db = self.container.get('db')
         try:
             user = db.query(User).filter(User.name == login.username).one()
         except sqlalchemy.orm.exc.NoResultFound:
             self.flash_messages.add('Tu nombre de usuarion no esta registrado', namespace='danger')
             return {'form': login}
         print(user.password)
         dk = hashlib.pbkdf2_hmac('sha256', login.password.encode(), user.salt.encode(), 100000)
         password = binascii.hexlify(dk)
         print(password, user.password)
         if password == user.password.encode():
             print('Saving', self.request.session)
             self.request.session['logged'] = True
             self.flash_messages.add('Bienvenido!')
             self.redirect('index')
         else:
             self.flash_messages.add('El usuario y contraseña prorcionados no coinciden')
     else:
         for field in login.errors.keys():
             for ms in login.errors[field]['messages']:
                 self.flash_messages.add('{} {}'.format(field, ms))
         #self.redirect('login')
     return {'form': login}
示例#13
0
def bip39_to_seed(mnemonic, passphrase):
    import hashlib, hmac
    PBKDF2_ROUNDS = 2048
    mnemonic = normalize('NFKD', ' '.join(mnemonic.split()))
    passphrase = bip39_normalize_passphrase(passphrase)
    return hashlib.pbkdf2_hmac('sha512', mnemonic.encode('utf-8'),
        b'mnemonic' + passphrase.encode('utf-8'), iterations = PBKDF2_ROUNDS)
示例#14
0
文件: scram.py 项目: jesopo/bitbot
    def server_first(self, data: bytes) -> bytes:
        self.state = SCRAMState.ClientFinal

        pieces = self._get_pieces(data)
        nonce = pieces[b"r"] # server combines your nonce with it's own
        salt = base64.b64decode(pieces[b"s"]) # salt is b64encoded
        iterations = int(pieces[b"i"])

        salted_password = hashlib.pbkdf2_hmac(self._algo, self._password,
            salt, iterations, dklen=None)
        self._salted_password = salted_password

        client_key = self._hmac(salted_password, b"Client Key")
        stored_key = self._hash(client_key)

        channel = base64.b64encode(b"n,,")
        auth_noproof = b"c=%s,r=%s" % (channel, nonce)
        auth_message = b"%s,%s,%s" % (self._client_first, data, auth_noproof)
        self._auth_message = auth_message

        client_signature = self._hmac(stored_key, auth_message)
        client_proof_xor = _scram_xor(client_key, client_signature)
        client_proof = base64.b64encode(client_proof_xor)

        # c=<b64encode("n,,")>,r=<nonce>,p=<proof>
        return b"%s,p=%s" % (auth_noproof, client_proof)
示例#15
0
def main():
    """ Entry point """
    parser = argparse.ArgumentParser(
        description="Tool to add new user to database")
    parser.add_argument("login", help="user login")
    parser.add_argument("password", help="user password")
    parser.add_argument("id", type=int, help="user ID")
    args = parser.parse_args()
    mongo = MongoClient(
        ["mongo1", "mongo2", "mongo3"],
        replicaSet="rs0",
        read_preference=ReadPreference.PRIMARY_PREFERRED,
        readConcernLevel="majority",
        w=2, wtimeout=3000, j=True
    )
    user = mongo["shiva"]["users"].find_one({"login": args.login})
    if user is not None:
        print "User {} already exists!".format(args.login)
        return
    salt = os.urandom(64)
    dkey = hashlib.pbkdf2_hmac("sha512", args.password, salt, 100000)
    mongo["shiva"]["users"].insert_one({
        "login": args.login,
        "password": binascii.hexlify(dkey),
        "salt": binascii.hexlify(salt),
        "id": args.id
    })
    print "Added {}".format(args.login)
示例#16
0
文件: db.py 项目: geokala/k-voter
 def hash_password(self, password):
     return hashlib.pbkdf2_hmac(
         hash_name='sha256',
         password=bytes(password, 'utf8'),
         salt=self.salt,
         iterations=100000,
     )
示例#17
0
def do_auth():
    devs = u2f.list_devices()
    db = json.load(open('data.json'))

    keyhandle = websafe_decode(db['keyhandle'])
    salt = websafe_decode(db['salt'])
    hkey = websafe_decode(db['hkey'])

    req = make_auth_request(keyhandle)

    result = authenticate.authenticate(devs, req, OUR_APPID, check_only = False)

    authData = decode_auth_response(websafe_decode(result['signatureData']))

    open('sig.der', 'w').write(authData.sig)

    # decode our signature, and reconstruct the message that was signed
    sig = decode_sig(authData.sig)
    signed_message = H(req['appId']) + encode_auth_response_prefix(authData) + H(websafe_decode(result['clientData']))
    
    # recover the two possible public keys from the signature
    pubkeys = ecdsa.recover_candidate_pubkeys(ec.nistp256, hashlib.sha256, signed_message, sig)
    pubkeys = [ec.nistp256.ec2osp(pk) for pk in pubkeys]

    if H(pubkeys[0]) == hkey:
        pubkey = pubkeys[0]
    elif H(pubkeys[1]) == hkey:
        pubkey = pubkeys[1]
    else:
        print 'token is broken/lying/replayed!'
        sys.exit(1)

    key = hashlib.pbkdf2_hmac('sha256', pubkey + SOME_PASSWORD, salt, SOME_ITERATIONS)
    print 'secret is', key.encode('hex')
示例#18
0
def do_enroll():
    devs = u2f.list_devices()
    req = make_reg_request()
    result = register.register(devs, req, OUR_APPID)
    
    # check client data from token
    clientData = json.loads(websafe_decode(result['clientData']))

    assert clientData['origin'] == OUR_APPID
    assert clientData['challenge'] == req['challenge']
    assert clientData['typ'] == 'navigator.id.finishEnrollment'
   
    # check registration data
    regData = decode_reg_response(websafe_decode(result['registrationData']))

    salt = os.urandom(32)

    with open('data.json', 'w') as f:
        db = dict(
            hkey = websafe_encode(H(regData.pubkey)),
            keyhandle = websafe_encode(regData.keyhandle),
            salt = websafe_encode(salt)
        )
        json.dump(db, f)
        print 'written data to', f.name

    key = hashlib.pbkdf2_hmac('sha256', regData.pubkey + SOME_PASSWORD, salt, SOME_ITERATIONS)
    print 'secret is', key.encode('hex')
示例#19
0
def addUser(name, passw, conn, realName = None, email = None):
  if realName is None:
    realName = name

  c = conn.execute('select null from user where usrnam=?', (name,))
  if c.fetchone():
    raise UserExistsException('A user with username "{0}" is already registered'.format(name))

  
  c = conn.execute('select cryptid, hashfunc, rounds, saltbytes from crypto order by isdefault desc')
  
  hash = b''
  
  while hash == b'':
    row = c.fetchone()
    if not row:
      raise DataError('Failed to select default crypto settings')
  
    cryptid = row[0]
    hashfunc = row[1]
    rounds = row[2]
    saltbytes = row[3]

    salt = os.urandom(saltbytes)

    try:
      hash = hashlib.pbkdf2_hmac(hashfunc, passw.encode('UTF-8'), salt, rounds)
    except ValueError:
      hash = b''

  conn.execute('insert into user values(null, ?, ?, ?, ?, ?, ?)', (name,realName, hash, salt, email, cryptid));
  dbCommit()

  return userid
    def verify_access_token(dbsession, encoded_token):
        try:
            decoded_token = b64decode(encoded_token)
        except TypeError:
            return None

        username, submitted_access_token = decoded_token.split(':')

        try:
            known_access_token_instance = dbsession.query(AccessToken) \
                                                   .join(User) \
                                                   .filter(
                User.username==username.decode('utf-8')
            ).one()
        except NoResultFound:
            return None

        decoded_known_hash = b64decode(
            known_access_token_instance.token_hash[:-salt_length]
                                       .encode('utf-8')
        )
        salt = known_access_token_instance.token_hash[-salt_length:] \
                                          .encode('utf-8')

        submitted_hash = pbkdf2_hmac(
            'sha256',
            submitted_access_token,
            salt,
            100000
        )

        if submitted_hash == decoded_known_hash:
            return known_access_token_instance.user.id

        return None
示例#21
0
def decrypt_file(passwd, filename):
	assert isinstance(passwd, bytes)
	assert os.path.isfile(filename)

	with open(filename, 'rb') as ciphertext_file, open(filename + '.tmp', 'wb') as plaintext_file:
		# derive AES key from password and salt
		salt = ciphertext_file.read(32)
		aes_key = hashlib.pbkdf2_hmac('sha512', passwd, salt, 200000, dklen=32)

		# verify derived AES key is the same as the one used to encrypt the file
		if hashlib.sha512(aes_key).digest() == ciphertext_file.read(64):
			# decrypt file
			aes_cipher = AES.new(aes_key, mode=AES.MODE_CTR, counter=Counter.new(128))

			while True:
				# decrypt ciphertext 10 MiB at a time
				ciphertext = ciphertext_file.read(10485760)

				if len(ciphertext) == 0:
					break

				plaintext_file.write(aes_cipher.decrypt(ciphertext))
		else:
			os.remove(filename + '.tmp')
			raise HashMismatch('\nThe decryption AES key hash does not match the one in the encrypted file.\nPossible causes: 0. file is not encrypted 1. password is incorrect.')

	os.rename(filename + '.tmp', filename)
示例#22
0
 def derive_pbkdf2(self, password):
     """Derive an encryption key from the provided password."""
     from hashlib import pbkdf2_hmac
     from pskc.exceptions import KeyDerivationError
     prf = 'sha1'
     if self.pbkdf2_prf:
         match = re.search(
             r'^(.*#)?hmac-(?P<hash>[a-z0-9-]+)$', self.pbkdf2_prf)
         if match:
             prf = match.group('hash')
         else:
             raise KeyDerivationError(
                 'Unsupported PRF: %r' % self.pbkdf2_prf)
     if not all((password, self.pbkdf2_salt, self.pbkdf2_key_length,
                 self.pbkdf2_iterations)):
         raise KeyDerivationError('Incomplete PBKDF2 configuration')
     # force conversion to bytestring on Python 3
     if not isinstance(password, type(b'')):
         password = password.encode()  # pragma: no cover (Py3 specific)
     try:
         return pbkdf2_hmac(
             prf, password, self.pbkdf2_salt, self.pbkdf2_iterations,
             self.pbkdf2_key_length)
     except ValueError:
         raise KeyDerivationError(
             'Pseudorandom function unsupported: %r' % self.pbkdf2_prf)
def edit_header_file(oldpassword, newpassword, fname):
    headername = str(fname) + ".header"
    headerfile = open(headername, "rb")
    totalheader = headerfile.read()
    headerfile.close()
    newheadercontents = ""
    header_salt = totalheader[0:32]
    header_encrypted_key = totalheader[32:160]
    header_master_key = do_xor_on_hex(binascii.hexlify(hashlib.pbkdf2_hmac('sha512', oldpassword, header_salt, 100000)), header_encrypted_key)
    header_new_encrypted_key = do_xor_on_hex(binascii.hexlify(hashlib.pbkdf2_hmac('sha512', newpassword, header_salt, 100000)), header_master_key)
    header_length = totalheader[160:]
    newheadercontents = header_salt + header_new_encrypted_key + header_length
    headerfile = open(headername, "wb")
    headerfile.write(newheadercontents)
    headerfile.close()
    return "Done"
    def check_permission(self, password, username):
        # get hash of name
        dk = hashlib.pbkdf2_hmac("sha256", bytearray(username, "utf8"), b"salt", 100000)
        username_hashed = binascii.hexlify(dk).decode("ascii")

        # get hash password from database
        return login.get_hash_login(username_hashed, password)
示例#25
0
def hashPassword(passwd):
    salt = os.urandom(64)
    md5sum = hashlib.md5()
    md5sum.update(passwd)
    hashkey = md5sum.hexdigest().encode() #string to binary
    dk = hashlib.pbkdf2_hmac('sha256',hashkey,salt,10000,256)
    return salt + dk
示例#26
0
文件: db.py 项目: raylu/outlauth
	def hash_pw(password, salt=None):
		if salt is None:
			salt = os.urandom(16)
		hashed = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
		hashed_hex = binascii.hexlify(hashed).decode()
		salt_hex = binascii.hexlify(salt).decode()
		return hashed_hex, salt_hex
def validateUser(session, user):
    userFromDB = findUserByName(session, user.name)
    user.password = unicode(hashlib.pbkdf2_hmac('sha256', user.password, userFromDB.salt, 100000), 'unicode-escape')
    if (userFromDB != None and user.password == userFromDB.password):
        return userFromDB
    else:
        return None
示例#28
0
    def test_save_send_out_request(self):
        assoc_service = AssociatedService(client=self.oidc_client, enabled=True)
        assoc_service.save()

        test_client = Client()
        message = 'Long message' * 50
        dk = hashlib.pbkdf2_hmac('sha256', message, self.client_secret, 100000)
        check_sum_verification = base64.b64encode(dk).decode()  # py3k-mode

        response = test_client.post(reverse('api_simple_sendout'), {
            'client_id': '1337',
            'message_text': message,
            'check_sum': check_sum_verification
        })

        self.assertEquals(202, response.status_code)
        self.assertEquals(response.json()['job_id'], 1)
        self.assertEquals(response.json()['job_description'],
                          'The message was accepted and wil be checked. Once released it will be send to the desired group of users')
        self.assertIn('job_created', response.json())

        job_id = response.json()['job_id']

        sccr = SimpleClientCommunicationRequest.objects.get(id=job_id)
        self.assertEquals(sccr.client, self.oidc_client)
        self.assertTrue(sccr.pending)
示例#29
0
def encrypt_file(passwd, filename):
	assert isinstance(passwd, bytes)
	assert os.path.isfile(filename)

	with open(filename, 'rb') as plaintext_file, open(filename + '.tmp', 'wb') as ciphertext_file:
		# derive AES key from password and salt
		salt = os.urandom(32)
		aes_key = hashlib.pbkdf2_hmac('sha512', passwd, salt, 200000, dklen=32)

		# save salt used to derive AES key and hash of AES key (see decrypt_file())
		ciphertext_file.write(salt + hashlib.sha512(aes_key).digest())

		# encrypt file
		aes_cipher = AES.new(aes_key, mode=AES.MODE_CTR, counter=Counter.new(128))

		while True:
			# encrypt plaintext 10 MiB at a time
			plaintext = plaintext_file.read(10485760)

			if len(plaintext) == 0:
				break

			ciphertext_file.write(aes_cipher.encrypt(plaintext))

	os.rename(filename + '.tmp', filename)
示例#30
0
文件: dao.py 项目: garsh0p/garpr
def gen_password(password):
    # more bytes of randomness? i think 16 bytes is sufficient for a salt
    salt = base64.b64encode(os.urandom(16))
    hashed_password = base64.b64encode(hashlib.pbkdf2_hmac(
        'sha256', password, salt, ITERATION_COUNT))

    return salt, hashed_password
def mnemonic_to_bip39seed(mnemonic: str, passphrase: str = "") -> bytes:
    """ BIP39 seed from a mnemonic key.
        Logic adapted from https://github.com/trezor/python-mnemonic. """
    mnemonic = bytes(mnemonic, 'utf8')
    salt = bytes(BIP39_SALT_MODIFIER + passphrase, 'utf8')
    return hashlib.pbkdf2_hmac('sha512', mnemonic, salt, BIP39_PBKDF2_ROUNDS)
示例#32
0
import hashlib
import secrets

# password.encode() will convert the password to bytes
password = input()
byte_password = password.encode()
salt = secrets.token_bytes(32)

# hashed = hashlib.pbkdf2_hmac('algorithm', b'password', b'salt', number of iterations)
hashed = hashlib.pbkdf2_hmac('sha256', byte_password, salt, 64)
print('sha256: ', hashed)
print('salt: ', salt)
示例#33
0
def PBKDF2(password, salt, dklen, iterations=10000, hashfunc="sha512"):
    dk = pbkdf2_hmac(hashfunc, password, salt, iterations, dklen)
    return hexlify(dk)
def generate_key(password, salt):
    return base64.urlsafe_b64encode(
        pbkdf2_hmac('sha256', password, salt, 100000, 32))
示例#35
0
 def _get_chunk_hash(chunk):
     sha1_hash = hashlib.pbkdf2_hmac('sha1', chunk, '', 80)
     return binascii.hexlify(sha1_hash)
示例#36
0
def register():
    clear()
    print("Enter the following details to register: ")
    email = input("Email id: ")

    rowcount = 0

    with open('users.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            if row[0] == email:
                print("\n\nEmail already exists, please try again")
                time.sleep(2)
                register()
                return 0
            else:
                rowcount += 1

    name = input("Name: ")
    mobile = int(input("Mobile number (10 digits): "))
    pass1 = getpass.getpass(prompt="Password: "******"Confirm password: "******"\n\nPasswords do not match, please try again")
        time.sleep(2)
        register()
        return 0

    sex = input("Sex (M/F/N): ")

    city = input("City: ")

    print("1. Use default profile picture")
    print("2. Enter path of profile picture")
    c = int(input("Enter your choice: "))
    path = "profile_pictures/default.jpg"
    if c == 2:
        path = input("Enter path (only .jpg supported): ")
        shutil.copy(path,
                    "profile_pictures/" + name + "_" + str(rowcount) + ".jpg")
        path = "profile_pictures/" + name + "_" + str(rowcount) + ".jpg"

    salt = hashlib.sha256(os.urandom(32)).hexdigest().encode('ascii')
    pwdhash = hashlib.pbkdf2_hmac('sha256', pass1.encode('utf-8'), salt,
                                  100000)
    pwdhash = binascii.hexlify(pwdhash)
    storage = (salt + pwdhash).decode('ascii')

    f = open("users.csv", "a")
    f.write('"' + email + '"' + ',' + name + ',' + str(mobile) + ',')
    f.close()

    f = open("users.csv", "a")
    f.write(storage)
    f.close()

    f = open("users.csv", "a")
    f.write(',' + sex + ',' + city + ',' + path + ',' + str(rowcount) + '\n')
    f.close()

    login()
示例#37
0
def locker(file_path, password, remove=True, **kwargs):
    """Provides file locking/unlocking mechanism
    This function either encrypts or decrypts the file - *file_path*.
    Encryption or decryption depends upon the file's extension.
    The user's encryption or decryption task is almost automated since
    *encryption* or *decryption* is determined by the file's extension.

    :param file_path: File to be written on.
    :param password: Password to be used for encryption/decryption.
    :param remove: If set to True, the the file that is being
                   encrypted or decrypted will be removed.
                   (Default: True).
    :param kwargs:
                block_size = valid block size in int for reading files.
                ext = extension to be appended to the files.
                iterations = no. of iterations to derive the the key
                             from the password.
                algo = The PBKDF2 hashing algorithm to use.
                dklen = length of key after PBK derivation.
                metadata = associated metadata written to file.
                method = set method manually (`encrypt` or `decrypt`)
                new_file = set new file path to be written upon.
    :return: None
    """

    block_size = kwargs.get('block_size', 64 * 1024)
    ext = kwargs.get('ext', '.0DAY')
    iterations = kwargs.get('iterations', 50000)
    dklen = kwargs.get('dklen', 32)
    metadata = kwargs.get('metadata', b'Encrypted-using-Pycryptor')
    algo = kwargs.get('algo', 'sha512')
    _method = kwargs.get('method')
    _new_file = kwargs.get('new_file')

    # check for new-file's existence
    if _new_file is not None:
        if os.path.exists(_new_file):
            if os.path.samefile(file_path, _new_file):
                raise ValueError(f'Cannot process with the same file.')
            os.remove(_new_file)

    # check for method validity
    if _method is not None:
        if _method not in ['encrypt', 'decrypt']:
            raise ValueError(f'Invalid method: `{_method}`. '
                             'Method can be "encrypt" or "decrypt" only.')

    # use auto-functionality or `_method`.
    _auto_method = 'encrypt' if not file_path.endswith(ext) else 'decrypt'
    method = _method or _auto_method

    # The file is being decrypted.
    if method == 'decrypt':
        flag = False
        new_file = _new_file or os.path.splitext(file_path)[0]

        # Retrieve the *nonce* and *salt*.
        with open(file_path, 'rb') as file:
            check_metadata = file.read(len(metadata))
            if not check_metadata == metadata:
                raise RuntimeError("The file is not supported. "
                                   "The file might be tampered.")

            mac, nonce, salt = unpack('16s12s32s', file.read(16 + 12 + 32))

    # The file is being encrypted.
    else:
        flag = True
        new_file = _new_file or file_path + ext
        nonce = os.urandom(12)
        salt = os.urandom(32)
        mac = None

    # Create a *password_hash* and *cipher* with
    # required method.
    password_hash = hashlib.pbkdf2_hmac(algo, password, salt, iterations,
                                        dklen)
    cipher_obj = AES.new(password_hash, AES.MODE_GCM, nonce=nonce)
    crp = getattr(cipher_obj.update(metadata), method)

    _writer(file_path,
            new_file,
            crp,
            flag,
            nonce=nonce,
            mac_func=cipher_obj.digest,
            mac_val=mac,
            salt=salt,
            block_size=block_size,
            write_metadata=metadata)

    if not flag:
        try:
            cipher_obj.verify(mac)
        except ValueError:
            os.remove(new_file)
            raise DecryptionError('Invalid Password or tampered data.') \
                from None

    if remove:
        os.remove(file_path)
示例#38
0
文件: crypto.py 项目: zademn/IC2021
def hash_password(password: str):
    salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
    pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'),
                                  salt, 100000)  # 100k iterations
    pwdhash = binascii.hexlify(pwdhash)
    return (salt + pwdhash).decode('ascii')
示例#39
0
def get_salted_password_hash(password):
    salt = os.urandom(10)
    hashed = hashlib.pbkdf2_hmac('sha1', password.encode("utf-8"), salt,
                                 100000)

    return hashed.hex(), salt.hex()
示例#40
0
# !/usr/bin/env python3
# -*- coding:utf-8 -*-

# @Time    : 2019/12/9 19:30
# @Author  : Fangyang
# @Software: PyCharm

import secrets
import base64
import hashlib

if __name__ == '__main__':
    a = secrets.token_bytes(16)
    b = base64.urlsafe_b64encode(a)
    c = str(b, encoding='utf-8')
    salt = base64.b64encode(c.encode('utf-8'))

    sk = hashlib.pbkdf2_hmac(hash_name='sha1',
                             password='******'.encode('utf-8'),
                             salt=salt,
                             iterations=10000,
                             dklen=64)
    print(1)
示例#41
0
 def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None):
     hashfunc = hashfunc or sha1
     hmac = hashlib.pbkdf2_hmac(hashfunc().name, to_bytes(data),
                                to_bytes(salt), iterations, keylen)
     return binascii.hexlify(hmac)
示例#42
0
def hash_password(password):
    salt = SALT
    pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
    pwdhash = binascii.hexlify(pwdhash)
    return (salt + pwdhash).decode('ascii')
示例#43
0
def hash_password_plain(password):
    salt = hashlib.sha256(b"1").hexdigest().encode('ascii')
    pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt,
                                  numOfHashes)
    pwdhash = binascii.hexlify(pwdhash)
    return (pwdhash).decode('ascii')
示例#44
0
    def decrypter(self):

        # Uses the get_wrapped_keybag() function to get the wrapped keybag from the offsets defined in the
        # Conatiner Super Block
        # THIS IS STEP 1 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
        log.debug("Finding the Wrapped Keybag now")
        wrapped_container_keybag = self.get_wrapped_keybag(self.wrapped_keybag_offset, self.keylocker_block_count)

        # Decrypts the wrapped keybag
        # THIS IS STEP 2 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
        log.debug("Attempting to unwrap the Wrapped Keybag now")
        unwrapped_container_keybag = self.decrypt_keybag(wrapped_container_keybag, self.wrapped_keybag_offset, self.uuid)
        log.debug("Successfully unwrapped the Wrapped Keybag!")
        parsed_container_keybag = parse_vek_keybag(unwrapped_container_keybag)

        # Parses the unwrapped kb_locker object derived from the wrapped keybag into structures
        # THIS IS STEP 3 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
        log.debug("Parsing the unwrapped keybag now")
        wrapped_vek, vek_uuid, vek_enc_type = self.find_wrapped_vek(parsed_container_keybag)

        # Returns if no UUID is found
        if wrapped_vek is None:
            log.error("COULD NOT FIND MATCHING UUID IN KEYBAG (for obtaining wrapped VEK). VOLUME CANNOT BE DECRYPTED!!")
            return

        # Finds the volumes keybag by looking at the unwrapped containers keybag with a tag of KB_TAG_VOLUME_UNLOCK_RECORDS
        # THIS IS STEP 4 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
        volume_keybag_start_addr, volume_keybag_block_count, volume_uuid = self.find_volume_keybag_details(parsed_container_keybag)
        wrapped_volume_keybag = self.get_wrapped_keybag(volume_keybag_start_addr, volume_keybag_block_count)

        # Decrypts the wrapped volume keybag
        # THIS IS STEP 5 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
        unwrapped_volume_keybag = self.decrypt_keybag(wrapped_volume_keybag, volume_keybag_start_addr, volume_uuid)

        # Parses the unwrapped volume kb_locker object derived from the wrapped keybag into structures
        parsed_volume_keybag = parse_volume_keybag(unwrapped_volume_keybag)


        """
        Find an entry in the volumeʼs keybag whose UUID matches the userʼs Open Directory UUID and whose tag is
        KB_TAG_VOLUME_UNLOCK_RECORDS. The key data for that entry is the wrapped KEK for this volume.

        THIS IS STEP 6 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION (find 3)
        """

        user_password_key = b''

        # Try supplied password as a recovery key first
        log.debug("Trying as Personal Recovery key to decrypt")
        wrapped_kek, iterations, salt, kek_enc_type = self.get_wrapped_key_from_prk(parsed_volume_keybag)
        if wrapped_kek:
            user_password_key = hashlib.pbkdf2_hmac('sha256', self.password.encode(), salt, iterations, dklen=32)
            self.decryption_key = self.get_VEK_by_unwrapping_keys(user_password_key, wrapped_kek, wrapped_vek, vek_uuid, kek_enc_type, vek_enc_type)

        # Try password if recovery key failed above
        if self.decryption_key is None:
            log.debug("Trying as Password to decrypt")

            user_uuids = self.get_open_dir_uuid()
            if len(user_uuids) > 1:
                log.warning("There is more than one User Open Directory UUID. We will try for all users.")
            if len(user_uuids) == 0:
                log.error("There were no User Open Directory UUIDs found. Decryption cannot move forward")
                return

            for user, open_dir_uuid in user_uuids:
                log.info(f'Trying to decrypt encryption keys for user {user}')
                """
                Unwrap the KEK using the userʼs password, and then unwrap the VEK using the KEK, both according to the
                algorithm described in RFC 3394.

                THIS IS STEP 7 OF THE APFS ACCESSING ENCRYPTED OBJECTS DOCUMENTATION
                """
                wrapped_kek, iterations, salt, kek_enc_type = find_wrapped_kek_from_vol_keybag(parsed_volume_keybag, open_dir_uuid)
                if wrapped_kek:
                    log.debug(f'kek_enc_type = {kek_enc_type}, vek_enc_type = {vek_enc_type}')
                    user_password_key = hashlib.pbkdf2_hmac('sha256', self.password.encode(), salt, iterations, dklen=32)
                    self.decryption_key = self.get_VEK_by_unwrapping_keys(user_password_key, wrapped_kek, wrapped_vek, vek_uuid, kek_enc_type, vek_enc_type)
                    if self.decryption_key:
                        return # on success
                else:
                    log.debug(f'Wrapped KEK was not present for user {user}')

        if not self.decryption_key:
            log.error('Could not decrypt with credentials provided!')
示例#45
0
文件: Auth.py 项目: egrabs/web-editor
def hashPwd(password):
    return hl.pbkdf2_hmac('sha256', password, _SALT, _ROUNDS)
print()

# Read username
username = input("Username: "******"--save--":
    # Read the new password for the user
    newPassword = input("New password: "******"sha512",  # Hash algorithm
        newPassword.encode("utf-8"),  # Convert the password to bytes
        salt,  # Salt
        100000,  # Iterations of the hash algorithm
    )

    # Store the user's new salt and password hash
    users[username] = {"salt": salt, "password": passwordHash}

    print("OK")
    print()
    # Read another username
    username = input("Username: "******"Users.yaml", "w", encoding="utf-8") as outfile:
    # Dump the contents of the users dictionary to the file in utf-8 format
    yaml.dump(
示例#47
0
 def _hash_password(password: str, salt: bytes, iterations: int,
                    algorithm: str) -> bytes:
     hashed_password = hashlib.pbkdf2_hmac(algorithm, password.encode(),
                                           salt, iterations)
     return hashed_password
示例#48
0
文件: key.py 项目: ololoru/borg
 def kdf(self, salt, iterations, length):
     return pbkdf2_hmac('sha256', self.encode('utf-8'), salt, iterations,
                        length)
示例#49
0
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    client_socket.connect((host, port))
    response = client_socket.recv(2048)  # Demande login par serveur
    name = input(response.decode('utf-8'))
    login_general = name
    if name == "server":
        name = input(
            "Ce pseudo n'est pas autorisé, veuillez en choisir un nouveau svp :"
        )
    client_socket.send(name.encode('utf-8'))  # Envoi login
    response = client_socket.recv(2048)  # Demande password par serveur
    salt = b'\xf0\xa4\x1f;\xcbZ\xf41\xb4k{T\xac\x8ea\x9a'
    password = hashlib.pbkdf2_hmac(
        'sha256',
        input(response.decode('utf-8')).encode('utf-8'), salt, 100000).hex()
    client_socket.send(password.encode('utf-8'))  # Envoie password
    response = client_socket.recv(2048)  # Demande pubkey par serveur
    if not os.path.isfile("privateclient.json"):
        open("privateclient.json", "w").close
    if not os.path.isfile("publicclient.json"):
        open("publicclient.json", "w").close
    if response.decode('utf-8') == "pubkey":
        if os.path.getsize("privateclient.json") > 0 and os.path.getsize(
                "publicclient.json") > 0:
            with open("privateclient.json", "r") as privateclient:
                dataprivate = json.load(privateclient)
                if (name in dataprivate.keys() and dataprivate[name]
                        == "") or name not in dataprivate.keys():
                    secret_code = "JackJack"
示例#50
0
from selenium import webdriver
import time
import os, hashlib, getpass
try:
    driver = webdriver.Chrome()
except:
    print("It seems that you have not correctly installed chromedriver\n \
Lauching requirement.py\nIf requirement.py doesn't fix the issue, try to reinstall chromedriver"
          )
    os.system("python3 requirement.py")
passphrase = getpass.getpass("Passphrase:  ")
salt = b"{salt}"  #Put the salt given by create_sha256_hashed_password.py
key = b"{key}"  #Put the key given by create_sha256_hashed_password.py
username = '******'  #Put your username it's usually: prenom.nom
personal_datas = [salt, key, username]
hash_passphrase = hashlib.pbkdf2_hmac('sha256', passphrase.encode('utf-8'),
                                      salt, 100000)
if hash_passphrase == key:
    print('Correct password')
    driver = webdriver.Chrome()
    driver.get('https://ent.iledefrance.fr/auth/login')
    time.sleep(5)  #Waiting the time for the page to be loaded
    login_area = driver.find_element('id', 'email')
    login_area.send_keys(username)
    password_area = driver.find_element_by_id('password')
    password_area.send_keys(passphrase)
    bouton = driver.find_element_by_class_name('flex-magnet-bottom-right')
    bouton.click()
    time.sleep(10)  #Waiting the time for the page tp be loaded
    driver.find_element_by_class_name('pronote').click()
    time.sleep(5)  #Waiting the time for the page to be loaded
    driver.switch_to.window(driver.window_handles[-1])
示例#51
0
def hash(password,salt,iters=2048):
	return pbkdf2_hmac(hash_name='sha512',password=password,salt=salt,iterations=iters)
示例#52
0
def verify_password(password, salted_hash, salt):
    hashed = hashlib.pbkdf2_hmac('sha1', password.encode("utf-8"),
                                 bytearray.fromhex(salt), 100000)
    if hashed.hex() == salted_hash:
        return True
    return False
示例#53
0
文件: app.py 项目: jzlotek/regrader
def passencrypt(password):
    return hashlib.pbkdf2_hmac('sha256', bytes(password, 'utf-8'),
                               bytes(os.getenv('SALT'), 'utf-8'), 200000)
示例#54
0
def get_hashed_password(password: str, salt: str):
    key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
    return key