Python scrypt.hash() Examples
The following are 30
code examples of scrypt.hash().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
scrypt
, or try the search function
.
Example #1
Source File: uuid_map.py From bitmask-dev with GNU General Public License v3.0 | 6 votes |
def _encode_uuid_map(userid, uuid, passwd): data = 'userid:%s:uuid:%s' % (userid, uuid) # FIXME scrypt.encrypt is broken in windows. # This is a quick hack. The hostname might not be unique enough though. # We could use a long random hash per entry and store it in the file. # Other option is to use a different KDF that is supported by cryptography # (ie, pbkdf) if IS_WIN: key = scrypt.hash(passwd, socket.gethostname()) key = base64.urlsafe_b64encode(key[:32]) f = Fernet(key, backend=crypto_backend) encrypted = f.encrypt(data) else: encrypted = scrypt.encrypt(data, passwd, maxtime=0.05) return base64.urlsafe_b64encode(encrypted)
Example #2
Source File: uuid_map.py From bitmask-dev with GNU General Public License v3.0 | 6 votes |
def _decode_uuid_line(line, passwd): decoded = base64.urlsafe_b64decode(line) if IS_WIN: key = scrypt.hash(passwd, socket.gethostname()) key = base64.urlsafe_b64encode(key[:32]) try: f = Fernet(key, backend=crypto_backend) maybe_decrypted = f.decrypt(key) except Exception: return None else: try: maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1) except scrypt.error: return None match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted) if match: return match[0]
Example #3
Source File: nightminer.py From nightminer with MIT License | 6 votes |
def set_scrypt_library(library = SCRYPT_LIBRARY_AUTO): '''Sets the scrypt library implementation to use.''' global SCRYPT_LIBRARY global scrypt_proof_of_work if library == SCRYPT_LIBRARY_LTC: import ltc_scrypt scrypt_proof_of_work = ltc_scrypt.getPoWHash SCRYPT_LIBRARY = library elif library == SCRYPT_LIBRARY_SCRYPT: import scrypt as NativeScrypt scrypt_proof_of_work = lambda header: NativeScrypt.hash(header, header, 1024, 1, 1, 32) SCRYPT_LIBRARY = library # Try to load a faster version of scrypt before using the pure-Python implementation elif library == SCRYPT_LIBRARY_AUTO: try: set_scrypt_library(SCRYPT_LIBRARY_LTC) except Exception, e: try: set_scrypt_library(SCRYPT_LIBRARY_SCRYPT) except Exception, e: set_scrypt_library(SCRYPT_LIBRARY_PYTHON)
Example #4
Source File: coins.py From torba with MIT License | 6 votes |
def pay_to_address_script(cls, address): """Return a pubkey script that pays to a pubkey hash. Pass the address (either P2PKH or P2SH) in base58 form. """ raw = cls.DECODE_CHECK(address) # Require version byte(s) plus hash160. verbyte = -1 verlen = len(raw) - 20 if verlen > 0: verbyte, hash160 = raw[:verlen], raw[verlen:] if verbyte == cls.P2PKH_VERBYTE: return cls.hash160_to_P2PKH_script(hash160) if verbyte in cls.P2SH_VERBYTES: return ScriptPubKey.P2SH_script(hash160) raise CoinError('invalid address: {}'.format(address))
Example #5
Source File: cork.py From bazarr with GNU General Public License v3.0 | 6 votes |
def _hash_scrypt(username, pwd, salt=None): """Hash username and password, generating salt value if required Use scrypt. :returns: base-64 encoded str. """ if not scrypt_available: raise Exception("scrypt.hash required." " Please install the scrypt library.") if salt is None: salt = os.urandom(32) assert len(salt) == 32, "Incorrect salt length" cleartext = "%s\0%s" % (username, pwd) h = scrypt.hash(cleartext, salt) # 's' for scrypt hashed = b's' + salt + h return b64encode(hashed)
Example #6
Source File: cork.py From bazarr with GNU General Public License v3.0 | 6 votes |
def _verify_password(self, username, pwd, salted_hash): """Verity username/password pair against a salted hash :returns: bool """ assert isinstance(salted_hash, type(b'')) decoded = b64decode(salted_hash) hash_type = decoded[0] if isinstance(hash_type, int): hash_type = chr(hash_type) salt = decoded[1:33] if hash_type == 'p': # PBKDF2 h = self._hash_pbkdf2(username, pwd, salt) return salted_hash == h if hash_type == 's': # scrypt h = self._hash_scrypt(username, pwd, salt) return salted_hash == h raise RuntimeError("Unknown hashing algorithm in hash: %r" % decoded)
Example #7
Source File: keys.py From nowallet with MIT License | 6 votes |
def derive_key(salt: str, passphrase: str, hd: bool = True) -> \ Union[int, Tuple[int, bytes]]: key_length = 64 if hd else 32 # type: int t1 = and_split(bytes(salt, "utf-8")) # type: Tuple[bytes, bytes] salt1, salt2 = t1 t2 = and_split(bytes(passphrase, "utf-8")) # type: Tuple[bytes, bytes] pass1, pass2 = t2 scrypt_key = scrypt.hash( pass1, salt1, N=1 << 18, buflen=key_length) # type: bytes pbkdf2_key = pbkdf2.PBKDF2( pass2, salt2, iterations=1 << 16, digestmodule=SHA256).read(key_length) # type: bytes merged = xor_merge(scrypt_key, pbkdf2_key) # type: bytes if hd: secret_exp = int(merged[0:32].hex(), 16) # type: int chain_code = merged[32:] # type: bytes return secret_exp, chain_code return int(merged.hex(), 16)
Example #8
Source File: bruteforce.py From cryptovenom with GNU General Public License v3.0 | 6 votes |
def bf(h, dictionary): f = open(dictionary, 'r') lines = f.readlines() lines = lines.replace('\n', '') print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h) for i in lines: h2 = scrypt.hash(i, salt) if h == h2: print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i) exit() print('\033[1;31m[-]\033[0m Hash could not be cracked!')
Example #9
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 6 votes |
def addr_to_pubkeyhash(address, as_hex=False, encoding=None): """ Convert base58 or bech32 address to public key hash Wrapper for the :func:`addr_base58_to_pubkeyhash` and :func:`addr_bech32_to_pubkeyhash` method :param address: Crypto currency address in base-58 format :type address: str :param as_hex: Output as hexstring :type as_hex: bool :param encoding: Address encoding used: base58 or bech32. Default is base58. Try to derive from address if encoding=None is provided :type encoding: str :return bytes, str: public key hash """ if encoding == 'base58' or encoding is None: try: pkh = addr_base58_to_pubkeyhash(address, as_hex) except EncodingError: pkh = None if pkh is not None: return pkh if encoding == 'bech32' or encoding is None: return addr_bech32_to_pubkeyhash(address, as_hex=as_hex)
Example #10
Source File: genesis.py From GenesisH0 with Apache License 2.0 | 6 votes |
def generate_hash(data_block, algorithm, start_nonce, bits): print 'Searching for genesis hash..' nonce = start_nonce last_updated = time.time() # https://en.bitcoin.it/wiki/Difficulty target = (bits & 0xffffff) * 2**(8*((bits >> 24) - 3)) while True: sha256_hash, header_hash = generate_hashes_from_block(data_block, algorithm) last_updated = calculate_hashrate(nonce, last_updated) if is_genesis_hash(header_hash, target): if algorithm == "X11" or algorithm == "X13" or algorithm == "X15": return (header_hash, nonce) return (sha256_hash, nonce) else: nonce = nonce + 1 data_block = data_block[0:len(data_block) - 4] + struct.pack('<I', nonce)
Example #11
Source File: genesis.py From GenesisH0 with Apache License 2.0 | 6 votes |
def get_args(): parser = optparse.OptionParser() parser.add_option("-t", "--time", dest="time", default=int(time.time()), type="int", help="the (unix) time when the genesisblock is created") parser.add_option("-z", "--timestamp", dest="timestamp", default="The Times 03/Jan/2009 Chancellor on brink of second bailout for banks", type="string", help="the pszTimestamp found in the coinbase of the genesisblock") parser.add_option("-n", "--nonce", dest="nonce", default=0, type="int", help="the first value of the nonce that will be incremented when searching the genesis hash") parser.add_option("-a", "--algorithm", dest="algorithm", default="SHA256", help="the PoW algorithm: [SHA256|scrypt|X11|X13|X15]") parser.add_option("-p", "--pubkey", dest="pubkey", default="04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f", type="string", help="the pubkey found in the output script") parser.add_option("-v", "--value", dest="value", default=5000000000, type="int", help="the value in coins for the output, full value (exp. in bitcoin 5000000000 - To get other coins value: Block Value * 100000000)") parser.add_option("-b", "--bits", dest="bits", type="int", help="the target in compact representation, associated to a difficulty of 1") (options, args) = parser.parse_args() if not options.bits: if options.algorithm == "scrypt" or options.algorithm == "X11" or options.algorithm == "X13" or options.algorithm == "X15": options.bits = 0x1e0ffff0 else: options.bits = 0x1d00ffff return options
Example #12
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 6 votes |
def pubkeyhash_to_addr_base58(pubkeyhash, prefix=b'\x00'): """ Convert public key hash to base58 encoded address >>> pubkeyhash_to_addr_base58('21342f229392d7c9ed82c932916cee6517fbc9a2') '142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ' :param pubkeyhash: Public key hash :type pubkeyhash: bytes, str :param prefix: Prefix version byte of network, default is bitcoin '\x00' :type prefix: str, bytes :return str: Base-58 encoded address """ # prefix = to_bytes(prefix) key = to_bytearray(prefix) + to_bytearray(pubkeyhash) addr256 = key + double_sha256(key)[:4] return change_base(addr256, 256, 58)
Example #13
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def generate_address(self, passphrase): """ Make sure the confirm code is valid for the given password and address. """ inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt) public_key = privtopub(inter.passpoint) # from Bip38EncryptedPrivateKey.create_from_intermediate derived = scrypt.hash(inter.passpoint, self.addresshash + inter.ownerentropy, 1024, 1, 1, 64) derivedhalf1, derivedhalf2 = derived[:32], derived[32:] unencrypted_prefix = bytes_to_int(self.pointbprefix) ^ (bytes_to_int(derived[63]) & 0x01); aes = AES.new(derivedhalf2) block1 = aes.decrypt(self.pointbx1) block2 = aes.decrypt(self.pointbx2) raise Exception("Not done yet") return block2 = long(hexlify(pointb2), 16) ^ long(hexlify(derivedhalf1[16:]), 16) return pubtoaddr(*fast_multiply(pointb, passfactor)) ## tests below
Example #14
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 5 votes |
def addr_base58_to_pubkeyhash(address, as_hex=False): """ Convert Base58 encoded address to public key hash >>> addr_base58_to_pubkeyhash('142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ', as_hex=True) '21342f229392d7c9ed82c932916cee6517fbc9a2' :param address: Crypto currency address in base-58 format :type address: str, bytes :param as_hex: Output as hexstring :type as_hex: bool :return bytes, str: Public Key Hash """ try: address = change_base(address, 58, 256, 25) except EncodingError as err: raise EncodingError("Invalid address %s: %s" % (address, err)) check = address[-4:] pkh = address[:-4] checksum = double_sha256(pkh)[0:4] assert (check == checksum), "Invalid address, checksum incorrect" if as_hex: return change_base(pkh, 256, 16)[2:] else: return pkh[1:]
Example #15
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def create(cls, passphrase, seed=None, ownersalt=None, lot=None, sequence=None): passphrase = normalize('NFC', unicode(passphrase)) if is_py2: passphrase = passphrase.encode('utf8') if seed and not is_py2: seed = bytes(seed, 'ascii') if ownersalt and len(ownersalt) != 8: raise Exception("Invalid salt") if lot and sequence: if not ownersalt: ownersalt = sha256(seed).digest()[:4] lotseq = unhexlify("%0.8x" % (self.lotseq_constant * lot + sequence)) ownerentropy = ownersalt + lotseq else: if not ownersalt: ownersalt = ownerentropy = sha256(seed).digest()[:8] else: ownerentropy = ownersalt prefactor = scrypt.hash(passphrase, ownersalt, 16384, 8, 8, 32) if lot and sequence: passfactor = sha256(sha256(prefactor + ownerentropy).digest()).digest() else: passfactor = prefactor passpoint = compress(*fast_multiply(G, bytes_to_int(passfactor))) last_byte = b'\x53' if not lot and not sequence else b'\x51' # 7 1 8 33 payload = b'\x2C\xE9\xB3\xE1\xFF\x39\xE2' + last_byte + ownerentropy + passpoint return cls(b58encode_check(payload))
Example #16
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def encrypt(cls, crypto, privkey, passphrase): """ BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey. """ pub_byte, priv_byte = get_magic_bytes(crypto) privformat = get_privkey_format(privkey) if privformat in ['wif_compressed','hex_compressed']: compressed = True flagbyte = b'\xe0' if privformat == 'wif_compressed': privkey = encode_privkey(privkey, 'hex_compressed') privformat = get_privkey_format(privkey) if privformat in ['wif', 'hex']: compressed = False flagbyte = b'\xc0' if privformat == 'wif': privkey = encode_privkey(privkey,'hex') privformat = get_privkey_format(privkey) pubkey = privtopub(privkey) addr = pubtoaddr(pubkey, pub_byte) passphrase = normalize('NFC', unicode(passphrase)) if is_py2: ascii_key = addr passphrase = passphrase.encode('utf8') else: ascii_key = bytes(addr,'ascii') salt = sha256(sha256(ascii_key).digest()).digest()[0:4] key = scrypt.hash(passphrase, salt, 16384, 8, 8) derivedhalf1, derivedhalf2 = key[:32], key[32:] aes = AES.new(derivedhalf2) encryptedhalf1 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(hexlify(derivedhalf1[0:16]), 16)))) encryptedhalf2 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(hexlify(derivedhalf1[16:32]), 16)))) # 39 bytes 2 (6P) 1(R/Y) 4 16 16 payload = b'\x01\x42' + flagbyte + salt + encryptedhalf1 + encryptedhalf2 return cls(crypto, b58encode_check(payload))
Example #17
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def decrypt(self, passphrase, wif=False): """ BIP0038 non-ec-multiply decryption. Returns hex privkey. """ passphrase = normalize('NFC', unicode(passphrase)) if is_py2: passphrase = passphrase.encode('utf8') if self.ec_multiply: raise Exception("Not supported yet") key = scrypt.hash(passphrase, self.addresshash, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] aes = AES.new(derivedhalf2) decryptedhalf2 = aes.decrypt(self.encryptedhalf2) decryptedhalf1 = aes.decrypt(self.encryptedhalf1) priv = decryptedhalf1 + decryptedhalf2 priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16))) pub = privtopub(priv) if self.compressed: pub = encode_pubkey(pub, 'hex_compressed') addr = pubtoaddr(pub, self.pub_byte) if is_py2: ascii_key = addr else: ascii_key = bytes(addr,'ascii') if sha256(sha256(ascii_key).digest()).digest()[0:4] != self.addresshash: raise Exception('Bip38 password decrypt failed: Wrong password?') else: formatt = 'wif' if wif else 'hex' if self.compressed: return encode_privkey(priv, formatt + '_compressed', self.priv_byte) else: return encode_privkey(priv, formatt, self.priv_byte)
Example #18
Source File: bip38.py From python-graphenelib with MIT License | 5 votes |
def encrypt(privkey, passphrase): """ BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey. :param privkey: Private key :type privkey: Base58 :param str passphrase: UTF-8 encoded passphrase for encryption :return: BIP0038 non-ec-multiply encrypted wif key :rtype: Base58 """ if isinstance(privkey, str): privkey = PrivateKey(privkey) else: privkey = PrivateKey(repr(privkey)) privkeyhex = repr(privkey) # hex addr = format(privkey.bitcoin.address, "BTC") a = _bytes(addr) salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4] if SCRYPT_MODULE == "scrypt": # pragma: no cover key = scrypt.hash(passphrase, salt, 16384, 8, 8) elif SCRYPT_MODULE == "pylibscrypt": # pragma: no cover key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8) else: # pragma: no cover raise ValueError("No scrypt module loaded") # pragma: no cover (derived_half1, derived_half2) = (key[:32], key[32:]) aes = AES.new(derived_half2, AES.MODE_ECB) encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes) encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes) " flag byte is forced 0xc0 because Graphene only uses compressed keys " payload = b"\x01" + b"\x42" + b"\xc0" + salt + encrypted_half1 + encrypted_half2 " Checksum " checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] privatkey = hexlify(payload + checksum).decode("ascii") return Base58(privatkey)
Example #19
Source File: genesis.py From GenesisH0 with Apache License 2.0 | 5 votes |
def announce_found_genesis(genesis_hash, nonce): print "genesis hash found!" print "nonce: " + str(nonce) print "genesis hash: " + genesis_hash.encode('hex_codec') # GOGOGO!
Example #20
Source File: __init__.py From jarvis with GNU General Public License v2.0 | 5 votes |
def validate(n, r, p): """ helper which validates a set of scrypt config parameters. scrypt will take ``O(n * r * p)`` time and ``O(n * r)`` memory. limitations are that ``n = 2**<positive integer>``, ``n < 2**(16*r)``, ``r * p < 2 ** 30``. :param n: scrypt rounds :param r: scrypt block size :param p: scrypt parallel factor """ if r < 1: raise ValueError("r must be > 0: r=%r" % r) if p < 1: raise ValueError("p must be > 0: p=%r" % p) if r * p > MAX_RP: # pbkdf2-hmac-sha256 limitation - it will be requested to generate ``p*(2*r)*64`` bytes, # but pbkdf2 can do max of (2**31-1) blocks, and sha-256 has 32 byte block size... # so ``(2**31-1)*32 >= p*r*128`` -> ``r*p < 2**30`` raise ValueError("r * p must be < 2**30: r=%r, p=%r" % (r,p)) if n < 2 or n & (n - 1): raise ValueError("n must be > 1, and a power of 2: n=%r" % n) return True # TODO: configuration picker (may need psutil for full effect) #========================================================================== # hash frontend #========================================================================== #: backend function used by scrypt(), filled in by _set_backend()
Example #21
Source File: __init__.py From pycoind with MIT License | 5 votes |
def get_merkle_root(transactions): branches = [t.hash for t in transactions] while len(branches) > 1: if (len(branches) % 2) == 1: branches.append(branches[-1]) branches = [sha256d(a + b) for (a, b) in zip(branches[0::2], branches[1::2])] return branches[0] # Hexlify Helpers
Example #22
Source File: keystore.py From web3-gear with MIT License | 5 votes |
def scrypt_hash(val, params): return scrypt.hash(str(val), decode_hex(params["salt"]), params["n"], params["r"], params["p"], params["dklen"])
Example #23
Source File: genesis.py From GenesisH0 with Apache License 2.0 | 5 votes |
def calculate_hashrate(nonce, last_updated): if nonce % 1000000 == 999999: now = time.time() hashrate = round(1000000/(now - last_updated)) generation_time = round(pow(2, 32) / hashrate / 3600, 1) sys.stdout.write("\r%s hash/s, estimate: %s h"%(str(hashrate), str(generation_time))) sys.stdout.flush() return now else: return last_updated
Example #24
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 5 votes |
def hash160(string): """ Creates a RIPEMD-160 + SHA256 hash of the input string :param string: Script :type string: bytes :return bytes: RIPEMD-160 hash of script """ return hashlib.new('ripemd160', hashlib.sha256(string).digest()).digest()
Example #25
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 5 votes |
def double_sha256(string, as_hex=False): """ Get double SHA256 hash of string :param string: String to be hashed :type string: bytes :param as_hex: Return value as hexadecimal string. Default is False :type as_hex: bool :return bytes, str: """ if not as_hex: return hashlib.sha256(hashlib.sha256(string).digest()).digest() else: return hashlib.sha256(hashlib.sha256(string).digest()).hexdigest()
Example #26
Source File: encoding.py From bitcoinlib with GNU General Public License v3.0 | 5 votes |
def pubkeyhash_to_addr(pubkeyhash, prefix=None, encoding='base58'): """ Convert public key hash to base58 encoded address Wrapper for the :func:`pubkeyhash_to_addr_base58` and :func:`pubkeyhash_to_addr_bech32` method :param pubkeyhash: Public key hash :type pubkeyhash: bytes, str :param prefix: Prefix version byte of network, default is bitcoin '\x00' :type prefix: str, bytes :param encoding: Encoding of address to calculate: base58 or bech32. Default is base58 :type encoding: str :return str: Base58 or bech32 encoded address """ if encoding == 'base58': if prefix is None: prefix = b'\x00' return pubkeyhash_to_addr_base58(pubkeyhash, prefix) elif encoding == 'bech32': if prefix is None: prefix = 'bc' return pubkeyhash_to_addr_bech32(pubkeyhash, prefix) else: raise EncodingError("Encoding %s not supported" % encoding)
Example #27
Source File: __init__.py From jarvis with GNU General Public License v2.0 | 5 votes |
def _load_cffi_backend(): """ Try to import the ctypes-based scrypt hash function provided by the ``scrypt <https://pypi.python.org/pypi/scrypt/>``_ package. """ try: from scrypt import hash return hash except ImportError: pass # not available, but check to see if package present but outdated / not installed right try: import scrypt except ImportError as err: if "scrypt" not in str(err): # e.g. if cffi isn't set up right # user should try importing scrypt explicitly to diagnose problem. warn("'scrypt' package failed to import correctly (possible installation issue?)", exc.PasslibWarning) # else: package just isn't installed else: warn("'scrypt' package is too old (lacks ``hash()`` method)", exc.PasslibWarning) return None #: list of potential backends
Example #28
Source File: cork.py From bazarr with GNU General Public License v3.0 | 5 votes |
def validate_registration(self, registration_code): """Validate pending account registration, create a new account if successful. :param registration_code: registration code :type registration_code: str. """ try: data = self._store.pending_registrations.pop(registration_code) except KeyError: raise AuthException("Invalid registration code.") username = data['username'] if username in self._store.users: raise AAAException("User is already existing.") # the user data is moved from pending_registrations to _users self._store.users[username] = { 'role': data['role'], 'hash': data['hash'], 'email_addr': data['email_addr'], 'desc': data['desc'], 'creation_date': data['creation_date'], 'last_login': str(datetime.utcnow()) } self._store.save_users()
Example #29
Source File: cork.py From bazarr with GNU General Public License v3.0 | 5 votes |
def create_user(self, username, role, password, email_addr=None, description=None): """Create a new user account. This method is available to users with level>=100 :param username: username :type username: str. :param role: role :type role: str. :param password: cleartext password :type password: str. :param email_addr: email address (optional) :type email_addr: str. :param description: description (free form) :type description: str. :raises: AuthException on errors """ assert username, "Username must be provided." if self.current_user.level < 100: raise AuthException("The current user is not authorized" " to create users.") if username in self._store.users: raise AAAException("User is already existing.") if role not in self._store.roles: raise AAAException("Nonexistent user role.") tstamp = str(datetime.utcnow()) h = self._hash(username, password) h = h.decode('ascii') self._store.users[username] = { 'role': role, 'hash': h, 'email_addr': email_addr, 'desc': description, 'creation_date': tstamp, 'last_login': tstamp } self._store.save_users()
Example #30
Source File: cork.py From bazarr with GNU General Public License v3.0 | 5 votes |
def login(self, username, password, success_redirect=None, fail_redirect=None): """Check login credentials for an existing user. Optionally redirect the user to another page (typically /login) :param username: username :type username: str or unicode. :param password: cleartext password :type password: str.or unicode :param success_redirect: redirect authorized users (optional) :type success_redirect: str. :param fail_redirect: redirect unauthorized users (optional) :type fail_redirect: str. :returns: True for successful logins, else False """ #assert isinstance(username, type(u'')), "the username must be a string" #assert isinstance(password, type(u'')), "the password must be a string" if username in self._store.users: salted_hash = self._store.users[username]['hash'] if hasattr(salted_hash, 'encode'): salted_hash = salted_hash.encode('ascii') authenticated = self._verify_password( username, password, salted_hash, ) if authenticated: # Setup session data self._setup_cookie(username) self._store.users[username]['last_login'] = str(datetime.utcnow()) self._store.save_users() if success_redirect: self._redirect(success_redirect) return True if fail_redirect: self._redirect(fail_redirect) return False