Exemplo n.º 1
0
 def derive_key(user_password, salt):
     return pyscrypt.hash(password=user_password.encode(),
                          salt=salt.encode(),
                          N=16384,
                          r=8,
                          p=1,
                          dkLen=190)
Exemplo n.º 2
0
def bip38_encrypt_privkey(password, privkey, compressFlag=False, **kwargs):
    network = kwargs.get("network", "btc")
    if re.match("^[5KL9c][1-9a-km-zA-LMNP-Z]{50,51}$", privkey):
        compressFlag = "compressed" in get_privkey_format(privkey)
        network = "testnet" if privkey[0] in "9c" else "btc"
        privkey = encode_privkey(decode_privkey(privkey), "hex_compressed" if compressFlag else "hex")
    elif re.match("^[0-9a-f]{64}(01)?$", privkey):
        compressFlag = (len(privkey) == 66 and privkey[-2:] == "01")
    elif len(privkey) in (32, 33):
        privkey = binascii.hexlify(privkey)
    btcprivkey = binascii.unhexlify(privkey)            # 32 byte hex string (no trailing "01")
    
    pubkey = privtopub(privkey)
    addr = privtoaddr(privkey, 111 if network == "testnet" else 0)
    
    pwd = str(unicodedata.normalize("NFC", unicode(password)))
    addrhash = bin_dbl_sha256(addr)[:4]
    scrypthash = pyscrypt.hash(password=pwd, salt=addrhash, N=16384, r=8, p=8, dkLen=64)
    derivedhalf1, derivedhalf2 = scrypthash[:32], scrypthash[32:]
    block1 = strxor(btcprivkey[:16], derivedhalf1[:16])
    block2 = strxor(btcprivkey[16:], derivedhalf1[16:])
    key = derivedhalf2
    encryptedhalf1 = aes_encrypt_bip38(block1, key)
    encryptedhalf2 = aes_encrypt_bip38(block2, key)
    
    prefix = '\x01\x42'             # Do not use EC multiplication
    flagbyte = 0b11000000           # 192
    if compressFlag:
        flagbyte = flagbyte + 0x20  # 224
    flagbyte = encode(flagbyte, 256, 1)
    
    res = prefix + flagbyte + addrhash + encryptedhalf1 + encryptedhalf2
    b58 = bin_to_b58check(res)    # 16PRN7XmtPiu8pHRQGW2DSGrHYLKhb1ny144SnAomjZ9ySY4QcfKenoqXYB
    return b58[1:]                #. 6PRN7XmtPiu8pHRQGW2DSGrHYLKhb1ny144SnAomjZ9ySY4QcfKenoqXYB
Exemplo n.º 3
0
    def test_demo_user_keys(self):
        sk_base58 = b"29oiwbqkhLGBuX5teL5d2vsiJ3EXk3dpyBiPwA7W9DJG"
        sk_decoded = base58.b58decode(sk_base58)
        hash = pyscrypt.hash(password=b"demouser",
                             salt=b"demouser",
                             N=1024,
                             r=1,
                             p=1,
                             dkLen=32)

        sk = base58.b58encode(hash)
        hex_sk = binascii.b2a_hex(hash)
        print('Secret Key:', sk, 'length: ', len(sk))
        self.assertEqual(sk_base58, sk)
        self.assertEqual(sk_decoded, hash)

        #print(sk)
        keypair = libnacl.public.SecretKey(hash)

        # 2ipFYsqXnrw4Mt2RUWzEQntAH1FEFB8R52rAT3eExn9S
        pk_base58 = base58.b58encode(keypair.pk)
        pk_decoded = base58.b58decode(pk_base58)

        self.assertEqual(pk_decoded, keypair.pk)
        print('Public Key:', pk_base58, 'length: ', len(pk_base58))

        print("XID: ", crypto.key_to_xid(keypair.pk))
Exemplo n.º 4
0
    def test_demo_user_keys(self):
        sk_base58 = b"29oiwbqkhLGBuX5teL5d2vsiJ3EXk3dpyBiPwA7W9DJG"
        sk_decoded = base58.b58decode(sk_base58)
        hash = pyscrypt.hash(password=b"demouser",
                             salt=b"demouser",
                             N=1024,
                             r=1,
                             p=1,
                             dkLen=32)

        sk = base58.b58encode(hash)
        hex_sk = binascii.b2a_hex(hash)
        print('Secret Key:', sk, 'length: ', len(sk))
        self.assertEqual(sk_base58, sk)
        self.assertEqual(sk_decoded, hash)

        #print(sk)
        keypair = libnacl.public.SecretKey(hash)

        # 2ipFYsqXnrw4Mt2RUWzEQntAH1FEFB8R52rAT3eExn9S
        pk_base58 = base58.b58encode(keypair.pk)
        pk_decoded = base58.b58decode(pk_base58)

        self.assertEqual(pk_decoded, keypair.pk)
        print('Public Key:', pk_base58, 'length: ', len(pk_base58))

        print("XID: ", crypto.key_to_xid(keypair.pk))
