示例#1
0
    def test_valid_password(self):
        dummy_password = dummy_salt_input = \
            "http://blog.transparency.org/wp-content/uploads/2010/05/A2_Whistelblower_poster.jpg"
        dummy_salt = get_salt(dummy_salt_input)

        hashed_once = binascii.b2a_hex(scrypt.hash(dummy_password, dummy_salt))
        hashed_twice = binascii.b2a_hex(scrypt.hash(dummy_password, dummy_salt))
        self.assertTrue(hashed_once, hashed_twice)

        self.assertTrue(check_password(dummy_password, hashed_once, dummy_salt_input))
示例#2
0
def hash_pw(password, salt):
    if type(password) != bytes:
        password = bytes(password, 'utf-8')

    if debug:
        h = scrypt.hash(password, salt, N=2 ** 4, p=1, r=1, dkLen=buflen)
    else:
        h = scrypt.hash(password, salt, N=N, p=p, r=r, buflen=buflen)

    return h
示例#3
0
    def _decrypt_ec_multiply(k_buffer, passphrase):
        if passphrase is None or passphrase == '':
            raise ValueError("Passphrase must not be empty.")

        prefix = k_buffer[0:1]
        flagbyte = k_buffer[1:2]
        ls_numbers = False
        if ''.join(chr(ord(c)&ord(k)) for c,k in izip(flagbyte, '\x04')) == '\x04':
            ls_numbers = True
            ls, = unpack('>I', k_buffer[10:14])
            lot = ls / 4096
            sequence = ls - (lot*4096)
            salt = k_buffer[6:10]
        else:
            salt = k_buffer[6:14]
        
        address_hash = k_buffer[2:6]
        ownerentropy = k_buffer[6:14]

        prefactor = scrypt.hash(passphrase, salt, N=16384, r=8, p=8, buflen=32)
        if ls_numbers is True:
            passfactor = SHA256.new(SHA256.new(prefactor+ownerentropy).digest()).digest()
        else:
            passfactor = prefactor

        passpoint = Bip38._compute_passpoint(passfactor)
        derived = scrypt.hash(passpoint, address_hash + ownerentropy, N=1024, r=1, p=1, buflen=64)
        derived_half1 = derived[:32]
        derived_half2 = derived[32:64]
        cipher = AES.new(derived_half2)

        decrypted_half2 = Bip38.xor_zip(cipher.decrypt(k_buffer[22:22+16]), derived_half1[16:32])
        ep12 = decrypted_half2[0:8]
        decrypted_half1 = Bip38.xor_zip(cipher.decrypt(k_buffer[14:14+8] + ep12), derived_half1[:16])
        seedb = decrypted_half1[0:16] + decrypted_half2[8:16]
        factorb = SHA256.new(SHA256.new(seedb).digest()).digest()

        r = ssl.BN_new()
        pf = ssl.BN_bin2bn(passfactor, 32, ssl.BN_new())
        fb = ssl.BN_bin2bn(factorb, 32, ssl.BN_new())
        NID_secp256k1 = 714
        k = ssl.EC_KEY_new_by_curve_name(NID_secp256k1)
        group = ssl.EC_KEY_get0_group(k)
        ctx = ssl.BN_CTX_new()
        ssl.BN_CTX_start(ctx)
        order = ssl.BN_CTX_get(ctx)
        if ssl.EC_GROUP_get_order(group, order, ctx) == 0:
            raise Exception('Error in EC_GROUP_get_order()')
        ssl.BN_mod_mul(r, pf, fb, order, ctx)
        ssl.BN_CTX_free(ctx) 
        pkey = CKey()
        final =  ctypes.create_string_buffer(32)
        ssl.BN_bn2bin(r, final)
        pkey.generate(secret=final)
        return pkey.get_secret()
示例#4
0
文件: bfkdf.py 项目: stribika/bfkdf
def hash(password, salt):
    """The hash function you want to call."""

    k0 = scrypt.hash(password, salt, 512, 4, 8, 48)
    debug("k0", k0)
    rng = prng.AESCTR(k0[:32], k0[32:])
    b = run_brainfuck(rng)
    k1 = scrypt.hash(b, salt, 512, 4, 8, 32)
    debug("k1", k1)
    key = scrypt.hash(k1 + password, salt, 512, 4, 8, 32)
    debug("key", key)
    return key
示例#5
0
def intermediate_code(password,useLotAndSequence=False,lot=100000,sequence=1, \
                      owner_salt=os.urandom(8)):
    '''
    Generates an intermediate code, as outlined by the BIP0038
    wiki, found at:

    https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki

    Output is a string, beginning with 'passphrase'. Lot and
    sequence inputs are ints.  Even though the Lot range is only
    recommended to be in the range 100000-999999, that
    recommendation is enforced in this code. Sequence is in the
    range 0-4095. Sequence starts at one instead of zero, as per
    the wiki recommendation.

    Also, note that the wiki test vectors do not include examples
    for compressed keys with EC multiplication. Nor does the 
    Bitcoin Address Utility reference implementation successfully
    identify 'cfrm38' confirmation codes for compressed keys.
    This python implementation works with them, and the Bitcoin
    Address Utility can still decrypt the '6P' encrypted private
    keys for compressed public keys, but for compatibility with
    the reference implementation, it is highly recommended that
    you create encrypted keys and confirmation codes only for
    uncompressed public keys when using an intermediate code to
    create EC multiplied encryped private keys with confirmation
    codes.
    '''

    password = normalize_input(password, False, True)
    assert len(owner_salt) == 8 or \
          (len(owner_salt) == 4 and useLotAndSequence)
    if useLotAndSequence:
        lot, sequence = int(lot), int(sequence)
        assert lot >= 100000 and lot <= 999999
        assert sequence >= 0 and sequence <= 4095
        lotsequence = dechex((lot*4096 + sequence),4)
        owner_salt = owner_salt[:4]
        prefactor = scrypt.hash(password,owner_salt,16384,8,8,32)
        prefactor = hexstrlify(prefactor)
        owner_entropy = hexstrlify(owner_salt) + lotsequence
        passfactor = hash256(prefactor + owner_entropy)
        magicbytes = '2ce9b3e1ff39e251'
    else:
        passfactor = scrypt.hash(password,owner_salt,16384,8,8,32)
        passfactor = hexstrlify(passfactor)
        owner_entropy = hexstrlify(owner_salt)
        magicbytes = '2ce9b3e1ff39e253'
    passpoint = privtopub(passfactor,True)
    return b58e(magicbytes + owner_entropy + passpoint)
