Пример #1
0
    def derive_secp256k1_master_keys(self):
        """
        Uses the XRPL's convoluted key derivation process to get the
        secp256k1 master keypair for this seed value.
        Saves the values to the object for later reference.
        """

        root_sec_i = secp256k1_secret_key_from(self.bytes)
        root_pub_point = keys.get_public_key(root_sec_i, curve.secp256k1)
        root_pub_b = compress_secp256k1_public(root_pub_point)
        fam_b = bytes(4)  # Account families are unused; just 4 bytes of zeroes
        inter_pk_i = secp256k1_secret_key_from(b''.join([root_pub_b, fam_b]))
        inter_pub_point = keys.get_public_key(inter_pk_i, curve.secp256k1)

        # Secret keys are ints, so just add them mod the secp256k1 group order
        master_sec_i = (root_sec_i + inter_pk_i) % curve.secp256k1.q
        # Public keys are points, so the fastecdsa lib handles adding them
        master_pub_point = root_pub_point + inter_pub_point

        self._secp256k1_sec = master_sec_i.to_bytes(32,
                                                    byteorder="big",
                                                    signed=False)
        self._secp256k1_pub = compress_secp256k1_public(master_pub_point)
        self._secp256k1_root_pub = root_pub_b

        # Saving the full key to make it easier to sign things later
        self._secp256k1_full = master_pub_point
Пример #2
0
    def gen_publickey(self, key=None):
        """
		Get public key from private key.

		:param key: (optional) the private key
		:type key: int

		:return: None
		"""
        if key:
            self.public_key = keys.get_public_key(key, secp256k1)
        elif self.private_key:
            self.public_key = keys.get_public_key(self.private_key, secp256k1)
        else:
            raise TypeError("no private key to generate from")
Пример #3
0
 def __init__(self, priv_key=None):
     if priv_key == None:
         self.priv_key, self.pub_key = generate_keypair()
     else:
         self.priv_key = priv_key
         self.pub_key = keys.get_public_key(self.priv_key, curve.secp256k1)
     self.address = generate_address(self.pub_key)
Пример #4
0
 def from_entropy(cls, entropy, is_public=False):
     """Create a BIP32Key using supplied entropy >= MIN_ENTROPY_LEN"""
     if entropy is None:
         entropy = urandom(MIN_ENTROPY_LEN //
                           8)  # Python doesn't have os.random()
     if not len(entropy) >= MIN_ENTROPY_LEN // 8:
         raise ValueError("Initial entropy %i must be at least %i bits" %
                          (len(entropy), MIN_ENTROPY_LEN))
     i64 = hmac.new(b"Bitcoin seed", entropy, hashlib.sha512).digest()
     il, ir = i64[:32], i64[32:]
     # FIXME test Il for 0 or less than SECP256k1 prime field order
     secret = int.from_bytes(il, 'big')
     public = get_public_key(secret, secp256k1)
     if is_public:
         return cls(secret=None,
                    public=public,
                    chain=ir,
                    depth=0,
                    index=0,
                    fpr=b'\0\0\0\0',
                    path='m')
     else:
         return cls(secret=secret,
                    public=public,
                    chain=ir,
                    depth=0,
                    index=0,
                    fpr=b'\0\0\0\0',
                    path='m')
def fast_ecdsa(count, loop):
    private_key = keys.gen_private_key(curve.P256)
    public_key = keys.get_public_key(private_key, curve.P256)
    # standard signature, returns two integers

    with open("message.txt", "rb") as f:
        m = f.read()

    time_list_sign = []
    for l in range(loop):
        start = time.time()
        for c in range(count):
            r, s = ecdsa.sign(m, private_key)
        end = time.time() - start
        # print("["+str(l)+"th fast_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature")
        time_list_sign.append(end)
    ave_sign = numpy.mean(numpy.array(time_list_sign))

    time_list_vrfy = []
    for l in range(loop):
        start = time.time()
        for c in range(count):
            valid = ecdsa.verify((r, s), m, public_key)
        end = time.time() - start
        # print("["+str(l)+"th fast_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature")
        time_list_vrfy.append(end)
    ave_vrfy = numpy.mean(numpy.array(time_list_vrfy))

    print("fast_ecdsa:sign average second is " + str(ave_sign) + "/" +
          str(count) + " signature")
    print("fast_ecdsa:vrfy average second is " + str(ave_vrfy) + "/" +
          str(count) + " signature")
    return time_list_sign, time_list_vrfy
