Example #1
0
def bip39_to_seed(mnemonic, passphrase):
    import pbkdf2, hashlib, hmac
    PBKDF2_ROUNDS = 2048
    mnemonic = normalize('NFKD', ' '.join(mnemonic.split()))
    passphrase = bip39_normalize_passphrase(passphrase)
    return pbkdf2.PBKDF2(mnemonic,
                         'mnemonic' + passphrase,
                         iterations=PBKDF2_ROUNDS,
                         macmodule=hmac,
                         digestmodule=hashlib.sha512).read(64)
Example #2
0
def register(username, password):
    db = cred_setup()
    if db.query(Cred).get(username):
        return None
    newcred = Cred()
    newcred.username = username
    salt = binascii.hexlify(os.urandom(SALT_LEN)).decode()
    newcred.password = pbkdf2.PBKDF2(password, salt).hexread(32)
    newcred.salt = salt
    db.add(newcred)
    return newtoken(db, newcred)
Example #3
0
 def mnemonic_to_seed(self, mnemonic, passphrase):
     # trezor uses bip39
     import pbkdf2, hashlib, hmac
     PBKDF2_ROUNDS = 2048
     mnemonic = unicodedata.normalize('NFKD', ' '.join(mnemonic.split()))
     passphrase = unicodedata.normalize('NFKD', passphrase)
     return pbkdf2.PBKDF2(mnemonic,
                          'mnemonic' + passphrase,
                          iterations=PBKDF2_ROUNDS,
                          macmodule=hmac,
                          digestmodule=hashlib.sha512).read(64)
Example #4
0
def encryption(p):
    password = "******"
    passwordSalt = os.urandom(16)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
    p1 = []
    p1.clear()
    iv = secrets.randbits(256)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(p)
    p1.append(ciphertext), p1.append(key), p1.append(iv)
    return p1
Example #5
0
def register(username, password):
    cred_db = cred_setup()
    newcred = Cred()
    newcred.username = username

    salt = os.urandom(16)
    newcred.password = pbkdf2.PBKDF2(password, salt).hexread(32)
    newcred.salt = salt
    cred_db.add(newcred)
    cred_db.commit()

    return newtoken(cred_db, newcred)
Example #6
0
def login(username, password):
    db_person = person_setup()
    person = db_person.query(Person).get(username)
    if not person:
        return None
    db_cred = cred_setup()
    cred = db_cred.query(Cred).get(username)
    password = pbkdf2.PBKDF2(password, cred.salt).hexread(32)
    if cred.password == password:
        return newtoken(db_cred, cred)
    else:
        return None
Example #7
0
def _encryption(p):
    password = "******"
    passwordSalt = os.urandom(16)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(16)

    m = []
    m.clear()
    iv = secrets.randbits(128)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(p)
    m.append(ciphertext), m.append(key), m.append(iv)
    return m
Example #8
0
def login(username, password):
    db = cred_setup()
    person = db.query(Cred).get(username)

    if not person:
        return None

    salt = person.salt
    password = pbkdf2.PBKDF2(password, salt).hexread(32)

    if person.password == password:
        return newtoken(db, person)
    else:
        return None
Example #9
0
def _encrypt_with_key(data, passphrase=''):
    """
    method for key-encryption, uses 24 bits keys, adds fillers in case its less.
    :param passphrase: user selected key
    :param data: data to encrypt
    :return: data encrypted, safe to save.
    """
    if passphrase is None:
        passphrase = ''
    # Generate machine specific key
    key = pbkdf2.PBKDF2(
        passphrase,
        platform.machine() + platform.processor() + str(get_mac())).read(24)
    k = pyDes.triple_des(key, pyDes.ECB, pad=None, padmode=pyDes.PAD_PKCS5)
    return k.encrypt(data).encode('string_escape').replace('\\\\', '\\')
