示例#1
0
    def _parse_ecdsa_private_key(private, curve):
        ver = private.getChild(0)
        if ver.value != b'\x01':
            raise SyntaxError("Unexpected EC key version")
        private_key = private.getChild(1)
        public_key = private.getChild(2)
        # first two bytes are the ASN.1 custom type and the length of payload
        # while the latter two bytes are just specification of the public
        # key encoding (uncompressed)
        # TODO: update ecdsa lib to be able to parse PKCS#8 files
        if curve is not NIST521p:
            if list(public_key.value[:1]) != [3] or \
                    list(public_key.value[2:4]) != [0, 4]:
                raise SyntaxError(
                    "Invalid or unsupported encoding of public key")

            pub_key = VerifyingKey.from_string(
                compatHMAC(public_key.value[4:]), curve)
        else:
            if list(public_key.value[:3]) != [3, 129, 134] or \
                    list(public_key.value[3:5]) != [0, 4]:
                raise SyntaxError(
                    "Invalid or unsupported encoding of public key")

            pub_key = VerifyingKey.from_string(
                compatHMAC(public_key.value[5:]), curve)
        pub_x = pub_key.pubkey.point.x()
        pub_y = pub_key.pubkey.point.y()
        priv_key = SigningKey.from_string(compatHMAC(private_key.value), curve)
        mult = priv_key.privkey.secret_multiplier
        return Python_ECDSAKey(pub_x, pub_y, curve.name, mult)
示例#2
0
    def check_sig(*args, **kwargs):

        id = get_id()
        if not id:
            log.info('ID Unavailable from request: %s' % request.url)
            return create_json_response(False, 'Unknown Endpoint', 404)

        if request.headers.get('x-signature'):
            sig = request.headers.get('x-signature')
        else:
            log.info('No x-signature header present, Signature Check Failed [ID: %s]' % id)
            return create_json_response(False, 'Missing x-signature header', 400)

        try:
            vk = VerifyingKey.from_string(request.headers.get('x-identity').decode('hex'), curve=curves.SECP256k1)
        except UnexpectedDER as e:
            log.info('Bad Key Format [ID: %s]: %s' % (id, str(e)))
            return create_json_response(False, 'Bad Public Key Format', 400)

        try:
            verified = vk.verify(sig.decode('hex'), request.url + request.data)
            if verified:
                return f(*args, **kwargs)
            else:
                return create_json_response(False, 'Signature Verification Error', 401)

        except BadDigestError as e:
            log.info('Digest Error During Signature Validation [ID: %s]: %s' % (id, str(e)))
            return create_json_response(False, 'Signature Verification Error', 401)

        except BadSignatureError as e:
            log.info('Bad Signature Encountered During Signature Validation [ID: %s]: %s' % (id, str(e)))
            return create_json_response(False, 'Signature Verification Error', 401)
    def __init__(self,
                 keyid,
                 prikey,
                 ccode,
                 pubkey,
                 is_prikey,
                 parentId=None,
                 depth=0):
        self.depth = depth
        self.is_prikey = is_prikey
        self.keyid = keyid
        self.credid = (parentId + keyid) if parentId else keyid
        ccode_int = int.from_bytes(ccode, 'big')

        if not ccode or ccode_int > CURVE_ORDER:
            raise Exception('ccode must less than {}'.format(CURVE_ORDER))

        self.ccode = ccode[:]

        if is_prikey:
            if not isinstance(prikey, SigningKey):
                raise Exception('need prikey')
            self.prikey = prikey
            self.pubkey = prikey.get_verifying_key()
        else:
            self.pubkey = VerifyingKey.from_string(pubkey.to_string(),
                                                   curve=pubkey.curve)
示例#4
0
    def __init__(self, public_key: str = None, private_key: str = None):
        """

        :param public_key: base58 encoded
        :param private_key: base58 encoded
        """
        self.__public_key = None
        self.__private_key = None

        if private_key is not None:
            self.__private_key = SigningKey.from_string(
                b58decode(private_key),
                curve=NIST256p
            )
            self.__public_key = self.__private_key.get_verifying_key()

        if public_key is not None:
            self.__public_key = VerifyingKey.from_string(
                self.decompress(b58decode(public_key))[1:],
                curve=NIST256p
            )

        if public_key is None and private_key is None:
            self.__private_key = SigningKey.generate(curve=NIST256p)
            self.__public_key = self.__private_key.get_verifying_key()