Пример #6
0
def sign(m):
    #generate public key & private key
    myCurve = curve.secp256k1
    private_key = keys.gen_private_key(myCurve)
    public_key = keys.get_public_key(private_key, myCurve)

    #print("this is the point:", public_key )
    #print("this is th public key:", public_key)
    #print("this is th private key:", private_key)

    #generate signature
    k = random.randint(1, 100)
    n = myCurve.q
    d = private_key
    G = myCurve.G
    print("this is n:", n)

    x1y1 = k * G
    r = pow(x1y1.x, 1, n)
    z = int.from_bytes((hashlib.sha256(m.encode('utf-8')).digest()), 'big')
    s = modinv(k, n) * (z + r * d) % n

    #r = 0
    #s = 0
    return (public_key, [r, s])
Пример #7
0
def get_public_key(priv_key, curve=curve.P256, hashfunc=sha256, fmt='RAW'):
    if fmt in ['RAW', '04']:
        priv_key = int(priv_key, 16)
        pub_key = keys.get_public_key(priv_key, curve=curve)
        return point_to_hex_str(pub_key, fmt=fmt)
    else:
        raise UnknownPublicKeyFormatError("fmt: '%s'" % fmt)
Пример #8
0
 def derive_pubkey(self, secret):
     P = keys.get_public_key(secret, curve.secp256k1)
     pub_key = SEC1Encoder.encode_public_key(P)
     #print("Pub key: ", pub_key)
     #print("pubkey : ", hexlify(pub_key))
     # return hex encoding in bytes AND int encoding
     return hexlify(pub_key), P
Пример #9
0
    def derive_localkeys(self, per_commitment_point, base_point, base_secret):
        hash = hashlib.sha256()
        hash.update(convert_to_bytes(per_commitment_point))
        hash.update(convert_to_bytes(base_point))

        initial_digest = hash.digest()
        digest = int.from_bytes(initial_digest, byteorder='big')
        #print("initial digest: 0x%s" % initial_digest.hex())

        # convert base_point to an actual Point
        #print("SHA: ", digest)
        P = keys.get_public_key(digest, curve.secp256k1)

        local_pubkey = base_point + P
        if self.verbose: print("local pubkey: 0x%s" % convert_to_bytes(local_pubkey).hex())
        local_pubkey_hex = convert_to_bytes(local_pubkey).hex()

        local_privkey = (base_secret + digest) % curve.secp256k1.q
        if self.verbose: print("local privkey: 0x%s" % hex(local_privkey))
        local_privkey_hex = hex(local_privkey).lstrip("0x")

        if self.verbose:
            print("local pubkey int: ", convert_to_int(local_pubkey))
            print("local privkey int:", local_privkey)
        #return convert_to_int(local_pubkey), local_privkey
        return local_pubkey_hex, local_privkey_hex
Пример #10
0
    def createVote(self, voter, voted_for, zoneSection, privateKey):
        if (voter == "" or voted_for == ""):
            return False  # Forneça todos os campos! Sua chave, em quem vota e suas Zona e Seção

    # Pega a chave pública associada à chave privada fornecida
        publicKey = keys.get_public_key(privateKey, curve.secp256k1)

        if (voter != publicKey.__str__()):
            return False  # Chave inválida

        for vote in self.pendingVotes:
            if (publicKey == vote.voter):
                return False  # Voto já adicionado (pendente)

        for block in self.chain:
            if (block.vote.voter.__str__() == publicKey.__str__()):
                return False  # Voto já realizado

        # Cria uma nova cédula de votação
        vote = Vote(publicKey, voted_for, zoneSection)

        # Assina a cédula
        vote.signVote(privateKey)

        # Verifica se a assinatura é válida
        if (not vote.verifyVote(privateKey)):
            return False  # Assinatura inválida. Voto não computado

        # Caso tudo ocorra com sucesso, adiciona ao array de votos pendentes de mineração
        self.pendingVotes.append(vote)
        return True
