Python ecdsa.VerifyingKey() Examples

The following are 15 code examples of ecdsa.VerifyingKey(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ecdsa , or try the search function .
Example #1
Source File: ecdsa_backend.py    From python-jose with MIT License 7 votes vote down vote up
def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'EC':
            raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty'))

        if not all(k in jwk_dict for k in ['x', 'y', 'crv']):
            raise JWKError('Mandatory parameters are missing')

        if 'd' in jwk_dict:
            # We are dealing with a private key; the secret exponent is enough
            # to create an ecdsa key.
            d = base64_to_long(jwk_dict.get('d'))
            return ecdsa.keys.SigningKey.from_secret_exponent(d, self.curve)
        else:
            x = base64_to_long(jwk_dict.get('x'))
            y = base64_to_long(jwk_dict.get('y'))

            if not ecdsa.ecdsa.point_is_valid(self.curve.generator, x, y):
                raise JWKError("Point: %s, %s is not a valid point" % (x, y))

            point = ecdsa.ellipticcurve.Point(self.curve.curve, x, y, self.curve.order)
            return ecdsa.keys.VerifyingKey.from_public_point(point, self.curve) 
Example #2
Source File: py_ecdsa.py    From gist-alfred with MIT License 6 votes vote down vote up
def prepare_key(self, key):

        if isinstance(key, ecdsa.SigningKey) or \
           isinstance(key, ecdsa.VerifyingKey):
            return key

        if isinstance(key, string_types):
            if isinstance(key, text_type):
                key = key.encode('utf-8')

            # Attempt to load key. We don't know if it's
            # a Signing Key or a Verifying Key, so we try
            # the Verifying Key first.
            try:
                key = ecdsa.VerifyingKey.from_pem(key)
            except ecdsa.der.UnexpectedDER:
                key = ecdsa.SigningKey.from_pem(key)

        else:
            raise TypeError('Expecting a PEM-formatted key.')

        return key 
Example #3
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sign_dict(self, data, signature_encoding='base64'):
		"""
		Sign a dictionary object. The dictionary will have a 'signature' key
		added is required by the :py:meth:`.VerifyingKey.verify_dict` method.
		To serialize the dictionary to data suitable for the operation the
		:py:func:`json.dumps` function is used and the resulting data is then
		UTF-8 encoded.

		:param dict data: The dictionary of data to sign.
		:param str signature_encoding: The encoding name of the signature data.
		:return: The dictionary object is returned with the 'signature' key added.
		"""
		utilities.assert_arg_type(data, dict, arg_pos=1)
		data = copy.copy(data)
		data.pop('signature', None)  # remove a pre-existing signature
		json_data = json.dumps(data, sort_keys=True).encode('utf-8')
		data['signature'] = _encoding_data(self.sign(json_data), encoding=signature_encoding)
		return data 
Example #4
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _load_key_store(self, file_name):
		file_path = find.data_file(file_name)
		if not file_path:
			return 0
		with open(file_path, 'r') as file_h:
			key_store = serializers.JSON.load(file_h)
		utilities.validate_json_schema(key_store, 'king-phisher.security')
		key_store = key_store['keys']
		loaded = 0
		for key_idx, key in enumerate(key_store, 1):
			identifier = key['id']
			if identifier in self.keys:
				self.logger.warning("skipping loading {0}:{1} due to a duplicate id".format(file_name, key_idx))
				continue
			verifying_key = key['verifying-key']
			key['verifying-key'] = VerifyingKey.from_dict(verifying_key, encoding=verifying_key.pop('encoding', 'base64'))
			self.keys[identifier] = key
			self.logger.debug("loaded key id: {0} from: {1}".format(identifier, file_path))
			loaded += 1
		return loaded 
Example #5
Source File: py_ecdsa.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def prepare_key(self, key):

        if isinstance(key, ecdsa.SigningKey) or \
           isinstance(key, ecdsa.VerifyingKey):
            return key

        if isinstance(key, string_types):
            if isinstance(key, text_type):
                key = key.encode('utf-8')

            # Attempt to load key. We don't know if it's
            # a Signing Key or a Verifying Key, so we try
            # the Verifying Key first.
            try:
                key = ecdsa.VerifyingKey.from_pem(key)
            except ecdsa.der.UnexpectedDER:
                key = ecdsa.SigningKey.from_pem(key)

        else:
            raise TypeError('Expecting a PEM-formatted key.')

        return key 
Example #6
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_secret_exponent(cls, *args, **kwargs):
		id_ = kwargs.pop('id', None)
		instance = super(SigningKey, cls).from_secret_exponent(*args, **kwargs)
		orig_vk = instance.verifying_key
		instance.verifying_key = VerifyingKey.from_public_point(orig_vk.pubkey.point, instance.curve, instance.default_hashfunc, id=id_)
		instance.id = id_
		return instance 
Example #7
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
		self.id = kwargs.pop('id', None)
		"""An optional string identifier for this key instance."""
		super(VerifyingKey, self).__init__(*args, **kwargs) 
Example #8
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_public_point(cls, *args, **kwargs):
		id_ = kwargs.pop('id', None)
		inst = super(VerifyingKey, cls).from_public_point(*args, **kwargs)
		inst.id = id_
		return inst 
Example #9
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_string(cls, string, **kwargs):
		kwargs = _kwarg_curve(kwargs)
		id_ = kwargs.pop('id', None)
		inst = super(VerifyingKey, cls).from_string(string, **kwargs)
		inst.id = id_
		return inst 
Example #10
Source File: bitcoin.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def _CKD_pub(cK, c, s):
    import hmac
    from ecdsa.util import string_to_number, number_to_string
    order = generator_secp256k1.order()
    I = hmac.new(c, cK + s, hashlib.sha512).digest()
    curve = SECP256k1
    pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
    public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
    c_n = I[32:]
    cK_n = GetPubKey(public_key.pubkey,True)
    return cK_n, c_n 
Example #11
Source File: identity.py    From ledger-api-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, public_key):

        if isinstance(public_key, Identity):
            self._verifying_key = public_key.verifying_key
        elif isinstance(public_key, ecdsa.VerifyingKey):
            self._verifying_key = public_key
        elif isinstance(public_key, bytes):
            self._verifying_key = ecdsa.VerifyingKey.from_string(public_key, curve=self.curve,
                                                                 hashfunc=self.hash_function)
        else:
            raise RuntimeError('Failed')

        # cache the binary representations of the public key
        self._public_key_bytes = self._verifying_key.to_string()
        self._public_key = base64.b64encode(self._public_key_bytes).decode() 