示例#6
0
def check_password(guessed_password, base64_stored, salt_input):
    guessed_password = guessed_password.encode('utf-8')
    salt = get_salt(salt_input)

    hashed_guessed = scrypt.hash(guessed_password, salt)

    return binascii.b2a_hex(hashed_guessed) == base64_stored
示例#7
0
文件: bip38.py 项目: bpdavenport/btc
def bip38_decrypt(encrypted_privkey,passphrase):
    '''BIP0038 non-ec-multiply decryption. Returns WIF privkey.'''
    d = base58.b58decode(encrypted_privkey)
    d = d[2:]
    flagbyte = d[0:1]
    d = d[1:]
    if flagbyte == '\xc0':
        compressed = False
    if flagbyte == '\xe0':
        compressed = True
    addresshash = d[0:4]
    d = d[4:-4]
    key = scrypt.hash(passphrase,addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    priv = decryptedhalf1 + decryptedhalf2
    priv = binascii.unhexlify('%064x' % (long(binascii.hexlify(priv), 16) ^ long(binascii.hexlify(derivedhalf1), 16)))
    pub = privtopub(priv)
    if compressed:
        pub = encode_pubkey(pub,'hex_compressed')
        wif = encode_privkey(priv,'wif_compressed')
    else:
        wif = encode_privkey(priv,'wif')
    addr = pubtoaddr(pub)
    if hashlib.sha256(hashlib.sha256(addr).digest()).digest()[0:4] != addresshash:
        print('Addresshash verification failed! Password is likely incorrect.')
    return wif
示例#8
0
文件: bip38.py 项目: bpdavenport/btc
def bip38_encrypt(privkey,passphrase):
    '''BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.'''
    privformat = get_privkey_format(privkey)
    if privformat in ['wif_compressed','hex_compressed']:
        compressed = True
        flagbyte = '\xe0'
        if privformat == 'wif_compressed':
            privkey = encode_privkey(privkey,'hex_compressed')
            privformat = get_privkey_format(privkey)
    if privformat in ['wif', 'hex']:
        compressed = False
        flagbyte = '\xc0'
    if privformat == 'wif':
        privkey = encode_privkey(privkey,'hex')
        privformat = get_privkey_format(privkey)
    pubkey = privtopub(privkey)
    addr = pubtoaddr(pubkey)
    addresshash = hashlib.sha256(hashlib.sha256(addr).digest()).digest()[0:4]
    key = scrypt.hash(passphrase, addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    aes = AES.new(derivedhalf2)
    encryptedhalf1 = aes.encrypt(binascii.unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(binascii.hexlify(derivedhalf1[0:16]), 16))))
    encryptedhalf2 = aes.encrypt(binascii.unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(binascii.hexlify(derivedhalf1[16:32]), 16))))
    encrypted_privkey = ('\x01\x42' + flagbyte + addresshash + encryptedhalf1 + encryptedhalf2)
    encrypted_privkey += hashlib.sha256(hashlib.sha256(encrypted_privkey).digest()).digest()[:4] # b58check for encrypted privkey
    encrypted_privkey = base58.b58encode(encrypted_privkey)
    return encrypted_privkey
示例#9
0
def _do_login(session, salt_info, password):
    salt = salt_info['salt']
    login_session = salt_info['login_session']

    if isinstance(password, str):
        password = password.encode('utf8')
    if isinstance(salt, str):
        salt = salt.encode('utf8')

    rs = binascii.unhexlify(salt)
    pwh = scrypt.hash(password, rs, N=2**15, r=8, p=1, buflen=224)[192:224]

    content = base64.b64decode(login_session)
    hmac_pwh = hmac.new(pwh, content, hashlib.sha512).hexdigest()

    url = make_url('login')
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    }
    params = {
        'email_or_username': salt_info['username'],
        'hmac_pwh': hmac_pwh,
        'login_session': salt_info['login_session'],
    }
    r = session.post(url, json.dumps(params), headers=headers)
    assert r.status_code == 200

    content = r.json()
    assert content['status']['code'] == 0

    session.cookies['session'] = content['session']
    return content['me']