示例#5
0
    def verify_jws(self, raw_jws: str, did_document: DidDocument or None):
        c = raw_jws.split('.')
        data = {
            'protected':
            json.loads(base64url_decode(str(c[0])).decode('utf-8')),
            'payload': json.loads(base64url_decode(str(c[1])).decode('utf-8')),
            'signature': base64url_decode(str(c[2]))
        }
        key_id = data['protected']['kid']
        issuer = data['payload']['iss']

        if did_document is None:
            _cache_pub_key_of_issuer = self.document.get_public_key(
                key_id=key_id)
            if not _cache_pub_key_of_issuer:
                self.document = self.__get_document(issuer)

        pub_key_of_issuer = self.document.get_public_key(key_id=key_id)
        if not pub_key_of_issuer:
            raise DidNotFoundException(
                error_message=f"Not Found KeyID in did document {issuer}")

        user_pub_key_hex = pub_key_of_issuer.get('publicKeyHex')
        if not user_pub_key_hex:
            return None

        user_pub_key = jwk.JWK.from_pem(
            VerifyingKey.from_string(bytes.fromhex(user_pub_key_hex),
                                     curve=SECP256k1).to_pem())
        return VerifiableSignedJWT.verify(token=raw_jws, key=user_pub_key)
示例#6
0
    def initiate_secure_channel(self, peer_pubkey_bytes):
        logger.debug("In initiate_secure_channel()")

        self.sc_IVcounter = 1

        #using ecdsa
        self.sc_peer_pubkey = VerifyingKey.from_string(peer_pubkey_bytes,
                                                       curve=SECP256k1)
        self.ecdh.load_received_public_key(self.sc_peer_pubkey)
        self.shared_key = self.ecdh.generate_sharedsecret_bytes()

        #logger.debug("Shared key:"+ self.shared_key.hex()) #debug

        mac = hmac.new(self.shared_key, "sc_key".encode('utf-8'), sha1)
        self.derived_key = mac.digest()[:16]
        mac = hmac.new(self.shared_key, "sc_mac".encode('utf-8'), sha1)
        self.mac_key = mac.digest()

        # alternative derivation
        # tmp_key= sha256(self.shared_key).digest()
        # self.derived_key = tmp_key[:16]
        # tmp_key= sha256(tmp_key).digest()
        # self.mac_key= tmp_key[:20]

        # logger.debug("Derived_key key:"+ self.derived_key.hex()) #debug
        # logger.debug("Mac_key key:"+ self.mac_key.hex()) #debug

        self.initialized_secure_channel = True
示例#7
0
def sign_from_json(cmd, filepath: Path):
    tx_dct: Dict[str, Any] = json.load(open(filepath, "r"))

    raw_utxos: List[Tuple[bytes, int]] = [
        (bytes.fromhex(utxo_dct["raw"]), output_index)
        for utxo_dct in tx_dct["utxos"]
        for output_index in utxo_dct["output_indexes"]
    ]
    to_address: str = tx_dct["to"]
    to_amount: int = tx_dct["amount"]
    fees: int = tx_dct["fees"]

    sigs = cmd.sign_new_tx(address=to_address,
                           amount=to_amount,
                           fees=fees,
                           change_path=tx_dct["change_path"],
                           sign_paths=tx_dct["sign_paths"],
                           raw_utxos=raw_utxos,
                           lock_time=tx_dct["lock_time"])

    expected_tx = CTransaction.from_bytes(bytes.fromhex(tx_dct["raw"]))
    witnesses = expected_tx.wit.vtxinwit
    for witness, (tx_hash_digest, sign_pub_key,
                  (v, der_sig)) in zip(witnesses, sigs):
        expected_der_sig, expected_pubkey = witness.scriptWitness.stack
        assert expected_pubkey == sign_pub_key
        assert expected_der_sig == der_sig
        pk: VerifyingKey = VerifyingKey.from_string(sign_pub_key,
                                                    curve=SECP256k1,
                                                    hashfunc=sha256)
        assert pk.verify_digest(
            signature=der_sig[:-1],  # remove sighash
            digest=tx_hash_digest,
            sigdecode=sigdecode_der) is True