Пример #11
0
    def generate_wallet():
        """
        Generate wallet key pair and encode public_key to base58check format
        :return: Accurately function returns private_key corresponded with wallet_address
        """
        ###256b Private key generation
        priv_key = keys.gen_private_key(curve.P256)
        ###Change private key to hex
        priv_key_hex = hex(priv_key)
        ###Change private key from hex to dec
        #priv_key_from_hex = int(f"{priv_key_hex}", 16)

        # Get public key from private key as point
        pub_key = keys.get_public_key(priv_key, curve.P256)

        # Public key (K) as 128bit string str(x)+str(y)
        pub_key_128 = f"{format(pub_key.x, 'x')}" + f"{format(pub_key.y, 'x')}"

        # SHA256(K) - binary
        pub_key_hash_bin = hashlib.sha256(pub_key_128.encode()).digest()

        # RIPEMD160(SHA256(K))
        pub_key_hash_ripemd = hashlib.new('ripemd160',
                                          pub_key_hash_bin).digest()

        # Base58Check address
        pub_key_base58 = base58.b58encode_check(pub_key_hash_ripemd)

        # Add 'B' as network sign
        wallet_address = "B" + str(pub_key_base58)

        key_pair = [wallet_address, priv_key_hex]

        return key_pair
Пример #12
0
    def from_secret_exponent(cls,
                             secret_exponent: bytes,
                             curve=b'ed',
                             activation_code=None):
        """
        Creates a key object from a secret exponent.
        :param secret_exponent: secret exponent or seed
        :param curve: b'sp' for Secp251k1, b'p2' for P256/Secp256r1, b'ed' for Ed25519 (default)
        :param activation_code: secret for initializing account balance
        """
        # Ed25519
        if curve == b'ed':
            # Dealing with secret exponent or seed?
            if len(secret_exponent) == 64:
                public_point = pysodium.crypto_sign_sk_to_pk(
                    sk=secret_exponent)
            else:
                public_point, secret_exponent = pysodium.crypto_sign_seed_keypair(
                    seed=secret_exponent)
        # Secp256k1
        elif curve == b'sp':
            sk = secp256k1.PrivateKey(secret_exponent)
            public_point = sk.pubkey.serialize()
        # P256
        elif curve == b'p2':
            pk = get_public_key(bytes_to_int(secret_exponent), curve=P256)
            public_point = SEC1Encoder.encode_public_key(pk)
        else:
            assert False

        return cls(public_point,
                   secret_exponent,
                   curve=curve,
                   activation_code=activation_code)
Пример #13
0
    def verify_priv_key(self, priv_key_hex, wallet_address):
        """
        Verify private_key compatibility with public_key result
        :param priv_key_hex: Private key written as hex
        :param wallet_address: base58check encoded public key
        :return: True if keys are compatible or False if not
        """
        # Convert hex priv_key to dec
        priv_key = int(f"{priv_key_hex}", 16)

        # Convert pub_key_base58 to ripemd160 bin
        pub_key_hash_ripemd1 = base58.b58decode_check(wallet_address[1:])

        # Get public key from private key as point
        pub_key = keys.get_public_key(priv_key, curve.P256)

        # Public key (K) as 128bit string str(x)+str(y)
        pub_key_128 = f"{format(pub_key.x, 'x')}" + f"{format(pub_key.y, 'x')}"

        # SHA256(K) - binary
        pub_key_hash_bin = hashlib.sha256(pub_key_128.encode()).digest()

        # RIPEMD160(SHA256(K))
        pub_key_hash_ripemd2 = hashlib.new('ripemd160',
                                           pub_key_hash_bin).digest()

        return pub_key_hash_ripemd1 == pub_key_hash_ripemd2
Пример #14
0
    def from_secret_key(cls, secret_key: bytes, curve=b'ed'):
        """
        Creates a key object from a secret exponent.
        :param secret_key: secret exponent or seed
        :param curve: an elliptic curve used, default is ed25519
        """
        # Ed25519
        if curve == b'ed':
            # Dealing with secret key or seed?
            if len(secret_key) == 64:
                public_key = pysodium.crypto_sign_sk_to_pk(sk=secret_key)
            else:
                public_key, secret_key = pysodium.crypto_sign_seed_keypair(seed=secret_key)
        # Secp256k1
        elif curve == b'sp':
            sk = secp256k1.PrivateKey(secret_key)
            public_key = sk.pubkey.serialize()
        # P256
        elif curve == b'p2':
            pk = get_public_key(bytes_to_int(secret_key), curve=P256)
            public_key = SEC1Encoder.encode_public_key(pk)
        else:
            assert False

        return cls(public_key, secret_key, curve=curve)
 def __init__(self, pem=None):
     if pem is None:
         self._key, self._pubkey = fe_keys.gen_keypair(self.CURVE)
         return
     self._key, self._pubkey = fe_pem.PEMEncoder.decode_private_key(
         pem.strip())
     if self._pubkey is None:
         self._pubkey = fe_keys.get_public_key(self._key, self.CURVE)