Exemplo n.º 5
0
def key_from_paswd(password):
    N = 2048
    r = 1
    p = 1
    key = pyscrypt.hash(password.encode('utf-8'), SALT, N, r, p, 32)
    print("calling key")
    return key
Exemplo n.º 6
0
 def _scrypt(password, salt, N, r, p, dkLen):
     password = to_bytes(password)
     salt = to_bytes(salt)
     if Bip38Key.isFast():
         if __class__._scrypt_1:
             return __class__._scrypt_1(password=password,
                                        salt=salt,
                                        n=N,
                                        r=r,
                                        p=p,
                                        dklen=dkLen)
         elif __class__._scrypt_2:
             return __class__._scrypt_2(password=password,
                                        salt=salt,
                                        N=N,
                                        r=r,
                                        p=p,
                                        key_len=dkLen)
         raise RuntimeError(
             "INTERNAL ERROR -- neither _scrypt_1 or _scrypt_2 are defined, but isFast()==True... FIXME!"
         )
     try:
         import pyscrypt
     except ImportError:
         raise Bip38Key.Error(
             "We lack a module to decrypt BIP38 Keys.  Install either: Cryptodome (fast), Python + OpenSSL 1.1 (fast), or pyscrypt (slow)"
         )
     print_error("[{}] using slow pyscrypt.hash... :(".format(
         __class__.__name__))
     return pyscrypt.hash(password=password,
                          salt=salt,
                          N=N,
                          r=r,
                          p=p,
                          dkLen=dkLen)
Exemplo n.º 7
0
    def __init__(self,
                 p_key,
                 p_encoding="utf-8",
                 p_backend=CryptorBackend.AES):
        try:
            self.v_encoding = p_encoding

            if p_backend == CryptorBackend.AES:
                self.v_hash = pyscrypt.hash(
                    password=p_key.encode("utf-8"),
                    salt="0123456789ABCDEF".encode("utf-8"),
                    N=1024,
                    r=1,
                    p=1,
                    dkLen=32,
                )
            elif p_backend == CryptorBackend.CRYPTOGRAPHY:
                if len(p_key) != 32:
                    raise Exception(
                        'p_key parameter must be exactaly 32 characters length while using "cryptography" backend'
                    )

                self.v_hash = base64.urlsafe_b64encode(p_key.encode("utf-8"))
            else:
                raise Exception("Unrecognized cryptor backend")

            self.v_backend = p_backend
        except Exception as exc:
            raise Spartacus.Utils.Exception(str(exc))
Exemplo n.º 8
0
def bip38_encrypt_privkey(password, privkey, compressFlag=False, **kwargs):
    network = kwargs.get("network", "btc")
    if re.match("^[5KL9c][1-9a-km-zA-LMNP-Z]{50,51}$", privkey):
        compressFlag = "compressed" in get_privkey_format(privkey)
        network = "testnet" if privkey[0] in "9c" else "btc"
        privkey = encode_privkey(decode_privkey(privkey), "hex_compressed" if compressFlag else "hex")
    elif re.match("^[0-9a-f]{64}(01)?$", privkey):
        compressFlag = (len(privkey) == 66 and privkey[-2:] == "01")
    elif len(privkey) in (32, 33):
        privkey = binascii.hexlify(privkey)
    btcprivkey = binascii.unhexlify(privkey)            # 32 byte hex string (no trailing "01")
    
    pubkey = privtopub(privkey)
    addr = privtoaddr(privkey, 111 if network == "testnet" else 0)
    
    pwd = str(unicodedata.normalize("NFC", unicode(password)))
    addrhash = bin_dbl_sha256(addr)[:4]
    scrypthash = pyscrypt.hash(password=pwd, salt=addrhash, N=16384, r=8, p=8, dkLen=64)
    derivedhalf1, derivedhalf2 = scrypthash[:32], scrypthash[32:]
    block1 = strxor(btcprivkey[:16], derivedhalf1[:16])
    block2 = strxor(btcprivkey[16:], derivedhalf1[16:])
    key = derivedhalf2
    encryptedhalf1 = aes_encrypt_bip38(block1, key)
    encryptedhalf2 = aes_encrypt_bip38(block2, key)
    
    prefix = '\x01\x42'             # Do not use EC multiplication
    flagbyte = 0b11000000           # 192
    if compressFlag:
        flagbyte = flagbyte + 0x20  # 224
    flagbyte = encode(flagbyte, 256, 1)
    
    res = prefix + flagbyte + addrhash + encryptedhalf1 + encryptedhalf2
    b58 = bin_to_b58check(res)    # 16PRN7XmtPiu8pHRQGW2DSGrHYLKhb1ny144SnAomjZ9ySY4QcfKenoqXYB
    return b58[1:]                #. 6PRN7XmtPiu8pHRQGW2DSGrHYLKhb1ny144SnAomjZ9ySY4QcfKenoqXYB