示例#8
0
    def __init__(self, pubkey: bytes):
        if len(pubkey) != 64 + 1 or pubkey[0] != 0x04:
            raise ValueError

        self.vk = VerifyingKey.from_string(pubkey[1:],
                                           SECP256k1,
                                           validate_point=True)
示例#9
0
 def encrypt_with_cbc_mode(plain_text: bytes,
                           public_key: bytes,
                           iv: bytes = b'') -> (bytes, bytes, bytes):
     if not isinstance(public_key, bytes):
         raise SDKException(
             ErrorCode.other_error(
                 'the type of public key should be bytes.'))
     if len(public_key) != 33:
         raise SDKException(
             ErrorCode.other_error(
                 'the length of public key should be 33 bytes.'))
     if not (public_key.startswith(b'\x02')
             or public_key.startswith(b'\x03')):
         raise SDKException(ErrorCode.other_error('Invalid public key.'))
     public_key = ECIES.__uncompress_public_key(public_key)
     r = randint(1, NIST256p.order)
     g_tilde = r * NIST256p.generator
     h_tilde = r * VerifyingKey.from_string(string=public_key,
                                            curve=NIST256p).pubkey.point
     str_g_tilde_x = number_to_string(g_tilde.x(), NIST256p.order)
     str_g_tilde_y = number_to_string(g_tilde.y(), NIST256p.order)
     encode_g_tilde = b''.join([b'\x04', str_g_tilde_x, str_g_tilde_y])
     str_h_tilde_x = number_to_string(h_tilde.x(), NIST256p.order)
     seed = b''.join([encode_g_tilde, str_h_tilde_x])
     aes_key = pbkdf2(seed, 32)
     aes_iv, cipher_text = AESHandler.aes_cbc_encrypt(
         plain_text, aes_key, iv)
     return aes_iv, encode_g_tilde, cipher_text
示例#10
0
def _get_brave_api():
    config = app.config['BRAVE_AUTH']
    return API(config['endpoint'],
               config['identity'],
               SigningKey.from_string(unhexlify(config['private']),
                                      curve=NIST256p, hashfunc=sha256),
               VerifyingKey.from_string(unhexlify(config['public']),
                                        curve=NIST256p, hashfunc=sha256))
示例#11
0
    def __before__(self, *args, **kw):
        """Validate the request signature, load the relevant data."""

        if 'X-Service' not in request.headers or 'X-Signature' not in request.headers:
            log.error("Digitally signed request missing headers.")
            raise HTTPBadRequest("Missing headers.")

        try:
            request.service = self.__service__(request.headers['X-Service'])
        except:
            log.exception("Exception attempting to load service: %s",
                          request.headers['X-Service'])
            raise HTTPBadRequest("Unknown or invalid service identity.")

        hex_key = request.service.key.public.encode('utf-8')
        key = VerifyingKey.from_string(unhexlify(hex_key),
                                       curve=NIST256p,
                                       hashfunc=sha256)

        log.debug(
            "Canonical request:\n\n\"{r.headers[Date]}\n{r.url}\n{r.body}\"".
            format(r=request))

        date = datetime.strptime(request.headers['Date'],
                                 '%a, %d %b %Y %H:%M:%S GMT')
        if datetime.utcnow() - date > timedelta(seconds=15):
            log.warning(
                "Received request that is over 15 seconds old, rejecting.")
            raise HTTPBadRequest("Request over 15 seconds old.")

        # We allow requests 1s from the future to account for slight clock skew.
        if datetime.utcnow() - date < timedelta(seconds=-1):
            log.warning(
                "Received a request from the future; please check this systems time for validity."
            )
            raise HTTPBadRequest(
                "Request from the future, please check your time for validity."
            )

        try:
            key.verify(
                unhexlify(request.headers['X-Signature']),
                "{r.headers[Date]}\n{r.url}\n{r.body}".format(r=request))
        except BadSignatureError:
            try:
                # Try verifying again with the time adjusted by one second.
                date = date - timedelta(seconds=1)
                key.verify(
                    unhexlify(request.headers['X-Signature']),
                    "{date}\n{r.url}\n{r.body}".format(
                        r=request,
                        date=date.strftime('%a, %d %b %Y %H:%M:%S GMT')))
            except BadSignatureError:
                raise HTTPBadRequest("Invalid request signature.")

        return args, kw