Пример #16
0
def gen_keypair(curve=curve.P256, hashfunc=sha256, pub_key_fmt='RAW'):
    if pub_key_fmt in ['RAW', '04']:
        priv_key = keys.gen_private_key(curve=curve)
        pub_key = keys.get_public_key(priv_key, curve=curve)
        return int_to_hex_str(priv_key), point_to_hex_str(pub_key,
                                                          fmt=pub_key_fmt)
    else:
        raise UnknownPublicKeyFormatError("fmt: '%s'" % fmt)
Пример #17
0
 def generate_keypairs():
     try:
         private_key = keys.gen_private_key(ccurve)
         public_key = keys.get_public_key(private_key, ccurve)
         return private_key, public_key
     except ecdsa.EcdsaError as encode_err:
         print("Error when generating key pairs: {0}".format(encode_err))
         raise
Пример #18
0
def sk2pk(sk):
    """secretKey to publicKey"""
    point = get_public_key(int.from_bytes(sk, 'big'), secp256k1)
    x = point.x.to_bytes(32, 'big')
    if point.y & 1:
        return b'\3' + x
    else:
        return b'\2' + x
Пример #19
0
def get_pub_key(priv_key: str) -> str:
    '''
    Returns the public key associated with
    the private key. 'x' is used to split
    up the x and y coordinates of the public
    key
    '''
    pub_key = keys.get_public_key(int(priv_key, 16), curve.P256)
    return '{:x}'.format(pub_key.x) + 'x' + '{:x}'.format(pub_key.y)
Пример #20
0
 def set_custom_key(self):
     try:
         new_private_key = int(input('please write a new private key '))
         new_public_key = keys.get_public_key(new_private_key, curve.P256)
         self._private_key = new_private_key
         self._public_key = new_public_key
         print('private and public keys were successfully reset')
     except ValueError:
         print('Reseting keys failed : no number found')
Пример #21
0
 def import_keypair(self, priv_key):
     pub_key = keys.get_public_key(int(priv_key, 16), curve.secp256k1)
     if (pub_key.y % 2):
         compressed_pub_key = '03' + str(hex(pub_key.x))[2:]
     else:
         compressed_pub_key = '02' + str(hex(pub_key.x))[2:]
     self.keypairs[compressed_pub_key] = int(priv_key, 16)
     self.uncompressed_keys[str(hex(pub_key.x))] = int(pub_key.y)
     return compressed_pub_key
Пример #22
0
    def new_keypair(self):
        """ 生成公私钥的键值对"""
        priv_key = keys.gen_private_key(curve.P256)

        pub_key = keys.get_public_key(priv_key, curve.P256)

        pub_key = "".join([str(pub_key.x), str(pub_key.y)])

        return priv_key, pub_key
Пример #23
0
 def verify(ch, aggrR, aggrPK, msg):
     if not (aggrR and aggrPK):
         return
     Gr = keys.get_public_key(aggrR, curve.P256)  # G^aggrR
     aggrV_1 = Gr + ch * aggrPK
     aggrMsg = msg + str(aggrV_1)
     encodedMsg = aggrMsg.encode('utf-8')
     ch_1 = hashlib.sha256(encodedMsg)
     ch_1 = int(ch_1.hexdigest(), 16)
     assert ch == ch_1
Пример #24
0
def private_key_to_public_key(private_key):
    """Accept a hex private key and convert it to its respective public key. Because converting a private key to
    a public key requires SECP256k1 ECDSA signing, this function is the most time consuming and is a bottleneck
    in the overall speed of the program.
    Average Time: 0.0016401287 seconds
    """
    # get the public key corresponding to the private key we just generated
    c = int('0x%s'%private_key,0)
    d = keys.get_public_key(c, curve.secp256k1)
    return '04%s%s'%('{0:x}'.format(int(d.x)), '{0:x}'.format(int(d.y)))
Пример #25
0
def derive_key_pair(seed: Seed) -> t.Tuple[PrivateKey, PublicKey]:
    root_private_key = derive_private_key(seed)
    root_public_point = keys.get_public_key(root_private_key, curve.secp256k1)
    root_public_key = compress_ecdsa_point(root_public_point)

    inter_private_key = derive_private_key(root_public_key + FAMILY)
    inter_public_point = keys.get_public_key(inter_private_key, curve.secp256k1)
    inter_public_key = compress_ecdsa_point(inter_public_point)

    master_private_key = to_bytes(
        (root_private_key + inter_private_key) % GROUP_ORDER, 32
    )
    master_public_point = root_public_point + inter_public_point
    master_public_key = compress_ecdsa_point(master_public_point)

    return (
        t.cast(PrivateKey, master_private_key),
        t.cast(PublicKey, master_public_key),
    )
