Ejemplo n.º 1
0
def prueba():
    if not os.path.exists("words.txt"):
        mnemo = Mnemonic("english")
        words = mnemo.generate(strength=256)

        with open("words.txt", 'w') as f:
            f.write(words)

        print(words)
    else:
        with open("words.txt", 'r') as f:
            words = f.read()
    print(words)
    w = Wallet(words)
    sk, pk = w.derive_account("TESTNET", account=0, address_index=0)
    sk = PrivateKey(sk)
    pk_bytes = bytes.fromhex(pk) if isinstance(pk, str) else pk
    if len(pk_bytes) != 64:
        pk_bytes = PublicKey(pk_bytes).format(False)[1:]
    print(sk.to_der())
Ejemplo n.º 2
0
def test_load_key_file():
    dummy_sk = PrivateKey()
    dummy_sk_der = dummy_sk.to_der()

    # If file exists and has data in it, function should work.
    with open("key_test_file", "wb") as f:
        f.write(dummy_sk_der)

    Cryptographer.load_key_file("key_test_file")
    os.remove("key_test_file")

    # If file doesn't exist, function should return None
    with pytest.raises(InvalidParameter, match="file not found"):
        Cryptographer.load_key_file("nonexistent_file")

    with pytest.raises(InvalidParameter, match="file path was expected"):
        Cryptographer.load_key_file(0)

    with pytest.raises(InvalidParameter, match="file path was expected"):
        Cryptographer.load_key_file(None)
Ejemplo n.º 3
0
class BaseKey:
    """This class represents a point on the elliptic curve secp256k1 and
    provides all necessary cryptographic functionality. You shouldn't use
    this class directly.

    :param wif: A private key serialized to the Wallet Import Format. If the
                argument is not supplied, a new private key will be created.
                The WIF compression flag will be adhered to, but the version
                byte is disregarded. Compression will be used by all new keys.
    :type wif: ``str``
    :raises TypeError: If ``wif`` is not a ``str``.
    """
    def __init__(self, wif=None):
        if wif:
            if isinstance(wif, str):
                private_key_bytes, compressed, version = wif_to_bytes(wif)
                self._pk = ECPrivateKey(private_key_bytes)
            elif isinstance(wif, ECPrivateKey):
                self._pk = wif
                compressed = True
            else:
                raise TypeError('Wallet Import Format must be a string.')
        else:
            self._pk = ECPrivateKey()
            compressed = True

        self._public_point = None
        self._public_key = self._pk.public_key.format(compressed=compressed)

    @property
    def public_key(self):
        """The public point serialized to bytes."""
        return self._public_key

    @property
    def public_point(self):
        """The public point (x, y)."""
        if self._public_point is None:
            self._public_point = Point(*public_key_to_coords(self._public_key))
        return self._public_point

    def sign(self, data):
        """Signs some data which can be verified later by others using
        the public key.

        :param data: The message to sign.
        :type data: ``bytes``
        :returns: A signature compliant with BIP-62.
        :rtype: ``bytes``
        """
        return self._pk.sign(data)

    def verify(self, signature, data):
        """Verifies some data was signed by this private key.

        :param signature: The signature to verify.
        :type signature: ``bytes``
        :param data: The data that was supposedly signed.
        :type data: ``bytes``
        :rtype: ``bool``
        """
        return self._pk.public_key.verify(signature, data)

    def pub_to_hex(self):
        """:rtype: ``str`` """
        return bytes_to_hex(self.public_key)

    def to_hex(self):
        """:rtype: ``str``"""
        return self._pk.to_hex()

    def to_bytes(self):
        """:rtype: ``bytes``"""
        return self._pk.secret

    def to_der(self):
        """:rtype: ``bytes``"""
        return self._pk.to_der()

    def to_pem(self):
        """:rtype: ``bytes``"""
        return self._pk.to_pem()

    def to_int(self):
        """:rtype: ``int``"""
        return self._pk.to_int()

    def is_compressed(self):
        """Returns whether or not this private key corresponds to a compressed
        public key.

        :rtype: ``bool``
        """
        return True if len(self.public_key) == 33 else False

    def __eq__(self, other):
        return self.to_int() == other.to_int()