Example #10
0
def _decrypt_with_key(data, passphrase=''):
    """
    uses key to decrypt data.
    :param data: data to decrypt
    :param passphrase: key used in encryption
    :return: decrypted data
    """
    data = data.decode('string_escape').replace('\\', '\\\\')
    if passphrase is None:
        passphrase = ''
    key = pbkdf2.PBKDF2(
        passphrase,
        platform.machine() + platform.processor() + str(get_mac())).read(24)
    k = pyDes.triple_des(key, pyDes.ECB, pad=None, padmode=pyDes.PAD_PKCS5)
    return k.decrypt(data)
Example #11
0
    def __init__(self, username, password):
        self.username = username
        self.salt = srp.long_to_bytes(srp.get_random(16))

        key = pbkdf2.PBKDF2(password, self.salt).read(64)
        self.authentication_key, self.initialization_key = (key[:32], key[32:])

        self.cipher = AESCipher(self.initialization_key)
        self.ecc_key = pyelliptic.ECC()

        self.keychain = {
            self.username: self.ecc_key.get_pubkey(),
        }

        self.ecc_group_key = {}
        self.group_keys = {}
Example #12
0
 def rpc_register(self, username, password):
     credDb = cred_setup()
     cred = credDb.query(Cred).get(username)
     if cred:
         return "Failure"
     bank_client.makeBank(username)
     string_client.makeString(username)
     newcred = Cred()
     salt = os.urandom(32)
     passwordHash = pbkdf2.PBKDF2(password, salt).hexread(32)
     newcred.username = username
     newcred.password = passwordHash
     newcred.salt = salt
     credDb.add(newcred)
     credDb.commit()
     return "Success"
Example #13
0
    def _make_keystore_json(self, password):
        """
        Generate the keystore json that follows the Version 3 specification:
        https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#definition

        Uses pbkdf2 for password encryption, and AES-128-CTR as the cipher.
        """
        # Get the hash function and default parameters
        kdfparams = {
            "prf": "hmac-sha256",
            "dklen": 32,
            "c": 262144,
            "salt": encode_hex(os.urandom(16)),
        }

        # Compute derived key
        derivedkey = pbkdf2.PBKDF2(password, decode_hex(kdfparams["salt"]),
                                   kdfparams["c"],
                                   SHA256).read(kdfparams["dklen"])

        # Produce the encryption key and encrypt using AES
        enckey = derivedkey[:16]
        cipherparams = {"iv": encode_hex(os.urandom(16))}
        iv = int.from_bytes(decode_hex(cipherparams["iv"]), byteorder="big")
        ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
        encryptor = AES.new(enckey, AES.MODE_CTR, counter=ctr)
        c = encryptor.encrypt(self.identity.key)

        # Compute the MAC
        mac = sha3(derivedkey[16:32] + c)

        # Return the keystore json
        return {
            "crypto": {
                "cipher": "aes-128-ctr",
                "ciphertext": encode_hex(c),
                "cipherparams": cipherparams,
                "kdf": "pbkdf2",
                "kdfparams": kdfparams,
                "mac": encode_hex(mac),
                "version": 1,
            },
            "id": self.uuid,
            "version": 3,
        }
Example #14
0
def register(username, password):
    db = person_setup()
    db2 = cred_setup()

    #db3 = bank_setup()

    person = db.query(Person).get(username)

    print "check_token 1"
    if person:
        return None

    #generates 64 bit salt
    salt = b64encode(os.urandom(8)).decode('utf-8')

    person = Person()
    person_for_cred = Cred()
    #person_for_bank = Bank()

    #print "check_token 2"

    #salt=unicode(salt)
    person_for_cred.salt = salt

    person.username = username
    person_for_cred.username = username
    #person_for_bank.username = username

    #print "check_token 3"

    password = pbkdf2.PBKDF2(password, salt).hexread(32)
    person_for_cred.password = password

    #print "check_token 4"

    db.add(person)
    db2.add(person_for_cred)
    #db3.add(person_for_bank)

    #print "before db commit"
    db.commit()
    db2.commit()
    #db3.commit()
    #print "after db commit"
    return newtoken(db2, person_for_cred)