示例#12
0
def verify_signature(message, public_key, signature):
    public_key = uncompress_ecdsa_public_key(public_key)
    verifying_key = VerifyingKey.from_string(unhexlify(public_key), SECP256k1,
                                             hashlib.sha256)
    try:
        verifying_key.verify(unhexlify(signature), message.encode(),
                             hashlib.sha256, sigdecode_der)
    except (BadSignatureError, UnexpectedDER):
        return False
    return True
示例#13
0
 def verify_signature(public_key: bytes, signature: bytes, msg: bytes):
     if not isinstance(public_key, bytes):
         raise BotException(BotError.invalid_public_key)
     if len(public_key) != 64:
         raise BotException(BotError.invalid_public_key)
     public_key = VerifyingKey.from_string(string=public_key, curve=SECP256k1)
     try:
         result = public_key.verify(signature, msg)
     except BadSignatureError:
         result = False
     return result
示例#14
0
 def __init__(self, app):
     self.endpoint = app.config['CORE_ENDPOINT']
     self.app_id = app.config['CORE_APP_ID']
     self.private_key_string = app.config['CORE_PRIVATE_KEY']
     self.core_public_key_string = app.config['CORE_CORE_PUBLIC_KEY']
     
     self.private_key = SigningKey.from_string(unhexlify(self.private_key_string), curve=NIST256p, hashfunc=sha256)
     self.core_public_key = VerifyingKey.from_string(unhexlify(self.core_public_key_string), curve=NIST256p, hashfunc=sha256)
     
     self.view_perm = app.config['CORE_VIEW_PERMISSION']
     self.edit_perm = app.config['CORE_EDIT_PERMISSION']
示例#15
0
 def __init__(self):
     from brave.mumble import util
     
     # Configure mail delivery services.
     util.mail = Mailer(config, 'mail')
     util.mail.start()
     
     # Load our keys into a usable form.
     config['api.private'] = SigningKey.from_string(unhexlify(config['api.private']), curve=NIST256p, hashfunc=sha256)
     config['api.public'] = VerifyingKey.from_string(unhexlify(config['api.public']), curve=NIST256p, hashfunc=sha256)
     
     super(StartupMixIn, self).__init__()
 def verify_jwt(self, jwt_data: str, raw_public_key: str):
     try:
         pem = VerifyingKey.from_string(decode_hex(raw_public_key),
                                        curve=SECP256k1).to_pem()
         verifying_key = jwk.JWK.from_pem(pem)
         jws_token = jws.JWS(jwt_data)
         jws_token.deserialize(jwt_data)
         jws_token.allowed_algs.extend([self.algorithm])
         jws_token.verify(verifying_key, alg=self.algorithm)
         return True
     except jws.InvalidJWSSignature:
         return False
示例#17
0
def get_brave_api():
    import braveapi.client
    from binascii import unhexlify
    from hashlib import sha256
    from ecdsa.keys import SigningKey, VerifyingKey
    from ecdsa.curves import NIST256p

    endpoint = config.braveapi_endpoint
    my_id = config.braveapi_my_id
    my_privkey = SigningKey.from_string(unhexlify(config.braveapi_my_privkey), curve=NIST256p, hashfunc=sha256)
    server_pubkey = VerifyingKey.from_string(unhexlify(config.braveapi_server_pubkey), curve=NIST256p, hashfunc=sha256)

    return braveapi.client.API(endpoint, my_id, my_privkey, server_pubkey)
