Ejemplo n.º 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)
Ejemplo n.º 2
0
    def check_sig(*args, **kwargs):

        id = get_id()

        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:
            xidentity = request.headers.get('x-identity').decode('hex')
            vk = from_sec(xidentity) or VerifyingKey.from_der(xidentity)
        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:
            url = urlparse(request.url).hostname.rstrip('/') + request.path
            verified = vk.verify(sig.decode('hex'), str(request.method) + str(url) + str(request.data), hashfunc=sha256, sigdecode=sigdecode_der)
            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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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
Ejemplo n.º 5
0
 def post(self, **kw):
     if not request.is_xhr:
         raise HTTPNotFound()
     
     app = self.app
     valid, invalid = manage_form().native(kw)
     
     for k in ('name', 'description', 'groups', 'site', 'contact'):
         setattr(app, k, valid[k])
     
     if valid['key']['public'].startswith('-'):
         # Assume PEM format.
         valid['key']['public'] = hexlify(VerifyingKey.from_pem(valid['key']['public']).to_string())
     
     app.key.public = valid['key']['public']
     app.mask.required = valid['required'] or 0
     app.mask.optional = valid['optional'] or 0
     
     if valid['development'] == "true" or valid['development'] == "True":
         app.development = True
     else:
         app.development = False
     
     app.save()
     
     return 'json:', dict(
             success = True,
         )
Ejemplo n.º 6
0
def ecdsa_key_to_bin(ecdsa_key_file):
    with open(ecdsa_key_file, 'r') as f:
        ecdsa_key_str = f.read()
    vk = VerifyingKey.from_pem(ecdsa_key_str)
    _x = vk.pubkey.point.x()
    _y = vk.pubkey.point.y()
    x = bitarray(bin(_x)[2:])
    y = bitarray(bin(_y)[2:])
    x_remain = (8-(len(x) % 8)) % 8
    y_remain = (8-(len(y) % 8)) % 8
    for _ in range(0, x_remain):
        x.insert(0, 0)
    for _ in range(0, y_remain):
        y.insert(0, 0)

    x = x.tobytes()
    y = y.tobytes()
    x_b = bytearray(x)
    y_b = bytearray(y)

    key_bin = bytearray(48 * 2)
    insert_bytearray(x_b, key_bin, 0)
    insert_bytearray(y_b, key_bin, 48)

    return key_bin
Ejemplo n.º 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
Ejemplo n.º 8
0
    def __init__(self, x, y, curve_name, secret_multiplier=None):
        if not curve_name:
            raise ValueError("curve_name must be specified")
        self.curve_name = curve_name

        for c in curves:
            if c.name == curve_name or c.openssl_name == curve_name:
                curve = c
                break
        else:
            raise ValueError(
                "Curve '{0}' not supported by python-ecdsa".format(curve_name))

        self.private_key = None
        self.public_key = None
        self.key_type = "ecdsa"

        if secret_multiplier:
            self.private_key = SigningKey.from_secret_exponent(
                secret_multiplier, curve)

        if x and y:
            point = Point(curve.curve, x, y)
            self.public_key = VerifyingKey.from_public_point(point, curve)

        if not self.public_key:
            self.public_key = self.private_key.get_verifying_key()
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
    def post(self, **kw):
        if not request.is_xhr:
            raise HTTPNotFound()

        app = self.app
        valid, invalid = manage_form().native(kw)

        for k in ('name', 'description', 'groups', 'site', 'contact'):
            setattr(app, k, valid[k])

        if valid['key']['public'].startswith('-'):
            # Assume PEM format.
            valid['key']['public'] = hexlify(
                VerifyingKey.from_pem(valid['key']['public']).to_string())

        app.key.public = valid['key']['public']
        app.mask.required = valid['required'] or 0
        app.mask.optional = valid['optional'] or 0

        if valid['development'] == "true" or valid['development'] == "True":
            app.development = True
        else:
            app.development = False

        app.save()

        return 'json:', dict(success=True, )
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
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
Ejemplo n.º 15
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))
Ejemplo n.º 16
0
    def verify(cls, key: 'EC2', data: bytes, signature: bytes) -> bool:
        p = Point(curve=cls.get_curve().curve, x=int(hexlify(key.x), 16), y=int(hexlify(key.y), 16))

        vk = VerifyingKey.from_public_point(p, cls.get_curve(), cls.get_hash_func(), validate_point=True)

        try:
            return vk.verify(signature=signature, data=data, hashfunc=cls.get_hash_func())
        except BadSignatureError:
            return False
Ejemplo n.º 17
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
Ejemplo n.º 18
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
Ejemplo n.º 19
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
Ejemplo n.º 20
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']
 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