示例#10
0
def bip38_encrypt(private_key, passphrase, n=16384, r=8, p=8, compressed=False):
    # determine the flagbyte
    if compressed:
        flagbyte = '\xe0'
    else:
        flagbyte = '\xc0'
    # get the private key's address and equivalent in hex format and wif format
    k = BitcoinKeypair(private_key)
    address = k.address()
    hex_private_key = k.private_key()
    wif_private_key = k.wif_pk()
    # calculate the address's checksum
    address_checksum = sha256(sha256(address).digest()).digest()[0:4]
    # calculate the scrypt hash and split it in half
    scrypt_derived_key = scrypt.hash(passphrase, address_checksum, n, r, p)
    derived_half_1 = scrypt_derived_key[0:32]
    derived_half_2 = scrypt_derived_key[32:64]
    # combine parts of the private key and scrypt hash and AES encrypt them
    aes = AES.new(derived_half_2)
    encrypted_half_1 = aes.encrypt(
        binascii.unhexlify(
            '%0.32x' % (long(hex_private_key[0:32], 16) ^ long(binascii.hexlify(derived_half_1[0:16]), 16))
        )
    )
    encrypted_half_2 = aes.encrypt(
        binascii.unhexlify(
            '%0.32x' % (long(hex_private_key[32:64], 16) ^ long(binascii.hexlify(derived_half_1[16:32]), 16))
        )
    )
    # build the encrypted private key from the checksum and encrypted parts
    encrypted_private_key = ('\x42' + flagbyte + address_checksum + encrypted_half_1 + encrypted_half_2)
    # base 58 encode the encrypted private key
    b58check_encrypted_private_key = b58check_encode(encrypted_private_key, version_byte=1)
    # return the encrypted private key
    return b58check_encrypted_private_key
示例#11
0
文件: db.py 项目: cmusser/pw
 def import_from_encrypted(self, salt, password, encrypted):
     '''
     Load the data dictionary from an encrypted JSON text.
     '''
     key = scrypt.hash(password, salt, buflen=32)
     box = nacl.secret.SecretBox(key)
     self.data = json.loads(box.decrypt(encrypted))
示例#12
0
文件: wiki.py 项目: B-Rich/wiki
def register(username, password, email):
    salt = urandom(64)
    hashed = scrypt.hash(password, salt)
    engine.execute(users.insert().values(username=username,
                                         email=email,
                                         password_hash=hashed,
                                         password_salt=salt))
示例#13
0
    def test_03_add_users(self):
        with self.db.session_scope() as session:
            self.assertFalse(self.db.user_exists(session, "jmorton"))

        with self.db.session_scope() as session:
            #shows that a complex user can be added
            self.assertTrue(self.db.add_user(session, "jmorton", "*****@*****.**", "password", "Georgia Tech", first="Joshua", last="Morton", admin=True, mod=True))
            #as well as a simple one
            self.db.add_user(session, "cmalan", "*****@*****.**", "CS50isTheBest", "Harvard", mod=True)
            #but that they need to attend a real school
            self.assertFalse(self.db.add_user(session, "fake_user", "fmail", "fake_pw", "fakeuni"))

        with self.db.session_scope() as session:
            #checks that users can be searched
            self.assertTrue(self.db.user_exists(session, user_name="jmorton"))
            self.assertTrue(self.db.user_exists(session, email_address="*****@*****.**"))
            self.assertTrue(self.db.user_exists(session, user_id=1))
            #shows that even when correct information from conflicting users is provided, the result is correct
            self.assertFalse(self.db.user_exists(session, user_name="jmorton", email_address="*****@*****.**"))
            self.assertEqual(self.db.fetch_user_by_name(session, "jmorton").first_name, "Joshua")
            #and nonexistant users throw errors
            self.assertRaises(database.ItemDoesNotExistError, self.db.fetch_user_by_name, session, "name")
            #hashes are not the same as passwords
            self.assertNotEqual(self.db.fetch_user_by_name(session, "jmorton").password_hash, "password")
            #and we can authenticate users from them
            tempuser = self.db.fetch_user_by_name(session, "jmorton")
            self.assertEqual(tempuser.password_hash, scrypt.hash("password", tempuser.password_salt, self.db.hashlength))
示例#14
0
文件: pbp.py 项目: fpletz/pbp
def decrypt(pkt, pwd=None, k=None, retries=3):
    # decrypts a message symmetrically using crypto_secretbox
    # pkt is a (nonce, ciphertext) tuple
    # k specifies an encryption key, which if not supplied, is derived from
    # pwd which is queried from the user, if also not specified.
    cleark = (pwd is None)
    clearpwd = (k is None)
    cnt=0
    res = None
    while cnt<retries:
        if not k:
            if not pwd:
                pwd = getpass.getpass('\nPassphrase for decrypting: ')
            k =  scrypt.hash(pwd, scrypt_salt)[:nacl.crypto_secretbox_KEYBYTES]
            if clearpwd: clearmem(pwd)
            pwd = None
        try:
            res = nacl.crypto_secretbox_open(pkt[1], pkt[0], k)
        except ValueError:
            cnt += 1
            if cleark: clearmem(k)
            k = None
            continue
        break
    if cleark: clearmem(k)
    if res:
        return res
示例#15
0
def scrypt_test():
    start = time.time()
    hashed = hashlib.sha256(scrypt.hash(password,bcrypt.gensalt(16))).digest()
    obj =AES.new(hashed,AES.MODE_CBC, 'This is an IV456')
    end = time.time()
    ciphertext = obj.encrypt("The answer is no")
    print "scrypt : ",(end-start)
示例#16
0
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)
示例#17
0
文件: pbp.py 项目: fpletz/pbp
def getkey(l, pwd='', empty=False, text=''):
    # queries the user twice for a passphrase if neccessary, and
    # returns a scrypted key of length l
    # allows empty passphrases if empty == True
    # 'text' will be prepended to the password query
    # will not query for a password if pwd != ''
    global _prev_passphrase
    #clearpwd = (pwd.strip()=='')
    pwd2 = not pwd
    if not pwd:
        if _prev_passphrase:
            print >>sys.stderr, "press enter to reuse the previous passphrase"
        while pwd != pwd2 or (not empty and not pwd.strip()):
            pwd = getpass.getpass('1/2 %s Passphrase: ' % text)
            if pwd.strip():
                pwd2 = getpass.getpass('2/2 %s Repeat passphrase: ' % text)
            elif _prev_passphrase is not None:
                pwd = _prev_passphrase
                break
    #if isinstance(pwd2, str):
    #   clearmem(pwd2)
    if pwd.strip():
        _prev_passphrase = pwd
        key = scrypt.hash(pwd, scrypt_salt)[:l]
        #if clearpwd: clearmem(pwd)
        return key