示例#18
0
 def encrypt_with_cbc_mode(plain_text: bytes, public_key: bytes) -> (bytes, bytes, bytes):
     if not isinstance(public_key, bytes):
         raise BotException(BotError.invalid_public_key)
     if len(public_key) != 64:
         raise BotException(BotError.invalid_public_key)
     r = randint(1, SECP256k1.order)
     g_tilde = r * SECP256k1.generator
     h_tilde = r * VerifyingKey.from_string(string=public_key, curve=SECP256k1).pubkey.point
     str_g_tilde_x = number_to_string(g_tilde.x(), SECP256k1.order)
     str_g_tilde_y = number_to_string(g_tilde.y(), SECP256k1.order)
     encode_g_tilde = b''.join([b'\x04', str_g_tilde_x, str_g_tilde_y])
     str_h_tilde_x = number_to_string(h_tilde.x(), SECP256k1.order)
     seed = b''.join([encode_g_tilde, str_h_tilde_x])
     aes_key = pbkdf2(seed, 32)
     aes_iv, cipher_text = AESHandler.aes_cbc_encrypt(plain_text, aes_key)
     return aes_iv, encode_g_tilde, cipher_text
示例#19
0
    def GET(self):

        try:
            private = SigningKey.from_string(unhexlify(settings['api']['private']), curve=NIST256p, hashfunc=sha256)
            public = VerifyingKey.from_string(unhexlify(settings['api']['public']), curve=NIST256p, hashfunc=sha256)
        except:
            return "Invalid keys"
        # Perform the initial API call and direct the user.
        api = API(settings['api']['endpoint'], settings['api']['identity'], private, public)

        success = str(settings['domain'] + settings['path'] + '/account/authorized')
        failure = str(settings['domain'] + settings['path'] + '/account/nolove')

        result = api.core.authorize(success=success, failure=failure)

        raise web.seeother(result.location, absolute=True)
示例#20
0
    def compress(public_key: bytes):
        """
        This method is avaliable for any curves.

        The result is a flag (0x02 y is even otherwise 0x03) connecting x with discarding y.

        :param public_key: public key bytes in uncompressed representation
        :return:
        """
        order = NIST256p.generator.order()
        pk_bytes = public_key[1:]
        pk_obj = VerifyingKey.from_string(pk_bytes, curve=NIST256p)
        point = pk_obj.pubkey.point

        flag = bytes([2 + (point.y() & 1)])
        x_bytes = number_to_string(point.x(), order)
        return flag + x_bytes
示例#21
0
文件: util.py 项目: Acidity/irc
 def __init__(self):
     # Load our keys into a usable form.
     try:
         config['api.private'] = SigningKey.from_string(unhexlify(config['api.private']), curve=NIST256p, hashfunc=sha256)
         config['api.public'] = VerifyingKey.from_string(unhexlify(config['api.public']), curve=NIST256p, hashfunc=sha256)
     except:
         log.critical("Core Service API identity, public, or private key missing.")
         
         private = SigningKey.generate(NIST256p, hashfunc=sha256)
         
         log.critical("Here's a new private key; update the api.private setting to reflect this.\n%s", private.to_string().encode('hex'))
         log.critical("Here's that key's public key; this is what you register with Core.\n%s",  private.get_verifying_key().to_string().encode('hex'))
         log.critical("After registering, save the server's public key to api.public and your service's ID to api.identity.")
         
         exit(-1)
     
     super(StartupMixIn, self).__init__()
示例#22
0
文件: util.py 项目: paxswill/mumble
    def __init__(self):
        from brave.mumble import util

        # Configure mail delivery services.
        util.mail = Mailer(config, 'mail')
        util.mail.start()

        # Load our keys into a usable form.
        config['api.private'] = SigningKey.from_string(unhexlify(
            config['api.private']),
                                                       curve=NIST256p,
                                                       hashfunc=sha256)
        config['api.public'] = VerifyingKey.from_string(unhexlify(
            config['api.public']),
                                                        curve=NIST256p,
                                                        hashfunc=sha256)

        super(StartupMixIn, self).__init__()