Exemplo n.º 9
0
def get_key_and_iv(passphrase, salt):
    global FOOTER
    keyiv = pyscrypt.hash(password = passphrase, salt = salt, N = FOOTER.scrypt_N, r = FOOTER.scrypt_r, p = FOOTER.scrypt_p, dkLen = 32)
#    keyiv = pbkdf2_bin(passphrase, salt,
 #                      iterations = HASH_COUNT, keylen = 32)
    key = keyiv[0:KEY_LEN_BYTES]
    iv = keyiv[KEY_LEN_BYTES:IV_LEN_BYTES+KEY_LEN_BYTES]
    return key, iv
Exemplo n.º 10
0
def GenerateEncKey(passwd, salt):
    enc_key=pyscrypt.hash(password=passwd,
        salt = salt,
        N=Scrypt_N,
        r=Scrypt_r,
        p=Scrypt_p,
        dkLen=KeySize)
    return enc_key
Exemplo n.º 11
0
def generate(master_password, keyword, cost=2048, oLen=32):
    hashed = pyscrypt.hash(password=master_password.encode(),
                           salt=keyword.encode(),
                           N=cost,
                           r=1,
                           p=1,
                           dkLen=32)
    return codecs.encode(hashed, 'hex').decode('utf-8')[0:oLen]
Exemplo n.º 12
0
def encrypt_data(user_password, salt, data):
    """
    Encrypt the data and store it in form of [IV,TAG,CIPHER].
    """
    key = pyscrypt.hash(password = user_password.encode(encoding='UTF-8'), salt = salt.encode(encoding='UTF-8'), N = 1024, r = 1, p = 1, dkLen = 32)
    iv = os.urandom(12)
    ret = encrypt.encrypt(key, iv, data)
    return b''.join([iv, ret["tag"], ret["cipher"]])
Exemplo n.º 13
0
def GenerateEncKey(passwd, salt):
    enc_key = pyscrypt.hash(password=passwd,
                            salt=salt,
                            N=Scrypt_N,
                            r=Scrypt_r,
                            p=Scrypt_p,
                            dkLen=KeySize)
    return enc_key
Exemplo n.º 14
0
def generate(master_password, keyword, cost=2048, oLen=32):
    hashed = pyscrypt.hash(password=master_password,
                           salt=keyword,
                           N=cost,
                           r=1,
                           p=1,
                           dkLen=32)
    return hashed.encode('hex')[0:oLen]
Exemplo n.º 15
0
def decrypt(ciphertxt):
    """
    Decrypt credentails
    """
    hashed = pyscrypt.hash(PHRASE, SALT, 1024, 1, 1, 16)
    key = hashed.encode('hex')
    aes = pyaes.AESModeOfOperationCTR(key)
    cleartxt = aes.decrypt(ciphertxt.decode('hex'))
    return cleartxt
Exemplo n.º 16
0
def decrypt_data(user_password, salt, iv, tag, data):
    """
    Decrypt the data in form of [IV,TAG,CIPHER].

    Raise exception when failed to decrypt file.
    """
    key = pyscrypt.hash(password = user_password.encode(encoding='UTF-8'), salt = salt.encode(encoding='UTF-8'), N = 1024, r = 1, p = 1, dkLen = 32)
    ret = encrypt.decrypt(key, iv, tag, data)
    return ret
Exemplo n.º 17
0
def generate(master_password, keyword, cost=2048, oLen=32):
    hashed = pyscrypt.hash (
        password = master_password,
        salt = keyword,
        N = cost,
        r = 1,
        p = 1,
        dkLen = 32
    )
    return hashed.encode('hex')[0:oLen]
Exemplo n.º 18
0
def generate(master_password, keyword, cost=2048, oLen=32):
    hashed = pyscrypt.hash (
        password = master_password.encode('utf-8'),
        salt = keyword.encode('utf-8'),
        N = cost,
        r = 1,
        p = 1,
        dkLen = 32
    )
    return codecs.encode(hashed, 'hex').decode('utf-8')[0:oLen]
def gen_key(password):
    """Derives a key from input string using SCrypt and returns it hex encoded."""
    hashed = pyscrypt.hash(password=password,
                           salt="2df2e24c76d4d7b37e7ffcdf787e426b",
                           N=16384,
                           r=8,
                           p=1,
                           dkLen=16)

    return hashed.encode('hex')
Exemplo n.º 20
0
def scrypt(text):
    hashed = pyscrypt.hash(password=bytes(text, encoding='utf-8'),
                           salt=b'seasalt',
                           N=1024,
                           r=1,
                           p=1,
                           dkLen=32)
    return hashed[
        2:
        -1]  # обрезаем готовый Scrypt хэш для того, чтобы избаиться от 'b', " ' " перед конвертацией в hex
Exemplo n.º 21
0
 def __GetPBK(self, pin):
     salt = AddonSettings.GetClientId()
     pbk = pyscrypt.hash(password=pin,
                         salt=salt,
                         N=2 ** 7,  # should be so that Raspberry Pi can handle it
                         # N=1024,
                         r=1,
                         p=1,
                         dkLen=32)
     Logger.Trace("Generated PBK with MD5: %s", hashlib.md5(pbk).hexdigest())
     return pbk