Ejemplo n.º 22
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__()
Ejemplo n.º 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)
Ejemplo n.º 24
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)
Ejemplo n.º 25
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
Ejemplo n.º 26
0
    def _eddsa_pubkey_parsing(self, subject_public_key_info):
        """
        Convert the raw DER encoded EdDSA parameters into public key object.

        :param subject_public_key_info: bytes like object with the DER encoded
            public key in it
        """
        try:
            # python ecdsa knows how to parse curve OIDs so re-use that
            # code
            public_key = VerifyingKey.from_der(
                compatHMAC(subject_public_key_info))
        except Exception:
            raise SyntaxError("Malformed or unsupported public key in "
                              "certificate")
        self.publicKey = _create_public_eddsa_key(public_key)
Ejemplo n.º 27
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
Ejemplo n.º 28
0
Archivo: util.py Proyecto: 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__()
Ejemplo n.º 29
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__()
Ejemplo n.º 30
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)
Ejemplo n.º 31
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)
Ejemplo n.º 32
0
    def from_string(s: str) -> 'DuckietownToken':
        """
        Decodes a Duckietown Token string into an instance of
        :py:class:`dt_authentication.DuckietownToken`.

        Args:
            s:  The Duckietown Token string.

        Raises:
            InvalidToken:   The given token is not valid.
        """
        # break token into 3 pieces, dt1-PAYLOAD-SIGNATURE
        p = s.split('-')
        # check number of components
        if len(p) != 3:
            raise InvalidToken(
                "The token should be comprised of three (dash-separated) parts"
            )
        # unpack components
        version, payload_base58, signature_base58 = p
        # check token version
        if version != DuckietownToken.VERSION:
            raise InvalidToken("Duckietown Token version '%s' not supported" %
                               version)
        # decode payload and signature
        payload_json = b58decode(payload_base58)
        signature = b58decode(signature_base58)
        # verify token
        vk = VerifyingKey.from_pem(PUBLIC_KEY)
        is_valid = False
        try:
            is_valid = vk.verify(signature, payload_json)
        except BadSignatureError:
            pass
        # raise exception if the token is not valid
        if not is_valid:
            raise InvalidToken("Duckietown Token not valid")
        # unpack payload
        payload = json.loads(payload_json.decode("utf-8"))
        if not isinstance(payload, dict) or \
                len(set(payload.keys()).intersection(PAYLOAD_FIELDS)) != len(PAYLOAD_FIELDS):
            raise InvalidToken("Duckietown Token has an invalid payload")
        # ---
        return DuckietownToken(payload, str(signature))
Ejemplo n.º 33
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
Ejemplo n.º 34
0
    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()
Ejemplo n.º 35
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)):
Ejemplo n.º 36
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))
Ejemplo n.º 37
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'])
Ejemplo n.º 38
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'])
Ejemplo n.º 39
0
def signing_key_from_seed(encoded_seed: str) -> SigningKey:
    """
    Derives SigningKey from master seed.

    Reference:
    https://ripple.com/wiki/Account_Family#Root_Key_.28GenerateRootDeterministicKey.29
    """
    # Ripple seeds are base58-encoded and prefixed with letter "s"
    assert encoded_seed[0] == 's'
    seed = base58.b58decode_check(encoded_seed,
                                  alphabet=base58.RIPPLE_ALPHABET)[1:]

    seq = 0
    while True:
        private_gen = int.from_bytes(first_half_of_sha512(
            seed, seq.to_bytes(4, byteorder='big')),
                                     byteorder='big')
        seq += 1
        if SECP256k1.order >= private_gen:
            break

    public_key = VerifyingKey.from_public_point(SECP256k1.generator *
                                                private_gen,
                                                curve=SECP256k1)

    # Now that we have the private and public generators, we apparently
    # have to calculate a secret from them that can be used as a ECDSA
    # signing key.
    secret = i = 0
    public_gen_compressed = public_key.to_string(encoding='compressed')
    while True:
        secret = int.from_bytes(first_half_of_sha512(
            public_gen_compressed, bytes(4), i.to_bytes(4, byteorder='big')),
                                byteorder='big')
        i += 1
        if SECP256k1.order >= secret:
            break

    secret = (secret + private_gen) % SECP256k1.order
    return SigningKey.from_secret_exponent(secret, curve=SECP256k1)
Ejemplo n.º 40
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
Ejemplo n.º 41
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)):
         raise HTTPBadRequest("Invalid request signature.")
     
     return args, kw