示例#18
0
文件: sludger3.py 项目: bartmnz/final
def encrypt(inq, outq):
    while( True ):
        data = inq.get()
        # Thank you Primm
        outq.put(scrypt.hash(str(data), 'I Hate Liam Echlin', N=2048, r=4, p=4))
       # print("hashed hazmat")
        inq.task_done()
示例#19
0
def encrypt(password, salt=None):
    if salt is None:
        salt = os.urandom(8)
    else:
        salt = binascii.unhexlify(salt)
    hashed = scrypt.hash(password, salt)
    return binascii.hexlify(hashed), binascii.hexlify(salt)
示例#20
0
    def test_change_password(self):
        first_pass = helpers.VALID_PASSWORD1
        second_pass = helpers.VALID_PASSWORD2
        dummy_salt = generateRandomSalt()

        # as first we hash a "first_password" like has to be:
        hashed1 = binascii.b2a_hex(scrypt.hash(str(first_pass), dummy_salt))

        # now emulate the change unsing the globaleaks.security module
        hashed2 = change_password(hashed1, first_pass, second_pass, dummy_salt)

        # verify that second stored pass is the same
        self.assertEqual(
            hashed2,
            binascii.b2a_hex(scrypt.hash(str(second_pass), dummy_salt))
        )
def make_password(masterPassword, siteName):
	global debugging
	
	#strip whitespace and make lowercase
	siteName = re.sub(r'\s+', '', siteName).lower()
	
	key = masterPassword + siteName
	key = sha256hex(key)

	salt = "q3*V!jAre*kF8p5TPxXWQxQs$HTtdn@&dWSzTqwYBn$TF" + lessFrequentButStillAutoSuggestableWordsStr + key

	shash = scrypt.hash(key, salt, N=128, r=16, buflen=64)
	shash = codecs.encode(shash, 'hex')

	result = ""

	desired_word_count = 5
	chunklen = int(len(shash) / desired_word_count)

	
	i = 0
	while i < desired_word_count:
		lenStart = i * chunklen
		lenEnd = (i + 1) * chunklen
		chunk = shash[lenStart:lenEnd]
		ival = int(chunk, 16) % len(lessFrequentButStillAutoSuggestableWords)
		result = result + lessFrequentButStillAutoSuggestableWords[ival]
		result = result + "."
		i = i + 1
	
	result = result + str(ival)
	
	return result
 def add_user(self, session, username, email, password, school, first=None, last=None, admin=False, mod=False): #done
     if not self.user_exists(session, user_name=username):
         salt = str(int(time.time()))
         pwhash = scrypt.hash(password, salt, self.hashlength)
         if self.school_exists(session, school_name=school):
             schoolid = self.fetch_school_by_name(session, school).school_id
         session.add(self.user(user_name=username, email_address=email, password_hash=pwhash, password_salt=salt, school_id=schoolid, first=first, last=last, admin=admin, moderator=mod))
示例#23
0
 def check_login(self, password):
     c = g.db.cursor()
     c.execute("SELECT pass_hash, pass_salt FROM users WHERE username=?", (self.username,))
     for row in c:
         pass_hash, pass_salt = row
         return (str(pass_hash) == scrypt.hash(password.encode('utf-8'), str(pass_salt)))
     return False
示例#24
0
    def get_passkey(self, password):
        """Returns the hashed version of the password.

        Broken out into a method, so we can swap it if nec.

        """
        if password is None:
            raise Exception("Password cannot be null.")

        # N CPU cost parameter.  ( N should be a power of two > 1)
        # r Memory cost parameter.
        # p Parallelization parameter.
        # r*p should be < 2**30
        # Defaults to N=16384, r=8, p=1, buflen=64

        # Per http://www.tarsnap.com/scrypt/scrypt-slides.pdf
        # (N = 2^14, r = 8, p = 1) for < 100ms (interactive use), and
        # (N = 2^20, r = 8, p = 1) for < 5s (sensitive storage).

        if self.passkey is not None:
            return self.passkey

        pkey = base64.b64encode(scrypt.hash(
            password=password, salt=self.pubkey, N=16384, r=8, p=1)).decode('utf-8')
        return pkey
示例#25
0
文件: warp.py 项目: kilink/warpwallet
def warp(passphrase, salt=""):
    s1 = scrypt.hash(passphrase + "\x01", salt+"\x01", N=2**18, r=8, p=1,
                     buflen=32)
    s2 = pbkdf2(passphrase + "\x02", salt=salt+"\x02", keylen=32, rounds=2**16,
                prf="hmac-sha256")
    key = binascii.hexlify(xor(s1, s2))
    return key, bitcoin.pubtoaddr(bitcoin.privtopub(key))
示例#26
0
def sludger(data):
	if data:
		outgoing = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		#outgoing.connect(("downstream", 4444))
		list1 = []
		list1 = data.split(',')
		#print("str", list1)
		#header = Header(2, 8 + len(list1)*64, 0)
		#outgoing.send(header.serialize())
		h1 = b''
		header = Header(2, 8 + len(list1)*64, 0)
		h1 += header.serialize()
		print("Header {}".format(h1))
		for i in list1:
			i = str(i)
			salt  = "I Hate Liam Echlin"
			h1 += scrypt.hash(i, salt, N = 2048, r = 4, p = 4)
		#print("Header list {}".format(h1))
		not_sent = 1
		while not_sent:
			try:
				outgoing.connect(("downstream", 4444))
				#header = Header(2, 8 + len(list1)*64, 0)
				#outgoing.send(header.serialize())
				outgoing.send(h1)
				not_sent = 0
			except Exception:
				continue
		outgoing.close()