示例#23
0
def get_brave_api():
    import braveapi.client
    from binascii import unhexlify
    from hashlib import sha256
    from ecdsa.keys import SigningKey, VerifyingKey
    from ecdsa.curves import NIST256p

    endpoint = config.braveapi_endpoint
    my_id = config.braveapi_my_id
    my_privkey = SigningKey.from_string(unhexlify(config.braveapi_my_privkey),
                                        curve=NIST256p,
                                        hashfunc=sha256)
    server_pubkey = VerifyingKey.from_string(unhexlify(
        config.braveapi_server_pubkey),
                                             curve=NIST256p,
                                             hashfunc=sha256)

    return braveapi.client.API(endpoint, my_id, my_privkey, server_pubkey)
示例#24
0
def authorize():

    # Convert Key text into objects
    config['api.private'] = SigningKey.from_string(unhexlify(config['api.private']), curve=NIST256p, hashfunc=sha256)
    config['api.public'] = VerifyingKey.from_string(unhexlify(config['api.public']), curve=NIST256p, hashfunc=sha256)

    # Build API Client for CORE Services
    api = API(config['api.endpoint'], config['api.identity'], config['api.private'], config['api.public'])

    # Build Success/Failure Redirect URLs
    success = str("http://"+app.config['SERVER_NAME']+url_for('authorized'))
    failure = str("http://"+app.config['SERVER_NAME']+url_for('fail'))

    # Make the authentication call to the CORE Service
    result = api.core.authorize(success=success, failure=failure)

    # Redirect based on the authentication request validity
    return redirect(result.location)
示例#25
0
def verifySignatureFromBytes(data, publicKey, signature):
	"""
	Verify signature.

	Arguments:
	data (bytes) -- data in bytes
	publicKey (str) -- a public key as hex string
	signature (str) -- a signature as hex string

	Return bool
	"""
	if len(publicKey) == 66:
		publicKey = uncompressEcdsaPublicKey(publicKey)
	verifyingKey = VerifyingKey.from_string(unhexlify(publicKey), SECP256k1, hashlib.sha256)
	try:
		verifyingKey.verify(unhexlify(signature), data, hashlib.sha256, sigdecode_der)
	except (BadSignatureError, UnexpectedDER):
		return False
	return True
示例#26
0
文件: keys.py 项目: ulamlabs/aioxrpy
    def __init__(self,
                 *,
                 private_key: Optional[Union[str, bytes]] = None,
                 public_key: Optional[bytes] = None):
        assert not (private_key and public_key), 'Pass only one key'
        if public_key:
            self._sk = None
            self._vk = VerifyingKey.from_string(public_key, curve=SECP256k1)
            return

        if private_key:
            if isinstance(private_key, str):
                self._sk = signing_key_from_seed(private_key)
            else:
                self._sk = SigningKey.from_string(private_key, curve=SECP256k1)
        else:
            entropy = PRNG(secrets.randbits(512))
            self._sk = SigningKey.generate(entropy=entropy, curve=SECP256k1)

        self._vk = self._sk.get_verifying_key()
示例#27
0
 def __before__(self, *args, **kw):
     """Validate the request signature, load the relevant data."""
     
     if 'X-Service' not in request.headers or 'X-Signature' not in request.headers:
         log.error("Digitally signed request missing headers.")
         raise HTTPBadRequest("Missing headers.")
     
     try:
         request.service = self.__service__(request.headers['X-Service']))
     except:
         log.exception("Exception attempting to load service: %s", request.headers['X-Service'])
         raise HTTPBadRequest("Unknown or invalid service identity.")
     
     key = VerifyingKey.from_string(unhexlify(request.service.key.public), curve=NIST256p, hashfunc=sha256)
     
     log.debug("Canonical request:\n\n\"{r.headers[Date]}\n{r.url}\n{r.body}\"".format(r=request))
     
     if not key.verify(
             unhexlify(request.headers['X-Signature']),
             "{r.headers[Date]}\n{r.url}\n{r.body}".format(r=request)):