Ejemplo n.º 42
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
Ejemplo n.º 43
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))
Ejemplo n.º 44
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>'
Ejemplo n.º 45
0
    def test_ecdh_check(self):
        '''
https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-23#appendix-C
        '''

        v_stc_material = {
            "kty": "EC",
            "crv": "P-256",
            "x": "gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0",
            "y": "SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps",
            "d": "0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo"
        }

        u_epk_material = {
            "kty": "EC",
            "crv": "P-256",
            "x": "weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ",
            "y": "e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck",
            "d": "VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw"
        }

        import re

        def _to_pub(km):
            return (
                int(re.search(r"P-(\d+)$", km['crv']).group(1)),
                (base64.long_from_b64(km['x']),
                 base64.long_from_b64(km['y'])),
            )

        def _to_pri(km):
            return (
                int(re.search(r"P-(\d+)$", km['crv']).group(1)),
                base64.long_from_b64(km['d']),
            )

        pub_tuple = _to_pub(v_stc_material)
        pri_tuple = _to_pri(v_stc_material)

        import pydoc
        curve = pydoc.locate('ecdsa.curves.NIST{0}p'.format(pub_tuple[0]))

        from ecdsa import (
            SigningKey, VerifyingKey,
            ellipticcurve as ec)

        x, y = pub_tuple[1]
        v_pub = VerifyingKey.from_public_point(
            ec.Point(curve.curve, x, y, curve.order),
            curve,
        )

        v_stc = SigningKey.from_secret_exponent(pri_tuple[1], curve)

        # Party U provides a ephemeral key
        pub_tuple = _to_pub(u_epk_material)
        pri_tuple = _to_pri(u_epk_material)

        x, y = pub_tuple[1]
        u_epk = SigningKey.from_secret_exponent(pri_tuple[1], curve)

        from jose.jwa.ec import ecdsa_dhZ

        # Party U compute
        shared_secret_u = ecdsa_dhZ(v_pub, u_epk)

        print("Aggreement:", base64.long_to_b64(shared_secret_u))

        from Crypto.Util.number import long_to_bytes
        from math import ceil

        block_size = int(ceil(pub_tuple[0] / 8.0))
        # bit number(512 )  / 8 -> octets

        Zu = long_to_bytes(shared_secret_u, block_size)

        Z_jwa = [158, 86, 217, 29, 129, 113, 53,
                 211, 114, 131, 66, 131, 191, 132,
                 38, 156, 251, 49, 110, 163, 218,
                 128, 106, 72, 246, 218, 167, 121,
                 140, 254, 144, 196]

        self.assertEqual(_ilist(Zu), Z_jwa)

        # Other Information used in Concat KDF
        # AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo
        from struct import pack

        def _otherInfo(alg, pu, pv, klen):
            return b('').join([
                pack("!I", len(alg)),
                alg,
                pack("!I", len(pu)),
                pu,
                pack("!I", len(pv)),
                pv,
                pack("!I", klen),
            ])

        oi_u = _otherInfo(
            b("A128GCM"),
            b("Alice"),
            b("Bob"),
            16 * 8,     # A128GCM
        )

        oi_jwa = [
            0, 0, 0, 7,
            65, 49, 50, 56, 71, 67, 77,
            0, 0, 0, 5,
            65, 108, 105, 99, 101,
            0, 0, 0, 3,
            66, 111, 98,
            0, 0, 0, 128]

        print(">>>>>>>", type(oi_u))
        print("<<<<<<<", oi_u)
        self.assertEqual(_ilist(oi_u), oi_jwa)

        # Coccat KDF : NIST defines SHA256
        from Crypto.Hash import SHA256

        def _ConcatKDF(Z, dkLen, otherInfo,
                       digest_method=SHA256):

            def _src(counter_bytes):
                return b("").join([counter_bytes, Z, otherInfo])

            from math import ceil
            from struct import pack

            dkm = b''   # Derived Key Material
            counter = 0
            klen = int(ceil(dkLen / 8.0))
            while len(dkm) < klen:
                counter += 1
                counter_b = pack("!I", counter)
                dkm += digest_method.new(_src(counter_b)).digest()

            return dkm[:klen]

        _derived_key_u = _ConcatKDF(Zu, 16 * 8, oi_u)

        # Party V recive Epemeral Public Key
        v_epk = u_epk.get_verifying_key()
        Zv = long_to_bytes(ecdsa_dhZ(v_epk, v_stc), block_size)

        _derived_key_v = _ConcatKDF(Zv, 16 * 8, oi_u)

        self.assertEqual(_derived_key_u, _derived_key_v)

        kd_jwa = [
            86, 170, 141, 234, 248, 35, 109, 32,
            92, 34, 40, 205, 113, 167, 16, 26]

        self.assertEqual(_ilist(_derived_key_u), kd_jwa)

        self.assertEqual(b("VqqN6vgjbSBcIijNcacQGg"),
                         base64.base64url_encode(_derived_key_u))
Ejemplo n.º 46
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)
Ejemplo n.º 47
0
def create_verifying_key(x, y):
    point = Point(SECP256k1.curve, x, y)
    return VerifyingKey.from_public_point(point, curve=SECP256k1)