Exemplo n.º 22
0
def hashPassword(password: str) -> str:
    encrypted = pyscrypt.hash(password=toBytes(password),
                              salt=toBytes("salt"),
                              N=128,
                              r=1,
                              p=1,
                              dkLen=256)
    dpr("encrypted=%r:%s", encrypted, type(encrypted))
    hx = toHex(encrypted)
    dpr("hx=%r:%s", hx, type(hx))
    return hx
Exemplo n.º 23
0
def password_hash(plainpassword, passwordsalt):
    """
    Imitate code which receives the password and pepper then
    continous to hash them securely using a per user salt and a sound algorithm
    """
    hashed = pyscrypt.hash(password=plainpassword,
                           salt=passwordsalt,
                           N=1024,
                           r=1,
                           p=1,
                           dkLen=64)
    return hashed.encode('hex')
Exemplo n.º 24
0
 def __init__(self, p_key, p_encoding='utf-8'):
     try:
         self.v_encoding = p_encoding
         self.v_hash = pyscrypt.hash(
             password=p_key.encode('utf-8'),
             salt='0123456789ABCDEF'.encode('utf-8'),
             N=1024,
             r=1,
             p=1,
             dkLen=32)
     except Exception as exc:
         raise Spartacus.Utils.Exception(str(exc))
Exemplo n.º 25
0
def derive_secret_key(password, salt):
    if isinstance(password, unicode):
        password = password.encode('utf-8')
    if isinstance(salt, unicode):
        salt = salt.encode('utf-8')

    sk = pyscrypt.hash(password=password,
                       salt=salt,
                       N=1024,
                       r=1,
                       p=1,
                       dkLen=32)
    return sk
Exemplo n.º 26
0
 def _calculate_block_hash(self):
     """
     :return: scrypt hash
     :rtype: str
     """
     header = self.block_header.to_hashable()
     hash_object = pyscrypt.hash(password=header,
                                 salt=header,
                                 N=1024,
                                 r=1,
                                 p=1,
                                 dkLen=32)
     return hash_object.encode('hex')
Exemplo n.º 27
0
 def __init__(self, p_key, p_encoding='utf-8'):
     try:
         self.v_encoding = p_encoding
         self.v_hash = pyscrypt.hash(
             password = p_key.encode('utf-8'),
             salt = '0123456789ABCDEF'.encode('utf-8'),
             N = 1024,
             r = 1,
             p = 1,
             dkLen = 32
         )
     except Exception as exc:
         raise Spartacus.Utils.Exception(str(exc))
Exemplo n.º 28
0
def verifyPassword(hashedPassword, guessedPassword):
    encrypted = pyscrypt.hash(password=toBytes(guessedPassword),
                              salt=toBytes("salt"),
                              N=128,
                              r=1,
                              p=1,
                              dkLen=256)
    dpr("encrypted=%r:%s", encrypted, type(encrypted))
    hx = toHex(encrypted)
    dpr("hx=%r:%s", hx, type(hx))
    ok = (hx == hashedPassword)
    dpr("hashedPassword=%r ok=%r", hashedPassword, ok)
    return ok
Exemplo n.º 29
0
 def hash(self):
     """
     :return: scrypt hash
     :rtype: str
     """
     hashable = self.to_hashable().encode('utf-8')
     hash_object = pyscrypt.hash(password=hashable,
                                 salt=hashable,
                                 N=1024,
                                 r=1,
                                 p=1,
                                 dkLen=32)
     return codecs.encode(hash_object, 'hex').decode('utf-8')
Exemplo n.º 30
0
 def verify(self, widget):
     start = op.join(self.path, 'transform', 'start.hyde')
     if op.exists(start):
         with open(start, 'rb') as f:
             dec = f.read()
         key32 = ps.hash(self.app.pas1, self.app.pas2, 1024, 1, 1, 32)
         aes = vial.Vial(key32)
         start_ctr = op.join(self.path, 'transform', 'start.ctr')
         dec = aes.decrypt(dec, start_ctr)
         try:
             widget.text = dec.decode('utf-8')
         except Exception as e:
             widget.text = '<Unable to decrypt>'
             print(e)  # to logger
Exemplo n.º 31
0
def generate_sec_key():  
                                       
#     key = Fernet.generate_key()                            #generate key using Fernet class         
    password = getpass.getpass()                                    
    hashed = pyscrypt.hash(password = userMesgToBytes(password), 
                       salt = b"seasalt", 
                       N = 1024, 
                       r = 1, 
                       p = 1, 
                       dkLen = 32) 
    if len(sys.argv)>1:
        if sys.argv[1]==list_of_args[3]:
            print(str(hashed)[2:-1])
    return(str(hashed)[2:-1])