示例#28
0
    def test_signing(self):
        seed = unhexlify('c882685a2859016f26ea3b95d3d06929')  # tools.generate_seed(tools.STRENGTH_LOW, '')
        data = 'nazdar bazar'
        hsh = sha256(data).digest()
        
        # Generate secexp
        xprv = BIP32.get_xprv_from_seed(seed)
        bip32 = BIP32(xprv)

        # Get signing key and sign some data
        signing = bip32._get_master_private_key()
        signature = signing.sign_digest_deterministic(hsh, sha256)

        # Transform secexp into master public key
        master_public_key = bip32.get_master_public_key()

        # Load verifying class from master public key
        verifying = VerifyingKey.from_string(unhexlify(master_public_key), SECP256k1)

        # Check that signature is valid using master public key
        self.assertTrue(verifying.verify(signature, data, sha256))
示例#29
0
    def __init__(self, public_key_string, version_byte=None, verify=True):
        """ Takes in a public key in hex format.
        """
        # set the version byte
        if version_byte:
            self._version_byte = version_byte
        self._charencoding, self._type = get_public_key_format(
            public_key_string)

        # extract the binary bitcoin key (compressed/uncompressed w magic byte)
        self._bin_public_key = extract_bin_bitcoin_pubkey(public_key_string)

        # extract the bin ecdsa public key (uncompressed, w/out a magic byte)
        bin_ecdsa_public_key = extract_bin_ecdsa_pubkey(public_key_string)
        if verify:
            try:
                # create the ecdsa key object
                self._ecdsa_public_key = VerifyingKey.from_string(
                    bin_ecdsa_public_key, self._curve)
            except AssertionError as e:
                raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
示例#30
0
    def __init__(self, public_key_string, version_byte=None, verify=True):
        """ Takes in a public key in hex format.
        """
        # set the version byte
        if version_byte:
            self._version_byte = version_byte
        self._charencoding, self._type = get_public_key_format(
            public_key_string)

        # extract the binary bitcoin key (compressed/uncompressed w magic byte)
        self._bin_public_key = extract_bin_bitcoin_pubkey(public_key_string)

        # extract the bin ecdsa public key (uncompressed, w/out a magic byte)
        bin_ecdsa_public_key = extract_bin_ecdsa_pubkey(public_key_string)
        if verify:
            try:
                # create the ecdsa key object
                self._ecdsa_public_key = VerifyingKey.from_string(
                    bin_ecdsa_public_key, self._curve)
            except AssertionError as e:
                raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
示例#31
0
def test_sign_tx(cmd, button):
    bip32_path: str = "m/44'/0'/0'/0/0"

    pub_key, chain_code = cmd.get_public_key(
        bip32_path=bip32_path, display=False)  # type: bytes, bytes

    pk: VerifyingKey = VerifyingKey.from_string(pub_key,
                                                curve=SECP256k1,
                                                hashfunc=sha256)

    tx = Transaction(nonce=1,
                     to="0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae",
                     value=666,
                     memo="For u EthDev")

    v, der_sig = cmd.sign_tx(bip32_path=bip32_path,
                             transaction=tx,
                             button=button)

    assert pk.verify(signature=der_sig,
                     data=tx.serialize(),
                     hashfunc=keccak_256,
                     sigdecode=sigdecode_der) is True
示例#32
0
文件: controller.py 项目: Acidity/api
 def __before__(self, *args, **kw):
     """Validate the request signature, load the relevant data."""
     
     if 'X-Service' not in request.headers or 'X-Signature' not in request.headers:
         log.error("Digitally signed request missing headers.")
         raise HTTPBadRequest("Missing headers.")
     
     try:
         request.service = self.__service__(request.headers['X-Service']))
     except:
         log.exception("Exception attempting to load service: %s", request.headers['X-Service'])
         raise HTTPBadRequest("Unknown or invalid service identity.")
     
     key = VerifyingKey.from_string(unhexlify(request.service.key.public), curve=NIST256p, hashfunc=sha256)
     
     log.debug("Canonical request:\n\n\"{r.headers[Date]}\n{r.url}\n{r.body}\"".format(r=request))
     
     if not key.verify(
             unhexlify(request.headers['X-Signature']),
             "{r.headers[Date]}\n{r.url}\n{r.body}".format(r=request)):
         raise HTTPBadRequest("Invalid request signature.")
     
     return args, kw
