コード例 #1
0
 def test_basic(self):
     # this should take 1MB and 1s
     out = scrypt("password", "salt", N=1024, r=8, p=45, dkLen=16)
     self.failUnlessEqual(len(out), 16)
     self.failUnlessEqual(hexlify(out), "99e138108da14a277b69007c1b5d07ed")
     out = scrypt("password", "salt", N=1024, r=8, p=45, dkLen=32)
     self.failUnlessEqual(len(out), 32)
     self.failUnlessEqual(hexlify(out), "99e138108da14a277b69007c1b5d07edbd41339cd6f31e4dc053479c887a627b")
コード例 #2
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]
    if SCRYPT_MODULE == "scrypt":
        key           = scrypt.hash(passphrase, salt, 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":
        key           = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
    else:
        raise ValueError("No scrypt module loaded")
    (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)
コード例 #3
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

    """
    if isinstance(privkey, str):
        privkey = PrivateKey(privkey)
    else:
        privkey = PrivateKey(repr(privkey))

    privkeyhex = repr(privkey)  # hex
    addr = format(privkey.bitcoin.address, "BTC")
    a = _bytes(addr)
    salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    if SCRYPT_MODULE == "scrypt":  # pragma: no cover
        key = scrypt.hash(passphrase, salt, 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":  # pragma: no cover
        key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
    else:  # pragma: no cover
        raise ValueError("No scrypt module loaded")  # pragma: no cover
    (derived_half1, derived_half2) = (key[:32], key[32:])
    aes = AES.new(derived_half2, AES.MODE_ECB)
    encrypted_half1 = _encrypt_xor(privkeyhex[:32], derived_half1[:16], aes)
    encrypted_half2 = _encrypt_xor(privkeyhex[32:], derived_half1[16:], aes)
    " flag byte is forced 0xc0 because Graphene only uses compressed keys "
    payload = b"\x01" + b"\x42" + b"\xc0" + salt + encrypted_half1 + encrypted_half2
    " Checksum "
    checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
    privatkey = hexlify(payload + checksum).decode("ascii")
    return Base58(privatkey)
コード例 #4
0
ファイル: bip38.py プロジェクト: G3niusMind/steem-python
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 = compat_bytes(addr, 'ascii')
    salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    if SCRYPT_MODULE == "scrypt":
        key = scrypt.hash(passphrase, salt, 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":
        key = scrypt.scrypt(compat_bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
    else:
        raise ValueError("No scrypt module loaded")
    (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 Graphene only uses compressed keys "
    payload = (
            b'\x01' + b'\x42' + b'\xc0' + salt + encrypted_half1 + encrypted_half2)
    " Checksum "
    checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
    privatkey = hexlify(payload + checksum).decode('ascii')
    return Base58(privatkey)
コード例 #5
0
ファイル: field.py プロジェクト: boweiliu/core
    def __set__(self, instance, value):
        if instance._initialised:
            if isinstance(value, unicode):
                value = value.encode("utf-8")

            salt = b"".join([choice(printable) for i in range(32)])
            value = str(scrypt(salt, value, maxtime=self.difficulty))

        return super(PasswordField, self).__set__(instance, value)
コード例 #6
0
    def __set__(self, instance, value):
        if instance._initialised:
            if isinstance(value, unicode):
                value = value.encode('utf-8')

            salt = b''.join([choice(printable) for i in range(32)])
            value = str(scrypt(salt, value, maxtime=self.difficulty))

        return super(PasswordField, self).__set__(instance, value)
コード例 #7
0
ファイル: minilockid.py プロジェクト: sharph/pyminilock
 def generate_key(self, password):
     self.pri = PrivateKey(scrypt(sha512(password,encoder = RawEncoder),
                                  self.salt,
                                  N = 1<<17,
                                  r = 8,
                                  p = 1,
                                  buflen = 32),
                           encoder = RawEncoder)
     pub = PublicID()
     pub.salt = self.salt
     pub.key = self.pri.public_key.encode()
     self.pub = pub
コード例 #8
0
def decrypt(encrypted_privkey, passphrase):
    """BIP0038 non-ec-multiply decryption. Returns WIF privkey.

    :param Base58 encrypted_privkey: Private key
    :param str passphrase: UTF-8 encoded passphrase for decryption
    :return: BIP0038 non-ec-multiply decrypted key
    :rtype: Base58
    :raises SaltException: if checksum verification failed (e.g. wrong
    password)

    """

    d = unhexlify(base58decode(encrypted_privkey))
    d = d[2:]  # remove trailing 0x01 and 0x42
    flagbyte = d[0:1]  # get flag byte
    d = d[1:]  # get payload
    assert flagbyte == b'\xc0', "Flagbyte has to be 0xc0"
    salt = d[0:4]
    d = d[4:-4]
    if SCRYPT_MODULE == "scrypt":
        if sys.version >= '3.0.0':
            key = scrypt.hash(passphrase, salt, 16384, 8, 8)
        else:
            key = scrypt.hash(str(passphrase), str(salt), 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":
        key = scrypt.scrypt(compat_bytes(passphrase, "utf-8"), salt, 16384, 8,
                            8)
    else:
        raise ValueError("No scrypt module loaded")
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2, AES.MODE_ECB)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    privraw = decryptedhalf1 + decryptedhalf2
    privraw = ('%064x' %
               (int(hexlify(privraw), 16) ^ int(hexlify(derivedhalf1), 16)))
    wif = Base58(privraw)
    """ Verify Salt """
    privkey = PrivateKey(format(wif, "wif"))
    addr = format(privkey.uncompressed.address, "BTC")
    a = compat_bytes(addr, 'ascii')
    saltverify = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    if saltverify != salt:
        raise SaltException(
            'checksum verification failed! Password may be incorrect.')
    return wif
コード例 #9
0
    def receive_request(self, tx):
        # HTTP body is utf8(json(PIECES))
        pieces = json.loads(tx.decode("utf-8"))
        if pieces[0] == "do-scrypt":
            A_b64 = pieces[1]
            salt = SALT("scrypt") # no email here, anon++
            N, r, p = [int(p) for p in pieces[2:5]]
            B = scrypt(password=b64decode(A_b64), salt=salt, N=N,r=r,p=p,
                       dkLen=KEYLEN)
            B_b64 = b64encode(B)
            resp = ["ok", B_b64]
            return json.dumps(resp).encode("utf-8")

        print "bad request", pieces
        raise Oops("bad request")
コード例 #10
0
ファイル: bip38.py プロジェクト: G3niusMind/steem-python
def decrypt(encrypted_privkey, passphrase):
    """BIP0038 non-ec-multiply decryption. Returns WIF privkey.

    :param Base58 encrypted_privkey: Private key
    :param str passphrase: UTF-8 encoded passphrase for decryption
    :return: BIP0038 non-ec-multiply decrypted key
    :rtype: Base58
    :raises SaltException: if checksum verification failed (e.g. wrong
    password)

    """

    d = unhexlify(base58decode(encrypted_privkey))
    d = d[2:]  # remove trailing 0x01 and 0x42
    flagbyte = d[0:1]  # get flag byte
    d = d[1:]  # get payload
    assert flagbyte == b'\xc0', "Flagbyte has to be 0xc0"
    salt = d[0:4]
    d = d[4:-4]
    if SCRYPT_MODULE == "scrypt":
        key = scrypt.hash(passphrase, salt, 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":
        key = scrypt.scrypt(compat_bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
    else:
        raise ValueError("No scrypt module loaded")
    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)
    privraw = decryptedhalf1 + decryptedhalf2
    privraw = ('%064x' %
               (int(hexlify(privraw), 16) ^ int(hexlify(derivedhalf1), 16)))
    wif = Base58(privraw)
    """ Verify Salt """
    privkey = PrivateKey(format(wif, "wif"))
    addr = format(privkey.uncompressed.address, "BTC")
    a = compat_bytes(addr, 'ascii')
    saltverify = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    if saltverify != salt:
        raise SaltException(
            'checksum verification failed! Password may be incorrect.')
    return wif
コード例 #11
0
c1 = 10000
c2 = 10000
N,r,p = pick_params(maxmem=100*MB, maxtime=1.0)
print N,r,p
dkLen = 256/8

email = "*****@*****.**"
password = "******"

if False:
    Tstart = time.time()
    A = PBKDF2(password=password, salt=plus(KW1, email), c=c1, dkLen=dkLen)
    Ta = time.time()
    print "time[A]:", Ta-Tstart
    B = scrypt(password=A, salt=plus(KW2, email), N=N,r=r,p=p, dkLen=256/8)
    Tb = time.time()
    print "time[B]:", Tb-Ta
    C = PBKDF2(password=plus(password,B), salt=plus(KW3, email), c=c2, dkLen=3*dkLen)
    Tc = time.time()
    print "time[C]:", Tc-Tb
    PWK, MAC, SRPpw = C[:dkLen], C[dkLen:2*dkLen], C[2*dkLen:3*dkLen]
    SRPsalt, SRPvkey = create_salted_verification_key(email, SRPpw, hash_alg=SHA256)
    Td = time.time()
    print "time[D]:", Td-Tc
    print "time[total]:", Td-Tstart
    print

    print "PWK:", hexlify(PWK)
    print "MAC:", hexlify(MAC)
    print "SRPpw:", hexlify(SRPpw)
コード例 #12
0
def scrypt_b64(password_b64, salt_b64, dkLen):
    N,r,p = SCRYPT_PARAMS
    return b64encode(scrypt(password=b64decode(password_b64),
                            salt=b64decode(salt_b64), N=N,r=r,p=p,
                            dkLen=dkLen))