Пример #26
0
    def new_keypair(self):
        priv_key = keys.gen_private_key(curve.P256)

        pub_key = keys.get_public_key(priv_key, curve.P256)

        pub_key = "".join([str(pub_key.x), str(pub_key.y)])

        self.private_key = priv_key
        self.pub_key = pub_key
        return priv_key, pub_key
Пример #27
0
def generate_wallet_address(passphrase=''):
    """
    :param passphrase: salt for the mnemonic
    The optional passphrase creates two important features:
    • A second factor (something memorized) that makes a mnemonic useless on its
    own, protecting mnemonic backups from compromise by a thief.
    • A form of plausible deniability or “duress wallet,” where a chosen passphrase
    leads to a wallet with a small amount of funds used to distract an attacker from
    the “real” wallet that contains the majority of funds.
    However, it is important to note that the use of a passphrase also introduces the risk
    of loss:
    • If the wallet owner is incapacitated or dead and no one else knows the pass‐
    phrase, the seed is useless and all the funds stored in the wallet are lost forever.
    • Conversely, if the owner backs up the passphrase in the same place as the seed, it
    defeats the purpose of a second factor.

    :return: (master)private key/address, (master)public key/address, (master) chain code, mnemonic,
    passphrase
    """

    flag = True

    while flag:
        m = mn.Mnemonic('english')
        mnemonic = m.generate()
        seed = m.to_seed(mnemonic, passphrase)

        # 64 bytes = 512 bits
        hash_512 = hmac.new(key=seed, digestmod=hashlib.sha512).digest()

        priv_key = hash_512[:32]

        # get the public key corresponding to the private key we just generated
        pub_key = keys.get_public_key(
            int.from_bytes(priv_key, byteorder='little'), curve.P256)

        x = int.to_bytes(pub_key.x, 32, byteorder='little')
        y = int.to_bytes(pub_key.y, 32, byteorder='little')

        # got to check the endianness of the bytes
        bitcoin_wallet_address = _generate_wallet_address(x + y)

        chain_code = hash_512[32:]

        # check if this public key already exists
        if bitcoin_wallet_address not in WALLET_DATABASE:
            # add this public key to the database
            WALLET_DATABASE.add(bitcoin_wallet_address)
            flag = False
    """A bitcoin address is not the same as a public key. Bitcoin addresses
    are derived from a public key using a one-way function.
    len(seed) = 64 bytes """
    return priv_key, bitcoin_wallet_address, chain_code, mnemonic, seed.hex(
    ), passphrase
Пример #28
0
def keyGen(username, type):
    privateKeyFile = username + '_privkey.pem'
    publicKeyFile = username + '_pubkey.pem'
    privateKey = keys.gen_private_key(curve.P256)
    publicKey = keys.get_public_key(privateKey, curve.P256)
    keys.export_key(privateKey,
                    curve=curve.P256,
                    filepath="keys/" + type + "Key/" + privateKeyFile)
    keys.export_key(publicKey,
                    curve=curve.P256,
                    filepath="keys/" + type + "Key/" + publicKeyFile)
    return True
Пример #29
0
def sign(m):
	#generate public key
	#Your code here
  private_key = keys.gen_private_key(curve.secp256k1)
  public_key = keys.get_public_key(private_key, curve.secp256k1)

	#generate signature
	#Your code here
  r, s = ecdsa.sign(m,private_key,curve=curve.secp256k1,hashfunc=sha256)    

  assert isinstance( public_key, point.Point )
  assert isinstance( r, int )
  assert isinstance( s, int )
  return( public_key, [r,s] )
Пример #30
0
def generate_iCloud_keypair():
    """
    When Bob sets up Find My for the first time and checks the
    "enable offline discovery" box, Find My generates an EC P-224
    private encryption key pair.

    Returns:
      Tuple of (privateKey, publicKey)
    """
    # Generate a private key using the P-224 curve.
    privateKey = keys.gen_private_key(curve.P224)

    # Generate the public key corresponding to the private key we just generated.
    publicKey = keys.get_public_key(privateKey, curve.P224)

    return (privateKey, publicKey)