Exemplo n.º 32
0
def decrypt(nonce, header, tag, chpw, mstr, slt):

    # Decode results from Base64 to bytes
    nonce = base64.b64decode(nonce.encode('utf-8'))
    header = base64.b64decode(header.encode('utf-8'))
    tag = base64.b64decode(tag.encode('utf-8'))
    chpw = base64.b64decode(chpw.encode('utf-8'))

    # Password Key Derivation Function with master and second factor password
    key = pyscrypt.hash(mstr, slt, 8192, 8, 1, 32)

    ch = ChaCha20_Poly1305.new(key=key, nonce=nonce)
    ch.update(header)
    enpw = ch.decrypt_and_verify(chpw, tag)

    return enpw
Exemplo n.º 33
0
def derive_secret_key(password=None, salt=None):
    """
    Derives secret key from password and salt combination with Scrypt.

    :param password:
    :param salt:
    :return:
    """
    hash = pyscrypt.hash(password=password,
                         salt=salt,
                         N=1024,
                         r=1,
                         p=1,
                         dkLen=32)

    return hash
Exemplo n.º 34
0
def derive_secret_key(password=None, salt=None):
    """
    Derives secret key from password and salt combination with Scrypt.

    :param password:
    :param salt:
    :return:
    """
    hash = pyscrypt.hash(password=password,
                         salt=salt,
                         N=1024,
                         r=1,
                         p=1,
                         dkLen=32)

    return hash
Exemplo n.º 35
0
    def hyde(self, target=None):
        self.buttons(True)
        target = self.default_target if target is None else target
        if self.app.flist == []:
            self.buttons()
            return
        flist = self.app.flist
        key32 = ps.hash(self.app.pas1, self.app.pas2, 1024, 1, 1, 32)
        aes = vial.Vial(key32)
        for child in self.scr.ids.filelist.children:
            child.children[1].disabled = True
        for item in flist:
            children = self.scr.ids.filelist.children
            i = ntpath.basename(item)
            fin = open(item, 'rb')
            if isinstance(target, (ListProperty, list)):
                target = target[0]
            fout = open(op.join(target, i), 'wb')
            if op.join('transform', 'dr') not in item:
                aes.encrypt_stream(fin, fout)
            else:
                aes.decrypt_stream(fin, fout)
            fin.close()
            fout.close()
            for child in children:
                if i in child.children[0].children[0].text:
                    self.scr.ids.filelist.remove_widget(child)
                    self.app.flist.remove(item)

        # if Thread ends en(de)crypting too soon, this recursion ensures that
        # all files left in 'flist' i.e. even files that could be broken
        # are en(de)crypted properly, because Thread always fails before
        # removing file from 'flist' i.e. during encryption
        if self.app.flist != []:
            if target == op.join(self.path, 'transform', 'dr'):
                self.scr.hyde()
            else:
                self.scr.hyde(target)
        else:
            self.buttons()
            p1 = partial(self.update, self.upl_screens[0])
            p2 = partial(self.update, self.upl_screens[1])
            Clock.schedule_once(p1)
            Clock.schedule_once(p2)
Exemplo n.º 36
0
def encrypt(pw, mstr, slt):
    header = b"header"
    pw = pw.encode('utf-8')

    # Password Key Derivation Function with master and second factor password
    key = pyscrypt.hash(mstr, slt, 8192, 8, 1, 32)

    ch = ChaCha20_Poly1305.new(key=key)
    ch.update(header)
    chpw, tag = ch.encrypt_and_digest(pw)

    # Encode results from bytes to Base64
    nonce = base64.b64encode(ch.nonce).decode('utf-8')
    header = base64.b64encode(header).decode('utf-8')
    tag = base64.b64encode(tag).decode('utf-8')
    chpw = base64.b64encode(chpw).decode('utf-8')

    # Return nonce, header, tag and encrypted password
    return nonce, header, tag, chpw
Exemplo n.º 37
0
    def __get_pbk(self, pin):
        """ Gets the Password Based Key (PBK) based on the PIN.

        :param str pin: The pin for the key.

        :return: The PBK
        :rtype: bytes

        """

        salt = AddonSettings.get_client_id()
        pbk = pyscrypt.hash(password=pin if PY2 else pin.encode(),
                            salt=salt if PY2 else salt.encode(),
                            N=2 ** 7,  # should be so that Raspberry Pi can handle it
                            # N=1024,
                            r=1,
                            p=1,
                            dkLen=32)
        Logger.trace("Generated PBK with MD5: %s", hashlib.md5(pbk).hexdigest())
        return pbk