Example #15
0
def register(username, password):
    cred_db = cred_setup()
    person_db = person_setup()
    if person_db.query(Person).get(username) or cred_db.query(Cred).get(
            username) or bank.register(username):
        return None
    newperson = Person()
    newperson.username = username
    person_db.add(newperson)
    person_db.commit()

    newcred = Cred()
    newcred.username = username
    newcred.salt = os.urandom(8).encode('hex')
    newcred.password = pbkdf2.PBKDF2(password, newcred.salt).hexread(32)
    cred_db.add(newcred)
    cred_db.commit()
    return newtoken(cred_db, newcred)
Example #16
0
def register(username, password):
    db = person_setup()
    db1 = cred_setup()
    person = db.query(Person).get(username)
    if person:
        return None
    newperson = Person()
    newcred = Cred()
    newcred.username = username
    newcred.salt = os.urandom(8).encode('base_64')
    newcred.password = pbkdf2.PBKDF2(password, newcred.salt).hexread(32)
    newperson.username = username
    db.add(newperson)
    db1.add(newcred)
    db1.commit()
    db.commit()
    bank_client.register(username)
    return newtoken(db1, newcred)
Example #17
0
def register(username, password):
    credDb = cred_setup()
    cred = credDb.query(Cred).get(username)
    if cred:
        return None
    newcred = Cred()
    salt = os.urandom(32)
    passwordHash = pbkdf2.PBKDF2(password, salt).hexread(32)
    newcred.username = username
    newcred.password = passwordHash
    newcred.salt = salt
    credDb.add(newcred)
    credDb.commit()
    personDb = person_setup()
    newperson = Person()
    newperson.username = username
    personDb.add(newperson)
    personDb.commit()
    return newtoken(credDb, newcred)
Example #18
0
def register(username, password):
    db = person_setup()
    db1 = cred_setup()
    person = db.query(Person).get(username)
    if person:
        return None
    newperson = Person()
    newcred = Cred()
    salt = os.urandom(5).decode("latin-1")
    password = unicode(pbkdf2.PBKDF2(password, salt).hexread(32))
    newperson.username = username
    newcred.password = password
    newcred.username = username
    newcred.salt = salt
    db.add(newperson)
    db1.add(newcred)
    db.commit()
    db1.commit()
    bank_client.register(username)
    return newtoken(db1, newcred)
Example #19
0
def register(username, password):
    db_person = person_setup()
    person = db_person.query(Person).get(username)
    if person:
        return None
    newperson = Person()
    newperson.username = username
    db_person.add(newperson)
    db_person.commit()

    salt = os.urandom(32).encode('hex')
    password = pbkdf2.PBKDF2(password, salt).hexread(32)
    db_cred = cred_setup()
    newcred = Cred()
    newcred.username = username
    newcred.password = password
    newcred.salt = salt
    db_cred.add(newcred)
    db_cred.commit()
    return newtoken(db_cred, newcred)
Example #20
0
def generator_key():

	global password

	passwordSalt = os.urandom(16)

	f = open("saltkeys.txt","r+")

	line = f.readline()

	while(len(line) > 0):
		if f.readline() == binascii.hexlify(passwordSalt).decode('latin-1'):
			generator_key()
		line = f.readline()

	key = pbkdf2.PBKDF2(password, passwordSalt).read(16)

	s = passwordSalt
	f.writelines((binascii.hexlify(passwordSalt).decode('latin-1'))+"\n")

	return key