示例#27
0
def auth_user(database, username, password):
    with database.session_scope() as session:
        user = database.fetch_user_by_name(session, username)
        salt = user.password_salt
        if scrypt.hash(password, salt, database.hashlength) == user.password_hash:
            return True
        return False
示例#28
0
def bip38_decrypt(b58check_encrypted_private_key, passphrase, n=16384, r=8, p=8):
    # decode private key from base 58 check to binary
    encrypted_private_key = b58check_decode(b58check_encrypted_private_key)
    # parse the encrypted key different byte sections
    bip38_key_identification_byte = encrypted_private_key[0:1]
    flagbyte = encrypted_private_key[1:2]
    address_checksum = encrypted_private_key[2:6]
    encrypted_half_1 = encrypted_private_key[6:6+16]
    encrypted_half_2 = encrypted_private_key[6+16:6+32]
    # derive a unique key from the passphrase and the address checksum
    scrypt_derived_key = scrypt.hash(passphrase, address_checksum, n, r, p)
    derived_half_1 = scrypt_derived_key[0:32]
    derived_half_2 = scrypt_derived_key[32:64]
    # decrypt the encrypted halves
    aes = AES.new(derived_half_2)
    decrypted_half_1 = aes.decrypt(encrypted_half_1)
    decrypted_half_2 = aes.decrypt(encrypted_half_2)
    # get the original private key from the encrypted halves + the derived half
    decrypted_private_key = '%064x' % (long(binascii.hexlify(decrypted_half_1 + decrypted_half_2), 16) ^ long(binascii.hexlify(derived_half_1), 16))
    # get the address corresponding to the private key
    k = BitcoinKeypair(decrypted_private_key)
    address = k.address()
    # make sure the address matches the checksum in the original encrypted key
    if address_checksum != sha256(sha256(address).digest()).digest()[0:4]:
        raise ValueError('Invalid private key and password combo.')
    # return the decrypted private key
    return k.private_key()
示例#29
0
def generate_hashes_from_block(data_block, algorithm):
    sha256_hash = hashlib.sha256(hashlib.sha256(data_block).digest()).digest()[::-1]
    header_hash = ""
    if algorithm == "scrypt":
        header_hash = scrypt.hash(data_block, data_block, 1024, 1, 1, 32)[::-1]
    elif algorithm == "SHA256":
        header_hash = sha256_hash
    elif algorithm == "X11":
        try:
            exec ("import %s" % "xcoin_hash")
        except ImportError:
            sys.exit("Cannot run X11 algorithm: module xcoin_hash not found")
        header_hash = xcoin_hash.getPoWHash(data_block)[::-1]
    elif algorithm == "X13":
        try:
            exec ("import %s" % "x13_hash")
        except ImportError:
            sys.exit("Cannot run X13 algorithm: module x13_hash not found")
        header_hash = x13_hash.getPoWHash(data_block)[::-1]
    elif algorithm == "X15":
        try:
            exec ("import %s" % "x15_hash")
        except ImportError:
            sys.exit("Cannot run X15 algorithm: module x15_hash not found")
        header_hash = x15_hash.getPoWHash(data_block)[::-1]
    return sha256_hash, header_hash