Exemplo n.º 38
0
    def encrypt(self, data: bytes, passphrase: bytes) -> CryptoJSON:

        # scrypt
        salt = os.urandom(CryptoJSON.ScryptDKLen)
        derived_key = pyscrypt.hash(passphrase, salt,
                                    CryptoJSON.StandardScryptN,
                                    CryptoJSON.StandardScryptR,
                                    CryptoJSON.StandardScryptP,
                                    CryptoJSON.ScryptDKLen)
        encrypt_key = derived_key[0:16]

        # AEC encrypt
        iv = os.urandom(16)
        ctr = Counter.new(128, initial_value=int_of_string(iv))
        aes = AES.new(encrypt_key, AES.MODE_CTR, counter=ctr)
        crypted_str = aes.encrypt(data)

        # sha3256
        mac_derived_key = derived_key[16:32]
        mac = Hash.sha3256(mac_derived_key, crypted_str, iv,
                           bytes(CryptoJSON.CIPHERNAME.encode("utf-8")))

        # generate crypto_json
        cipher_params = CryptoJSON.CipherParams()
        cipher_params.iv = base64.b16encode(iv).lower()
        scrypt_params = CryptoJSON.ScryptParams()
        scrypt_params.n = CryptoJSON.StandardScryptN
        scrypt_params.r = CryptoJSON.StandardScryptR
        scrypt_params.p = CryptoJSON.StandardScryptP
        scrypt_params.dklen = CryptoJSON.ScryptDKLen
        scrypt_params.salt = base64.b16encode(salt).lower()
        crypto_json = CryptoJSON()
        crypto_json.cipher = CryptoJSON.CIPHERNAME
        crypto_json.ciphertext = base64.b16encode(crypted_str).lower()
        crypto_json.cipherparams = cipher_params
        crypto_json.kdf = CryptoJSON.ScryptKDF
        crypto_json.kdfparams = scrypt_params
        crypto_json.mac = base64.b16encode(mac).lower()
        crypto_json.machash = CryptoJSON.MACHASH
        return crypto_json
Exemplo n.º 39
0
 def check(self, button):
     if not op.exists(op.join(self.path, '._')):
         return
     pas1 = self.ids.pas1.text.encode('utf-8')
     pas2 = self.ids.pas2.text.encode('utf-8')
     pas = ps.hash(pas1, self.app.mid.encode('utf-8'), 1024, 1, 1, 32)
     if self.phase == 1:
         self.ids.pas1.text = ''
         with open(op.join(self.path, '._'), 'rb') as f:
             h = f.read()
         if pas not in h:
             if len(h) < 36:
                 self.ids.log.text += '\nWrong password!'
                 with open(op.join(self.path, '._'), 'ab') as f:
                     f.write(b'x')
             else:
                 if not self.deleting:
                     self.deleting = True
                     Thread(target=self.delete).start()
                     self.ids.log.text = ('\nPerfect! Now you\'ve '
                                          'deleted all your data.')
             return
         else:
             with open(op.join(self.path, '._'), 'wb') as f:
                 f.write(pas)
             self.ids.labtitle.text = 'Mr. Hyde'
             button.text = 'Enter!'
             self.ids.pas2.disabled = False
             self.phase += 1
         self.ids.pas1.focus = True
     elif self.phase == 2:
         self.app.pas1 = pas1
         self.app.pas2 = pas2
         self.ids.pas1.text = ''
         self.ids.pas2.text = ''
         self.ids.log.text = ''
         self.app.lab.verify(self.app.lab.ids.verify)
         self.app.lab.ids.content.current = 'verify'
         self.manager.current = 'laboratory'
Exemplo n.º 40
0
 def __init__(self, p_key, p_encoding="utf-8"):
     try:
         self.v_encoding = p_encoding
         if v_use_scrypt:
             self.v_hash = scrypt.hash(
                 password=p_key.encode("utf-8"),
                 salt="0123456789ABCDEF".encode("utf-8"),
                 N=1024,
                 r=1,
                 p=1,
             )[:32]
         else:
             self.v_hash = pyscrypt.hash(
                 password=p_key.encode("utf-8"),
                 salt="0123456789ABCDEF".encode("utf-8"),
                 N=1024,
                 r=1,
                 p=1,
                 dkLen=32,
             )
     except Exception as exc:
         raise Spartacus.Utils.Exception(str(exc))
Exemplo n.º 41
0
    def decrypt(self,
                crypto_json: CryptoJSON,
                passphrase: bytes,
                version: int = 4) -> bytes:  #todo v3 match

        # check kdf&cipher
        if CryptoJSON.CIPHERNAME != crypto_json.cipher.lower():
            raise Exception("invalid cipher")
        if CryptoJSON.ScryptKDF != crypto_json.kdf.lower():
            raise Exception("kdf not support")

        # scrypt
        mac = base64.b16decode(crypto_json.mac, True)
        iv = base64.b16decode(crypto_json.cipherparams.iv, True)
        cipher_text = base64.b16decode(crypto_json.ciphertext, True)
        salt = base64.b16decode(crypto_json.kdfparams.salt, True)
        dklen = crypto_json.kdfparams.dklen
        n = crypto_json.kdfparams.n
        r = crypto_json.kdfparams.r
        p = crypto_json.kdfparams.p
        derived_key = pyscrypt.hash(passphrase, salt, n, r, p, dklen)
        mac_derived_key = derived_key[16:32]

        # sha3256
        if version == 4:
            cal_mac = Hash.sha3256(mac_derived_key, cipher_text, iv,
                                   bytes(crypto_json.cipher.encode("utf-8")))
        elif version == 3:
            cal_mac = Hash.sha3256(mac_derived_key, cipher_text)
        if mac != cal_mac:
            raise Exception("could not decrypt key with given passphrase")
        encrypt_key = derived_key[0:16]
        ctr = Counter.new(128, initial_value=int_of_string(iv))
        aes = AES.new(encrypt_key, AES.MODE_CTR, counter=ctr)

        # AEC decrypt
        crypted = aes.decrypt(cipher_text)
        return crypted