Example #21
0
def new_entry(user, credentials):
    '''Create new entry in db'''

    account = input("\nIngrese su nueva aplicacion: ")

    hmac_acct = hmac_sha_256.encrypt(account)

    # Verify if acct exists allready
    if (existing_account(user['accounts'], hmac_acct)):
        error_msg("La cuenta que desea agregar ya existe.")
    else:
        acct_id = str(uuid.uuid4())
        # Pseudorandom Salt
        salt = pbkdf2._makesalt()
        # PBKDF2 Autogenerated pssword
        pbkdf2_password = pbkdf2.PBKDF2(MASTER_KEY, salt, 1200).hexread(32)

        # AES-GCM Password Encription
        encrypted_pbkdf2_password, nonce = aes_gcm.encrypt_pbkdf2_password(
            pbkdf2_password, credentials['key'])

        # New Acct Dictionary
        new_acct = {}
        new_acct.update(
            dict(acct_id=acct_id,
                 app=hmac_acct,
                 password=encrypted_pbkdf2_password,
                 nonce=nonce))

        user['accounts'][acct_id] = new_acct

        user = save_user(user)

        success_msg(
            'Se a guardado su cuenta de la aplicacion {}'.format(account))

    return user
Example #22
0
def register(username, password):
    print "auth register"
    db = cred_setup()
    cred = db.query(Cred).get(username)
    if cred:
        return None
    newcred = Cred()
    newcred.username = username
    salt = os.urandom(16).encode('base_64')
    newcred.password = pbkdf2.PBKDF2(password, salt).hexread(32)
    newcred.salt = salt
    db.add(newcred)
    db.commit()

    # TODO: register bank account to user
    bank.register(username)

    newperson = Person()
    newperson.username = username
    ndb = person_setup()
    ndb.add(newperson)
    ndb.commit()

    return newtoken(db, newcred)
Example #23
0
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 #24
0
 def mnemonic_to_seed(self, mnemonic, passphrase):
     PBKDF2_ROUNDS = 2048
     mnemonic = normalize_text(mnemonic)
     passphrase = normalize_text(passphrase)
     return pbkdf2.PBKDF2(mnemonic, 'electrum' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
 def stretch_key(self, key):
     import pbkdf2, hmac
     return pbkdf2.PBKDF2(key, 'Digital Bitbox', iterations = 20480, macmodule = hmac, digestmodule = hashlib.sha512).read(64).encode('hex')
Example #26
0
 def make_key(cls, username, password, key_iteration_count):
     if key_iteration_count == 1:
         return hashlib.sha256(username.encode() + password.encode()).digest()
     else:
         p = pbkdf2.PBKDF2(password, username, iterations=key_iteration_count, digestmodule=SHA256)
         return p.read(32)
Example #27
0
 def get_key(self, password):
     secret = pbkdf2.PBKDF2(password, '', iterations = 1024, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
     ec_key = bitcoin.EC_KEY(secret)
     return ec_key
Example #28
0
 def get_eckey_from_password(password):
     secret = pbkdf2.PBKDF2(password, '', iterations=1024, macmodule=hmac, digestmodule=hashlib.sha512).read(64)
     ec_key = ecc.ECPrivkey.from_arbitrary_size_secret(secret)
     return ec_key
Example #29
0
 def getKey(self):  #generating key with PBKDF2 for AES
     password = "******"
     passwordSalt = '76895'
     key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
     return key
Example #30
0
import os, binascii, pbkdf2, secrets, pyaes

# Derive a 256-bit AES encryption key from the password
password = '******'
passwordSalt = os.urandom(16)
key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
print('AES encryption Key : ', binascii.hexlify(key))

# Encrypt the plaintext with the given key
#  ciphertext = AES-256-CTR-Encrypt(plaintext, key, iv)
# iv = secrets.randbits(256)
iv = os.urandom(16)
plaintext = 'plain text111111'
# aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
aes = pyaes.AESModeOfOperationCBC(key, iv)
ciphertext = aes.encrypt(plaintext)
print('Ciphertext : ', binascii.hexlify(ciphertext))

# Decrypt the ciphertext with the given key
#  plaintext = AES-256-CTR-Decrypt(ciphertext, key, iv)
# aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
aes = pyaes.AESModeOfOperationCBC(key, iv)
decryptedtext = aes.decrypt(ciphertext)
print('Decrypted : ', decryptedtext)