示例#30
0
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

    """
    privkeyhex    = repr(privkey)   # hex
    addr          = format(privkey.uncompressed.address, "BTC")
    a             = bytes(addr, 'ascii')
    salt          = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    key           = scrypt.hash(passphrase, salt, 16384, 8, 8)
    (derived_half1, derived_half2) = (key[:32], key[32:])
    aes             = AES.new(derived_half2)
    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 BTS 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)
示例#31
0
    def header_hash(cls, header):
        '''Given a header return the hash.'''
        if cls.HEADER_HASH is None:
            import scrypt
            cls.HEADER_HASH = lambda x: scrypt.hash(x, x, 1024, 1, 1, 32)

        version, = struct.unpack('<I', header[:4])
        if version > 6:
            return super().header_hash(header)
        else:
            return cls.HEADER_HASH(header)
示例#32
0
def hash_password(password, salt):
    """
    @param password: a unicode or utf-8 string
    @param salt: a password salt

    @return:
        the salted scrypt hash of the provided password
    """
    password = password.encode('utf-8')
    salt = text_type(salt).encode('utf-8')
    return binascii.hexlify(scrypt.hash(password, salt))
示例#33
0
文件: kdf.py 项目: superwow/zerodb
def key_from_password(username, password, key_file, cert_file, appname, key):
    """
    Key is derived from password using scrypt
    password is replaced with sha256(key) so that we cannot deduce key from
    auth info
    """
    salt = "|".join([username, appname, 'key'])
    key = scrypt.hash(password, salt, **scrypt_kw)
    # Calculate hash so that server cannot derive key from new_password
    # b'auth' is added so that we don't use hash(key) by mistake
    new_password = hashlib.sha256(key + b'auth').digest()
    return new_password, key
示例#34
0
    def get_sync_db_key(self):
        """
        Return the key for protecting the sync database.

        :return: The key for protecting the sync database.
        :rtype: str
        """
        return scrypt.hash(
            password=self._get_local_storage_secret(),
            salt=self._get_sync_db_salt(),
            buflen=32,  # we need a key with 256 bits (32 bytes)
        )
示例#35
0
文件: pbp.py 项目: dnet/pbp
def decrypt(pkt, pwd=None, basedir=None, k=None):
    # symmetric
    cleark = (pwd is None)
    clearpwd = (k is None)
    if not k:
        if not pwd:
            pwd = getpass.getpass('Passphrase for decrypting: ')
        k = scrypt.hash(pwd, scrypt_salt)[:nacl.crypto_secretbox_KEYBYTES]
        if clearpwd: clearmem(pwd)
    res = nacl.crypto_secretbox_open(pkt[1], pkt[0], k)
    if cleark: clearmem(k)
    return res
示例#36
0
    def test_change_password_fail_with_invalid_old_password(self):
        dummy_salt_input = "xxxxxxxx"
        first_pass = helpers.VALID_PASSWORD1
        second_pass = helpers.VALID_PASSWORD2
        dummy_salt = generateRandomSalt()

        # as first we hash a "first_password" like has to be:
        hashed1 = binascii.b2a_hex(scrypt.hash(str(first_pass), dummy_salt))

        # now emulate the change unsing the globaleaks.security module
        self.assertRaises(errors.InvalidOldPassword, change_password, hashed1,
                          "invalid_old_pass", second_pass, dummy_salt_input)
示例#37
0
def hash_password(password, salt):
    """
    @param password: a password
    @param salt: a password salt

    @return:
        the salted scrypt hash of the provided password
    """
    password = password.encode('utf-8')
    salt = salt.encode('utf-8')

    return scrypt.hash(password, salt).encode('hex')
示例#38
0
def decryptDecodeScryptKey(cf, password):
    derived = scrypt.hash(password, cf.cryptoSalt, cf.N, cf.r, cf.p)

    key = derived[:KEY_LEN_BYTES]
    iv = derived[KEY_LEN_BYTES:]
    #print('key        : %s' % str(codecs.encode(key,"hex")).upper())
    scrypted_intermediate_key = scrypt.hash(key, cf.cryptoSalt, cf.N, cf.r,
                                            cf.p)
    scrypted_intermediate_key_iv = scrypt.hash(derived, cf.cryptoSalt, cf.N,
                                               cf.r, cf.p)
    #print('scrypted IK_key        : %s' % str(codecs.encode(scrypted_intermediate_key,"hex")).upper())
    #print('scrypted IK_key_iv     : %s' % str(codecs.encode(scrypted_intermediate_key_iv,"hex")).upper())

    # do the decrypt
    cipher = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=0)  # 0 is DEC
    cipher.set_padding(padding=0)
    decKey = cipher.update(cf.cryptoKey)
    decKey = decKey + cipher.final()

    #print('DKEY        : %s' % str(codecs.encode(decKey,"hex")).upper())
    return decKey
示例#39
0
def Scrypt_excel(data):
    result=[]
    nrows=data.nrows
    ncolumns=data.ncols
    for i in range(1,20000):
        text=''
        for j in range(0,ncolumns):
            text+=str(data.cell(i,j).value)
            m = sc.hash(text.encode("utf-8"),"")
            m=int.from_bytes(m, byteorder='little', signed=True)
            result.append(m*10**(-152))
    return result
示例#40
0
def generate_key(password=''):
    if password == '':
        return Fernet.generate_key()

    if type(password) == bytes:
        password = password.decode('utf-8')

    password = password.encode('utf-8')

    key = scrypt.hash(password, salt='', N=2**16, r=8, p=1, buflen=32)
    key = base64.urlsafe_b64encode(key)
    return key
示例#41
0
    def hash_codename(self, codename, salt=None):
        """Salts and hashes a codename using scrypt.

        :param str codename: A source's codename.
        :param str salt: The salt to mix with the codename when hashing.
        :returns: A base32 encoded string; the salted codename hash.
        """
        if salt is None:
            salt = self.scrypt_id_pepper
        return b32encode(
            scrypt.hash(clean(codename), salt,
                        **self.scrypt_params)).decode('utf-8')
示例#42
0
    def hash_codename(self, codename: str, salt: Optional[str] = None) -> str:
        """Salts and hashes a codename using scrypt.

        :param codename: A source's codename.
        :param salt: The salt to mix with the codename when hashing.
        :returns: A base32 encoded string; the salted codename hash.
        """
        if salt is None:
            salt = self.scrypt_id_pepper
        _validate_name_for_diceware(codename)
        return b32encode(scrypt.hash(codename, salt,
                                     **self.scrypt_params)).decode('utf-8')
示例#43
0
def globalPass(flag=None):
    files_path = loc()
    #terminators call
    if flag == 1:
        try:
            with open(f'{files_path}/accman/data.yml', 'r') as d:
                y = yaml.safe_load(d)

            #check check
            globalPass = getpass('Please enter global password to proceed: ')
            try:
                with open(f'{files_path}/accman/data.yml', 'r') as d:
                    y = yaml.safe_load(d)
                    salt = y['GlobalSalt']
                #generate a key
                key = scrypt.hash(globalPass, salt, 2048, 8, 1, 32)
                key = base64.urlsafe_b64encode(key)

                with open(f'{files_path}/accman/data.yml', 'r') as d:
                    y = yaml.safe_load(d)
                    key2 = y['GlobalPassword']
                    key2 = str(key2).replace('{', '').replace('}', '')
            except TypeError:
                print(colored('\nFirst set up the global password!\n', 'red', attrs=['bold']))
                exit(0)
            #compare the keys
            if str(key) == str(key2):
                return True
            else:
                print(colored('\nInvalid global password!\n', 'red', attrs=['bold']))
                exit(0)
        except FileNotFoundError:
            print(colored('\nFirst set up the global password!\n', 'red', attrs=['bold']))
            exit(0)

    #writers call
    if flag == 0:
        try:
            with open(f'{files_path}/accman/data.yml', 'r') as d:
                y = yaml.safe_load(d)
                if 'GlobalPassword' in y:
                    return True
        except:#FileNotFoundError and TypeError
            globalPass = getpass('Enter the global password so that no one else can delete or modify your account information: ')
            key = keygen(None, globalPass)
            data = {
            'GlobalPassword':{key}
            }
            # save the key in information file
            encryptedFile = open(f'{files_path}/accman/data.yml', 'a')
            encryptedFile.write(yaml.safe_dump(data,  sort_keys=False))
            encryptedFile.close()
示例#44
0
def Script_txt(data):
    result=[]
    i=0
    while i<200000:
        text = data.readline()
        if not text:
            break
        m = sc.hash(text.encode("utf-8"),"")
        i+=1
        m = int.from_bytes(m, byteorder='little', signed=True)
        result.append(m * 10 ** (-152))
    data.close()
    return result
示例#45
0
def decrypt(encrypted_private_key, passphrase):
    bs58_decoded_pk = bs58_decode(encrypted_private_key)
    salt = bs58_decoded_pk[3:7]
    #scrypt_hash = scrypt.hash(passphrase, salt, N=n, r=r, p=p, buflen=l)
    scrypt_hash = scrypt.hash(passphrase, salt, N=16384, r=8, p=8, buflen=64)

    half1, half2 = scrypt_hash[:32], scrypt_hash[32:]
    pk_slice = bs58_decoded_pk[7:7 + 32]
    cipher = AES.new(key=half2, mode=AES.MODE_ECB)
    decipher = cipher.decrypt(pk_slice)

    decipher.setAutoPadding(false)
    print(decipher)
def generate_key_scrypt(uid, password):
    current_line = None
    my_dir = os.path.dirname(os.path.realpath(__file__)) + '/'

    with open(my_dir + 'scrypt_output.csv', 'r+') as f:
        while current_line != '':
            current_line = f.readline()
            if current_line.split(',')[0] == uid:
                print('Entry not added: UID already exists')
                return
        salt = os.urandom(64)
        digest = scrypt.hash(password, salt).hex()
        f.write(f'{uid},{digest},{salt}\n')
示例#47
0
文件: main.py 项目: ikeos2/-BudgetAPI
def signup():
    given_username = request.form['username']
    given_password = base64.b64encode(
        scrypt.hash(base64.b64encode(request.form['password']), 'random salt'))
    ins = User(username=given_username, passhash=given_password)

    try:
        Session.add(ins)
        Session.commit()
    except Exception as ex:
        return 'Something went wrong: ' + str(ex)

    return "done"
示例#48
0
def decryptDecodeScryptKey(cf, password):
    derived = scrypt.hash(password, cf.cryptoSalt, cf.N, cf.r, cf.p)

    key = derived[:KEY_LEN_BYTES]
    iv = derived[KEY_LEN_BYTES:]

    # do the decrypt
    cipher = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=0)  # 0 is DEC
    cipher.set_padding(padding=0)
    decKey = cipher.update(cf.cryptoKey)
    decKey = decKey + cipher.final()

    return decKey
示例#49
0
文件: views.py 项目: ItsTimmy/Voter
def hashemail(email):
    hashingconfig = CONFIG['emailHashing']
    n = 2**(int(hashingconfig['N']))
    r = int(hashingconfig['r'])
    p = int(hashingconfig['p'])
    buflen = int(hashingconfig['buflen'])
    return base64.b64encode(
        scrypt.hash(email,
                    CONFIG['emailHashing']['salt'],
                    N=n,
                    r=r,
                    p=p,
                    buflen=buflen), b'+_').decode('utf-8')
示例#50
0
def sscrypt(password, salt=None):
    """Returns a Salted-Scrypt password hash

    Args:
        password: password
        salt: salt to use. If none, one is generated

    """
    password = password.encode('utf8')
    if salt is None:
        salt = _gensalt()
    sscrypt = base64.b64encode(scrypt.hash(password, salt) + salt).strip()
    return "{SSCRYPT}%s" % sscrypt
示例#51
0
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)
示例#52
0
def CryptoScrypt():

         TimeEstimation()
         start = timer()
         
         global digest
         digest = scrypt.hash( keyx, saltx,N=args.iter ,r=args.blocksize, p=args.parallelism, buflen=args.size)
         
         end = timer()
         timex = (end - start)
         print("\n" + str(timex) + " seconds elapsed\n")
         print( "Key was : " + keyx +"\n")
         print( "salt was : " + saltx +"\n")
def reset_password2(code):
    password = request.form['password']
    connection = get_db()
    cursor = connection.cursor()
    cursor.execute("SELECT email FROM users WHERE verification_code = %s AND email_verified = True", (code,))
    rst = cursor.fetchone()
    email = rst[0]
    password_salt = str(uuid.uuid4()).replace("-","")
    password_hash = scrypt.hash(password, password_salt)
    cursor.execute("UPDATE users SET verification_code = %s, password_hash = %s, password_salt = %s, created_at = current_timestamp WHERE email = %s", (code, password_hash, password_salt, email))
    cursor.close()
    connection.commit()
    return '{success:true, message:"Password has been reset"}\n'
示例#54
0
def scrypt_crypto_footer(passwd, crypto_footer, length):
    '''
	Runs scrypt with the parameters stored in the crypto footer
	'''

    #The scrypt parameters
    N = 1 << crypto_footer['N_factor']
    r = 1 << crypto_footer['r_factor']
    p = 1 << crypto_footer['p_factor']
    print "N=%d" % N
    print "r=%d" % r
    print "p=%d" % p
    return scrypt.hash(passwd, crypto_footer['salt'], N, r, p, length)
示例#55
0
    def ExportNEP2(self, passphrase):
        """
        Export the encrypted private key in NEP-2 format.

        Args:
            passphrase (str): The password to encrypt the private key with, as unicode string

        Returns:
            str: The NEP-2 encrypted private key

        Raises:
            ValueError: if the input `passphrase` length is < 2
        """
        if len(passphrase) < 2:
            raise ValueError("Passphrase must have a minimum of 2 characters")

        # Hash address twice, then only use the first 4 bytes
        address_hash_tmp = hashlib.sha256(
            self.GetAddress().encode("utf-8")).digest()
        address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
        address_hash = address_hash_tmp2[:4]

        # Normalize password and run scrypt over it with the address_hash
        pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase),
                               'utf-8')
        derived = scrypt.hash(pwd_normalized,
                              address_hash,
                              N=SCRYPT_ITERATIONS,
                              r=SCRYPT_BLOCKSIZE,
                              p=SCRYPT_PARALLEL_FACTOR,
                              buflen=SCRYPT_KEY_LEN_BYTES)

        # Split the scrypt-result into two parts
        derived1 = derived[:32]
        derived2 = derived[32:]

        # Run XOR and encrypt the derived parts with AES
        xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
        cipher = AES.new(derived2, AES.MODE_ECB)
        encrypted = cipher.encrypt(xor_ed)

        # Assemble the final result
        assembled = bytearray()
        assembled.extend(NEP_HEADER)
        assembled.extend(NEP_FLAG)
        assembled.extend(address_hash)
        assembled.extend(encrypted)

        # Finally, encode with Base58Check
        encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
        return encrypted_key_nep2.decode("utf-8")
示例#56
0
文件: kdf.py 项目: superwow/zerodb
def key_from_cert(username, password, key_file, cert_file, appname, key):
    """
    Key is derived from SSL key_file.
    Password is securely hashed if given at all
    """
    with open(key_file) as f:
        key = hashlib.sha256(f.read().encode()).digest()

    if password is not None:
        salt = "|".join([username, appname, 'key'])
        password = scrypt.hash(password, salt, **scrypt_kw)
        password = hashlib.sha256(password + b'auth').digest()

    return password, key
示例#57
0
def keygen(name=None, passwrd=None):
    #generating key
    salt = os.urandom(16)
    passphrase = hashlib.sha256(salt)
    passphrase = passphrase.hexdigest()
    if passwrd == None:
        passphraseDict = {
            name:{
                'salt': passphrase
            }
        }
        passwd = getpass(prompt='this password will be used to encrypt account data, it will not be saved for security purposes: ')
        passwd = passwd.encode()
    elif passwrd != None:
        passphraseDict = {
            'GlobalSalt':passphrase
        }
        passwd = passwrd

    files_path = loc()
    try:
        #saving generated salt
        if passwrd != None:
            with open(f'{files_path}/accman/data.yml', 'r') as d:
                y = yaml.safe_load(d)
                y.update(passphraseDict)
                encryptedFile = open(f'{files_path}/accman/data.yml', 'w')
                encryptedFile.write(yaml.safe_dump(y,  sort_keys=False))
                encryptedFile.close()
        else:
            with open(f'{files_path}/accman/salt.yml', 'r') as d:
                y = yaml.safe_load(d)
                y.update(passphraseDict)
                encryptedFile = open(f'{files_path}/accman/salt.yml', 'w')
                encryptedFile.write(yaml.safe_dump(y,  sort_keys=False))
                encryptedFile.close()
    except:
        if passwrd != None:
            encryptedFile = open(f'{files_path}/accman/data.yml', 'w')
            encryptedFile.write(yaml.safe_dump(passphraseDict,  sort_keys=False))
            encryptedFile.close()
        else:
            encryptedFile = open(f'{files_path}/accman/salt.yml', 'w')
            encryptedFile.write(yaml.safe_dump(passphraseDict,  sort_keys=False))
            encryptedFile.close()

    #returning key
    key = scrypt.hash(passwd, passphrase, 2048, 8, 1, 32)
    key = base64.urlsafe_b64encode(key)
    return key
示例#58
0
    def get_ek(self, words: List[int]) -> bytes:
        """
        Returns the bytes constant used in the RecoverSecret loop
        It is passed into key_derivation

        returns  (s_1 * a_1) * (s_2 * a_2) * ... * (s_n * a_n) (mod p)
        """
        sList = self.extractor
        aList = words
        aList.sort()
        e: nmod = nmod(1, self.prime)
        for i in range(self.setSize):
            e *= sList[i] * aList[i]
        return scrypt.hash("key:" + str(e), self.salt)
示例#59
0
def warp(passphrase, salt=""):
    s1 = scrypt.hash(passphrase + "\x01",
                     salt + "\x01",
                     N=2**18,
                     r=8,
                     p=1,
                     buflen=32)
    s2 = pbkdf2(passphrase + "\x02",
                salt=salt + "\x02",
                keylen=32,
                rounds=2**16,
                prf="hmac-sha256")
    key = binascii.hexlify(xor(s1, s2))
    return key, bitcoin.pubtoaddr(bitcoin.privtopub(key))
示例#60
0
    def generate_hmac(self, key, message):
        """

        @param key: The user's generated password
        @type key: str
        @param message: message to hash for client-server authentication
        @type message: str
        @return: the hash based message auth code (to verify against the client sent one)
        @rtype: str
        @see: http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
        """

        if len(key) > self.__BLOCK_SIZE:
            salt = os.urandom(16).encode('base_64')
            key = scrypt.hash(key, salt)

        key += chr(0) * (self.__BLOCK_SIZE - len(key))
        o_key_pad = xor(self.__TRANS_5C, key)
        i_key_pad = xor(self.__TRANS_36, key)

        return scrypt.hash(
            o_key_pad + scrypt.hash(i_key_pad + message, self.__I_SALT),
            self.__O_SALT)