Exemplo n.º 42
0
 def create(self, *args):
     pas = self.ids.pas.text.encode('utf-8')
     if not op.exists(op.join(self.path, '._')):
         if pas != '':
             mid = self.app.mid.encode('utf-8')
             self.h = ps.hash(pas, mid, 1024, 1, 1, 32)
             with open(op.join(self.path, '._'), 'wb') as f:
                 f.write(self.h)
             self.phase += 1
             self.ids.pas.text = ''
             self.ids.steps.text = str(self.phase) + '/4'
     elif self.phase == 2:
         if pas != '':
             h = ps.hash(pas, self.app.mid.encode('utf-8'), 1024, 1, 1, 32)
             if self.h == h:
                 self.ids.pas.text = ''
                 self.ids.log.text += ('\n\nData pasword can not be the '
                                       'same as App password!')
                 self.ids.log.scroll_to(self.ids.log.children[0])
             else:
                 self.pas = pas
                 self.phase += 1
                 self.ids.pas.text = ''
                 self.ids.steps.text = str(self.phase) + '/4'
     elif self.phase == 3:
         if pas != '':
             h = ps.hash(pas, self.app.mid.encode('utf-8'), 1024, 1, 1, 32)
             if self.h == h:
                 self.ids.pas.text = ''
                 self.ids.log.text += ('\n\nData pasword can not be the '
                                       'same as App password!')
                 self.ids.log.scroll_to(self.ids.log.children[0])
             else:
                 self.pas2 = pas
                 os.mkdir(op.join(self.path, 'transform'))
                 os.mkdir(op.join(self.path, 'transform', 'dr'))
                 os.mkdir(op.join(self.path, 'transform', 'mr'))
                 self.ids.pas.text = ''
                 self.app.pas1 = self.pas
                 self.app.pas2 = self.pas2
                 self.phase += 1
                 self.ids.steps.text = str(self.phase) + '/4'
                 self.ids.log.text += ('\n\n* * *'
                                       '\n\nNow set a word or a sentence '
                                       'that will tell you if you typed '
                                       'your passwords correctly. If the '
                                       'wrong passwords are typed, your '
                                       'text won\'t show correctly.')
                 self.ids.log.scroll_to(self.ids.log.children[0])
     elif self.phase == 4:
         pas = self.ids.pas.text
         if pas != '':
             start = op.join(self.path, 'transform', 'start.hyde')
             with open(start, 'wb') as f:
                 key32 = ps.hash(self.pas, self.pas2, 1024, 1, 1, 32)
                 aes = vial.Vial(key32)
                 start_ctr = op.join(self.path, 'transform', 'start.ctr')
                 f.write(aes.encrypt(pas, start_ctr))
             self.phase += 1
             del self.h, self.pas, self.pas2
             self.manager.current = 'home'
     if self.phase <= 4:
         self.ids.pas.focus = True
     else:
         self.app.home.ids.pas1.focus = True
Exemplo n.º 43
0
 def encrypt(self, cleartxt):
     key = pyscrypt.hash(self.phrase.encode(), self.salt.encode(), 1024, 1,
                         1, 16)
     aes = pyaes.AESModeOfOperationCTR(key)
     ciphertxt = aes.encrypt(cleartxt.encode())
     return ciphertxt.hex()
Exemplo n.º 44
0

def var_int(i):
    if i < 0xfd:
        return int_to_hex(i)
    elif i <= 0xffff:
        return "fd" + int_to_hex(i, 2)
    elif i <= 0xffffffff:
        return "fe" + int_to_hex(i, 4)
    else:
        return "ff" + int_to_hex(i, 8)


Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()

HashScrypt = lambda x: pyscrypt.hash(x, x, 1024, 1, 1, 32)

hash_encode = lambda x: x[::-1].encode('hex')

hash_decode = lambda x: x.decode('hex')[::-1]


def header_to_string(res):
    pbh = res.get('prev_block_hash')
    if pbh is None:
        pbh = '0' * 64

    return int_to_hex(res.get('version'), 4) \
        + rev_hex(pbh) \
        + rev_hex(res.get('merkle_root')) \
        + int_to_hex(int(res.get('timestamp')), 4) \