Example #12
Source File: ulord.py    From Uwallet with MIT License 5 votes vote down vote up
def _CKD_pub(cK, c, s):
    order = generator_secp256k1.order()
    I = hmac.new(c, cK + s, hashlib.sha512).digest()
    curve = SECP256k1
    pubkey_point = string_to_number(I[0:32]) * curve.generator + ser_to_point(cK)
    public_key = ecdsa.VerifyingKey.from_public_point(pubkey_point, curve=SECP256k1)
    c_n = I[32:]
    cK_n = GetPubKey(public_key.pubkey, True)
    return cK_n, c_n 
Example #13
Source File: ecdsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def __init__(self, key, algorithm):
        if algorithm not in ALGORITHMS.EC:
            raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)

        self.hash_alg = {
            ALGORITHMS.ES256: self.SHA256,
            ALGORITHMS.ES384: self.SHA384,
            ALGORITHMS.ES512: self.SHA512
        }.get(algorithm)
        self._algorithm = algorithm

        self.curve = self.CURVE_MAP.get(self.hash_alg)

        if isinstance(key, (ecdsa.SigningKey, ecdsa.VerifyingKey)):
            self.prepared_key = key
            return

        if isinstance(key, dict):
            self.prepared_key = self._process_jwk(key)
            return

        if isinstance(key, six.string_types):
            key = key.encode('utf-8')

        if isinstance(key, six.binary_type):
            # Attempt to load key. We don't know if it's
            # a Signing Key or a Verifying Key, so we try
            # the Verifying Key first.
            try:
                key = ecdsa.VerifyingKey.from_pem(key)
            except ecdsa.der.UnexpectedDER:
                key = ecdsa.SigningKey.from_pem(key)
            except Exception as e:
                raise JWKError(e)

            self.prepared_key = key
            return

        raise JWKError('Unable to parse an ECKey from key: %s' % key) 
Example #14
Source File: ecdsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def is_public(self):
        return isinstance(self.prepared_key, ecdsa.VerifyingKey) 
Example #15
Source File: cryptography_backend.py    From python-jose with MIT License 4 votes vote down vote up
def __init__(self, key, algorithm, cryptography_backend=default_backend):
        if algorithm not in ALGORITHMS.EC:
            raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)

        self.hash_alg = {
            ALGORITHMS.ES256: self.SHA256,
            ALGORITHMS.ES384: self.SHA384,
            ALGORITHMS.ES512: self.SHA512
        }.get(algorithm)
        self._algorithm = algorithm

        self.cryptography_backend = cryptography_backend

        if hasattr(key, 'public_bytes') or hasattr(key, 'private_bytes'):
            self.prepared_key = key
            return

        if None not in (EcdsaSigningKey, EcdsaVerifyingKey) and isinstance(key, (EcdsaSigningKey, EcdsaVerifyingKey)):
            # convert to PEM and let cryptography below load it as PEM
            key = key.to_pem().decode('utf-8')

        if isinstance(key, dict):
            self.prepared_key = self._process_jwk(key)
            return

        if isinstance(key, six.string_types):
            key = key.encode('utf-8')

        if isinstance(key, six.binary_type):
            # Attempt to load key. We don't know if it's
            # a Public Key or a Private Key, so we try
            # the Public Key first.
            try:
                try:
                    key = load_pem_public_key(key, self.cryptography_backend())
                except ValueError:
                    key = load_pem_private_key(key, password=None, backend=self.cryptography_backend())
            except Exception as e:
                raise JWKError(e)

            self.prepared_key = key
            return

        raise JWKError('Unable to parse an ECKey from key: %s' % key)