示例#33
0
    def __init__(self, public_key, version_byte=0):
        """ Takes in a public key in hex format.
        """
        self._version_byte = version_byte

        if is_hex(public_key) and len(public_key) == 130 and public_key[0:2] == '04':
            public_key = public_key[2:]
        elif len(public_key) == 65 and public_key[0] == '\x04':
            public_key = public_key[1:]

        if is_hex_ecdsa_pubkey(public_key):
            bin_public_key = unhexlify(public_key)
        elif is_binary_ecdsa_pubkey(public_key):
            bin_public_key = public_key
        else:
            raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
        
        try:
            self._ecdsa_public_key = VerifyingKey.from_string(
                bin_public_key, self._curve)
        except AssertionError as e:
            raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
        
        self._bin_hash160 = bin_hash160(self.to_bin(prefix=True))
示例#34
0
    def authenticate(self, identifier, password=None):
        """Validate the given identifier; password is ignored."""
        from brave.notes.config import settings
        try:
            private = SigningKey.from_string(unhexlify(settings['api']['private']), curve=NIST256p, hashfunc=sha256)
            public = VerifyingKey.from_string(unhexlify(settings['api']['public']), curve=NIST256p, hashfunc=sha256)
        except:
            return "Invalid keys"

        api = API(settings['api']['endpoint'], settings['api']['identity'], private, public)
        result = api.core.info(identifier)
        
        user = self.objects(character__id=result.character.id).first()
        
        if not user:
            user = self(token=identifier, expires=result.expires, seen=datetime.utcnow())
            user.character.id = result.character.id
            user.character.name = result.character.name
            user.corporation.id = result.corporation.id
            user.corporation.name = result.corporation.name
            
            if result.alliance:
                user.alliance.id = result.alliance.id
                user.alliance.name = result.alliance.name
            
            user.save()
        
        else:
            # TODO: Also update the corporate details, if appropriate.
            user.update(set__token=identifier, set__seen=datetime.utcnow())
        
        from brave.notes.core.session import session
        session.user = user
        session.signedin = 1
        
        return user.id, user
示例#35
0
def config():
    # Load and validate the format of our auth config data
    try:
        config['api.identity']
        config['api.private'] = SigningKey.from_string(unhexlify(config['api.private']), curve=NIST256p, hashfunc=sha256)
        config['api.public'] = VerifyingKey.from_string(unhexlify(config['api.public']), curve=NIST256p, hashfunc=sha256)
    except:
        private = SigningKey.generate(NIST256p, hashfunc=sha256)

        error_message = "Core Service API identity, public, or private key missing.<br /><br />\n\n"

        error_message += "Here's a new private key; update the api.private setting to reflect this.<br />\n" + \
                         "%s <br /><br />\n\n" % private.to_string().encode('hex')

        error_message += "Here's that key's public key; this is what you register with Core.<br />\n" + \
                         "%s <br /><br /><br />\n\n" % private.get_verifying_key().to_string().encode('hex')

        error_message += "After registering, save the server's public key to api.public " + \
                         "and your service's ID to api.identity.<br /><br />"

        return error_message

    # config data looks good, allow auth attempt
    return '<a href="'+url_for('authorize')+'">Click here to auth</a>'
示例#36
0
def get_api(config):
    my_priv_key = SigningKey.from_string(config.get('core', 'app.priv_key').decode('hex'), curve=NIST256p, hashfunc=sha256)
    server_pub_key = VerifyingKey.from_string(config.get('core', 'server.pub_key').decode('hex'), curve=NIST256p, hashfunc=sha256)
    return API(config.get('core', 'server.endpoint'), config.get('core', 'app.id'), my_priv_key, server_pub_key)
示例#37
0
def generate_shared_key(sk, vk_str) -> bytes:
    vk = VerifyingKey.from_string(a2b_hex(vk_str), NIST256p)
    point = sk.privkey.secret_multiplier * vk.pubkey.point
    return sha256(point.x().to_bytes(32, 'big')).digest()