Exemplo n.º 45
0
    dict(password = '******', salt = 'salt', N = 256, r = 6, p = 2, dkLen = 100, result = '08d4bd8bc6a0db2d3afb86e14bb3e219c7e067add953576ebc4678f86c85f5bc819de1fe22877c7d98c2ee11fef9f3a1ca0047a079b3ee35152c31d51b8db57f267050255065b933d65edfc65203e9b964c5c54507eba8b990c8c9106274fa105237550a'),
    dict(password = "******", salt = 'And friendship for Everyone', N = 1024, r = 1, p = 1, dkLen = 256, result = '3a3cbca04456f6ee5295460171a2a2b27e1c28163999f19ab1e2eeda01e355d904627c6baa185087f99f3fee33e4a9ccad1f4230681d77301d2b4f6543023e090faf6e86431a1071f64b693402ceb485469ef33308af104fb1f87b39ecaf733ebc3d73b184c0914fbc4e8eff90777c60172596de79070418f3c9998b6b60640f1d8f3019904b3e20f2920d26c21daf81d0652ffcaffccf734773e0730900204b56b5bebbfb8c3a31d543f6e3ac5f4e1431a864da87c239eefec8e462d458ee2d214646864e9207e15f66a3782b52bb5158152d757d0ca25d2062235ee76c431e5016b3a52cd5b575e3a26aba95654d5b9a991527f5a19d7275ac4f9889081ee9'),
]

# Use the C wrapper to help generate results against a known-correct implementation
if False:
    import scrypt

    for test in Tests:
        test = test.copy()
        test['buflen'] = test['dkLen']
        del test['dkLen']
        del test['result']
        print scrypt.hash(**test).encode('hex')
        print

# Run each test case
index = 0
for test in Tests:
    index += 1

    # Store and remove the expected result
    result = test['result']
    del test['result']

    # Perform the hash
    h = pyscrypt.hash(**test).encode('hex')

    # How'd we do?
    print "Test %d: %s" % (index, { True: "pass", False: "FAIL" }[h == result])
Exemplo n.º 46
0
# add divider graphic
divider_width = 450
position = '+65+360' if compact else '+65+375'
file_divider = './images/divider-02.png'
file_divider_resized = '/tmp/passport-resized-divider.png'.format(os.getpid())
dimensions = '{}x{}'.format(divider_width, divider_width)
cmd(['convert', file_divider, '-resize', dimensions, '-fuzz', '100%', '-fill', '#{}'.format(rgb_light), '-opaque', 'white', file_divider_resized])
cmd(['composite', '-geometry', position, file_divider_resized, file_output, file_output])
os.remove(file_divider_resized)


# stretch key
start = time.time()
logger.debug('stretching key...')
hashed_password = pyscrypt.hash(password=pwd, salt=salt, N=scrypt_N, r=scrypt_r, p=scrypt_p, dkLen = 32)
hashed_hex = hashed_password.encode('hex')
elapsed = time.time() - start
logger.debug('scrypt(N={},r={},p={}) took {:.1f} seconds'.format(scrypt_N, scrypt_r, scrypt_p, elapsed))
logger.debug('HASH length {} bytes'.format(len(hashed_password)))


# AES key
aes_key = hashed_hex[:32]
logger.debug('KEY length {} bytes'.format(len(aes_key)))


# pad input text
payload = pad(privkey, 16)
logger.debug('DATA length {:,} bytes'.format(len(payload), payload))
Exemplo n.º 47
0
    # For Python 3, we want the hexlify to return a string, not bytes
    def hexlify(string):
        return "".join(('%02x' % b) for b in string)

# Use the C wrapper to help generate results against a known-correct implementation
if False:
    import scrypt

    for test in Tests:
        test = test.copy()
        test['buflen'] = test['dkLen']
        del test['dkLen']
        del test['result']
        print(hexlify(scrypt.hash(**test)))
        print()

# Run each test case
index = 0
for test in Tests:
    index += 1

    # Store and remove the expected result
    result = test['result']
    del test['result']

    # Perform the hash
    h = hexlify(pyscrypt.hash(**test))

    # How'd we do?
    print("Test %d: %s" % (index, { True: "pass", False: "FAIL" }[h == result]))
Exemplo n.º 48
0
import pyscrypt

hashed = pyscrypt.hash(password = "******",
                       salt = "seasalt",
                       N = 1024,
                       r = 1,
                       p = 1,
                       dkLen = 256)
print hashed.encode('hex')
Exemplo n.º 49
0
 def derive_id(self, username, password):
   credentials = (username.lower() + password).encode('ascii',errors='backslashreplace')
   salt = credentials.encode('ascii',errors='backslashreplace')
   hashed = pyscrypt.hash(credentials, salt, 2048, 8, 1, 32)
   return hashed.encode('hex')
Exemplo n.º 50
0
import pyscrypt, time

if __name__ == '__main__':
    tests = [
        (b'', b'', 16, 1, 1, 64),
        (b'password', b'NaCl', 1024, 8, 16, 64),
        (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, 64),
        (b'pleaseletmein', b'SodiumChloride', 1048576, 8, 1, 64)
    ]

    for test in tests:
        start = time.time()
        hashed = pyscrypt.hash(password = test[0], 
            salt = test[1], 
            N = test[2],
            r = test[3],
            p = test[4],
            dkLen = test[5])
        print(time.time() - start, test)