Exemple #1
0
 def setUp(self):
     self.private_key = SigningKey.generate()
     self.public_keys = tuple(PublicKey.from_signing_key(SigningKey.generate()) for _ in range(2))
     self.operation = Operation(OperationRev(), 'http://example.com', self.public_keys)
     sign_object(PublicKey.from_signing_key(self.private_key), self.private_key, self.operation)
     self.uuid = self.operation.uuid
     self.identifier = Identifier.from_operation(self.operation)
Exemple #2
0
    def test_dhZ(self):
        from ecdsa.keys import SigningKey   # VerifyingKey
        from ecdsa.curves import NIST521p

        # Party V(recepient) declares a satic key pair
        curve = NIST521p
        v_stc = SigningKey.generate(curve=curve)

        # and advertise to Party U(Sender) ( U <--(pub key)-- V)
        v_pub = v_stc.get_verifying_key()
        self.assertEqual(v_pub.curve, curve)
        print(v_pub.curve)

        # Party U provides a ephemeral key
        u_epk = SigningKey.generate(curve=v_pub.curve)

        from jose.jwa import ec
        # Compute ECDH as shared secret
        # This shared secret itself is NOT have to be exchanged.
        shared_secret_u = ec.ecdsa_dhZ(v_pub, u_epk)

        # Party V recive Epemeral Public Key ( U --(pub key)--> V)
        v_epk = u_epk.get_verifying_key()

        # Party V compute
        shared_secret_v = ec.ecdsa_dhZ(v_epk, v_stc)

        # Secrete Agreeed!
        self.assertEqual(shared_secret_u, shared_secret_v)
    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()
Exemple #4
0
    def setUp(self):
        initialise_database('test_database_file')

        self.private_keys = [SigningKey.generate(), SigningKey.generate()]
        self.public_keys = [PublicKey.from_signing_key(private_key) for private_key in self.private_keys]

        self.operation = [
            Operation(OperationRev(), 'http://example.com/', [self.public_keys[1]]),
            Operation(OperationRev(), 'http://example2.com/', [self.public_keys[0], self.public_keys[1]]),
            Operation(OperationRev(), 'http://example3.com/', [self.public_keys[1]])
        ]
Exemple #5
0
    def test_new_keys(self):
        user = User.new_keys(curve=NIST256p)

        self.assertIsInstance(user, User)
        self.assertIsInstance(user._private_key, SigningKey)
        self.assertIsInstance(user._public_key.verifying_key, VerifyingKey)

        self.assertEqual(user._private_key.to_der(),
                         SigningKey.from_string(user._private_key.to_string(), NIST256p).to_der())

        self.assertEqual(len(user._private_key.to_der()), len(SigningKey.generate(curve=NIST256p).to_der()))
        self.assertNotEqual(len(user._private_key.to_der()), len(SigningKey.generate().to_der()))
Exemple #6
0
    def new_keys(cls, curve=NIST192p):  # TODO different curve as default?
        """
        Create new user using auto-generated keys.

        :param curve: private key's generation curve
        """
        return cls(SigningKey.generate(curve=curve))
Exemple #7
0
def getKeys(secret, seed=None):
    """
	Generate keyring containing public key, signing and checking keys as
	attribute.

	Keyword arguments:
	secret (str or bytes) -- a human pass phrase
	seed (byte) -- a sha256 sequence bytes (private key actualy)

	Return dict
	"""
    if secret and not isinstance(secret, bytes):
        secret = secret.encode('utf-8')
    seed = hashlib.sha256(secret).digest() if not seed else seed
    signingKey = SigningKey.from_secret_exponent(
        int(binascii.hexlify(seed), 16), SECP256k1, hashlib.sha256)
    publicKey = signingKey.get_verifying_key().to_string()
    return {
        "publicKey":
        hexlify(
            compressEcdsaPublicKey(publicKey) if cfg.compressed else publicKey
        ),
        "privateKey":
        hexlify(signingKey.to_string()),
        "wif":
        getWIF(seed)
    }
Exemple #8
0
 def get(self):
     app = self.app
     
     if request.is_xhr:
         return 'brave.core.template.form', dict(
                 kind = _("Application"),
                 form = manage_form('/application/manage/{0}'.format(app.id)),
                 data = dict(
                         name = app.name,
                         description = app.description,
                         site = app.site,
                         contact = app.contact,
                         development = app.development,
                         key = dict(
                                 public = app.key.public,
                                 private = app.key.private,
                             ),
                         required = app.mask.required,
                         optional = app.mask.optional,
                         groups = app.groups
                     )
             )
     
     key = SigningKey.from_string(unhexlify(app.key.private), curve=NIST256p, hashfunc=sha256)
     return 'brave.core.application.template.view_app', dict(
             app = app,
             key = hexlify(key.get_verifying_key().to_string()),
             pem = key.get_verifying_key().to_pem()
         )
Exemple #9
0
    def test_generate(self):
        def hexdigest(digester, data):
            import hashlib
            return hashlib.new(digester, data).hexdigest()

        def longdigest(digester, data):
            return int(hexdigest(digester, data), 16)

        from ecdsa.keys import SigningKey, VerifyingKey
        from ecdsa.curves import NIST521p

        pri = SigningKey.generate(curve=NIST521p)
        pub = pri.get_verifying_key()
        self.assertTrue(isinstance(pub, VerifyingKey))

        data = 'what a wonderfull world.'
        digest = longdigest('sha256', b(data))

        sig = pri.sign_number(digest)
        self.assertTrue(isinstance(sig, tuple))
        self.assertEqual(len(sig), 2)

        from ecdsa.ecdsa import Signature
        sigobj = Signature(*sig)        # (r, s)
        self.assertTrue(pub.pubkey.verifies(digest, sigobj))
Exemple #10
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()
Exemple #11
0
    def setUp(self):
        self.private_key = SigningKey.generate(curve=NIST256p)
        self.public_key = PublicKey.from_signing_key(self.private_key)

        self.operation = Operation(OperationRev(), 'http://example.com/', [self.public_key])

        sign_object(self.public_key, self.private_key, self.operation)
Exemple #12
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)
Exemple #13
0
    def test_exchage(self):
        from ecdsa import SigningKey, NIST521p

        alice_own = SigningKey.generate(curve=NIST521p)
        bob_own = SigningKey.generate(curve=NIST521p)

        alice_pri = alice_own.privkey
        alice_pub = alice_pri.public_key

        bob_pri = bob_own.privkey
        bob_pub = bob_pri.public_key

        alice_pub_point = alice_pub.point
        bob_pub_point = bob_pub.point

        print(alice_pub_point, bob_pub_point)
Exemple #14
0
    def setUp(self):

        self.patcher1 = patch('addressimo.util.get_id')
        self.patcher2 = patch('addressimo.util.create_json_response')
        self.patcher3 = patch('addressimo.util.request')
        self.patcher4 = patch('addressimo.util.VerifyingKey', wraps=VerifyingKey)

        self.mockGetId = self.patcher1.start()
        self.mockCreateJsonResponse = self.patcher2.start()
        self.mockRequest = self.patcher3.start()
        self.mockVerifyingKey = self.patcher4.start()

        self.mockRequest.url = 'http://addressimo.com/address/0123456789abcdef/sf'
        self.mockRequest.data = 'this is some crazy random data, dude! you know you gotta love this!'

        from ecdsa.keys import SigningKey
        from ecdsa.curves import SECP256k1

        self.sk = SigningKey.from_string(TEST_PRIVKEY.decode('hex'), curve=SECP256k1)
        sig = self.sk.sign('GETaddressimo.com/address/0123456789abcdef/sfthis is some crazy random data, dude! you know you gotta love this!', hashfunc=sha256, sigencode=sigencode_der)

        self.mockRequest.headers = {
            'x-identity': VerifyingKey.from_string(TEST_PUBKEY.decode('hex'), curve=curves.SECP256k1).to_der().encode('hex'),
            'x-signature': sig.encode('hex')
        }
        self.mockRequest.method = 'GET'
        self.mockRequest.path = '/address/0123456789abcdef/sf'

        self.mockIdObj = Mock()
        self.mockIdObj.auth_public_key = TEST_PUBKEY

        # Mock the decorator function -> We run self.decorated
        self.mock_func = MagicMock(return_value='fake_response')
        self.mock_func.__name__ = 'mock_func'
        self.decorated = requires_valid_signature(self.mock_func)
Exemple #15
0
    def __after__(self, result, *args, **kw):
        """Generate the JSON response and sign."""

        key = SigningKey.from_string(unhexlify(request.service.key.private),
                                     curve=NIST256p,
                                     hashfunc=sha256)

        response = Response(status=200, charset='utf-8')
        response.date = datetime.utcnow()
        response.last_modified = result.pop('updated', None)

        ct, body = render('json:', result)
        response.headers[b'Content-Type'] = str(
            ct)  # protect against lack of conversion in Flup
        response.body = body

        canon = "{req.service.id}\n{resp.headers[Date]}\n{req.url}\n{resp.body}".format(
            req=request, resp=response)
        response.headers[b'X-Signature'] = hexlify(key.sign(canon))
        log.debug("Signing response: %s", response.headers[b'X-Signature'])
        log.debug("Canonical data:\n%r", canon)

        del response.date  # TODO: This works around an odd bug of sending two Date header values.

        return response
Exemple #16
0
    def get(self):
        app = self.app

        if request.is_xhr:
            return 'brave.core.template.form', dict(
                kind=_("Application"),
                form=manage_form('/application/manage/{0}'.format(app.id)),
                data=dict(name=app.name,
                          description=app.description,
                          site=app.site,
                          contact=app.contact,
                          development=app.development,
                          key=dict(
                              public=app.key.public,
                              private=app.key.private,
                          ),
                          required=app.mask.required,
                          optional=app.mask.optional,
                          groups=app.groups))

        key = SigningKey.from_string(unhexlify(app.key.private),
                                     curve=NIST256p,
                                     hashfunc=sha256)
        return 'brave.core.application.template.view_app', dict(
            app=app,
            key=hexlify(key.get_verifying_key().to_string()),
            pem=key.get_verifying_key().to_pem())
Exemple #17
0
def unserializeKeys(serial, network=None):
    """
Unserialize `serial`.

Argument:
keys (ArkyDict) -- serialized keyring returned by serializeKeys

Returns ArkyDict ready to be used as keyring

>>> binascii.hexlify(unserializeKeys({
...	'wif': 'SB3BGPGRh1SRuQd52h7f5jsHUg1G9ATEvSeA7L5Bz4qySQww4k7N',
...	'data': '2d2d2d2d2d424547494e2045432050524956415445204b45592d2d2d2d2d0a4d485143415145\
454943753444564e374861506a69394d4459617146566f6139344f724e63574c2b39714a66365876314a364a6\
26f416347425375424241414b0a6f555144516741456f4375645839305442384c75526c4b36564e5353306630\
5270394737507a7045784b42656566476436544f5353714a5941476d564b7746410a3249336948445a2b354b3\
93853704275464a6a7943726a324c6b777049513d3d0a2d2d2d2d2d454e442045432050524956415445\
204b45592d2d2d2d2d0a'}).public)
b'03a02b9d5fdd1307c2ee4652ba54d492d1fd11a7d1bb3f3a44c4a05e79f19de933'
"""
    keys = ArkyDict()
    keys.network = cfg.__NETWORK__ if network == None else network  # use cfg.__NETWORK__ network by default
    keys.signingKey = SigningKey.from_pem(binascii.unhexlify(serial["data"]))
    keys.checkingKey = keys.signingKey.get_verifying_key()
    keys.public = _compressEcdsaPublicKey(keys.checkingKey.to_string())
    if "wif" in serial: keys.wif = serial["wif"]
    return keys
Exemple #18
0
def getKeys(secret="passphrase", seed=None, network=None):
    """
Generate keyring containing network, public and private key as attribute.
secret or seed have to be provided, if network is not, cfg.__NETWORK__ is
automatically selected.

Keyword arguments:
secret (str or bytes) -- a human pass phrase
seed (byte)           -- a sha256 sequence bytes
network (object)      -- a python object

Returns ArkyDict

>>> binascii.hexlify(getKeys("secret").public)
b'03a02b9d5fdd1307c2ee4652ba54d492d1fd11a7d1bb3f3a44c4a05e79f19de933'
"""
    network = ArkyDict(
        **network
    ) if network else cfg.__NETWORK__  # use cfg.__NETWORK__ network by default
    seed = hashlib.sha256(
        secret.encode("utf8") if not isinstance(secret, bytes) else secret
    ).digest() if not seed else seed

    keys = ArkyDict()
    # save wallet address
    keys.wif = getWIF(seed, network)
    # save network option
    keys.network = network
    # generate signing and verifying object and public key
    keys.signingKey = SigningKey.from_secret_exponent(
        int(binascii.hexlify(seed), 16), SECP256k1, hashlib.sha256)
    keys.checkingKey = keys.signingKey.get_verifying_key()
    keys.public = _compressEcdsaPublicKey(keys.checkingKey.to_string())

    return keys
Exemple #19
0
 def decrypt_with_gcm_mode(nonce: bytes, mac_tag: bytes, cipher_text: bytes,
                           private_key: bytes, hdr: bytes,
                           encode_g_tilde: bytes):
     if not isinstance(private_key, bytes):
         raise SDKException(
             ErrorCode.other_error(
                 'the length of private key should be 32 bytes.'))
     if len(private_key) != 32:
         raise SDKException(
             ErrorCode.other_error(
                 'the length of private key should be 32 bytes.'))
     str_g_tilde_x = encode_g_tilde[1:33]
     str_g_tilde_y = encode_g_tilde[33:65]
     g_tilde_x = string_to_number(str_g_tilde_x)
     g_tilde_y = string_to_number(str_g_tilde_y)
     g_tilde = Point(NIST256p.curve, g_tilde_x, g_tilde_y, NIST256p.order)
     h_tilde = g_tilde * SigningKey.from_string(
         string=private_key, curve=NIST256p).privkey.secret_multiplier
     seed = b''.join(
         [encode_g_tilde,
          number_to_string(h_tilde.x(), NIST256p.order)])
     aes_key = pbkdf2(seed, 32)
     plain_text = AESHandler.aes_gcm_decrypt(cipher_text, hdr, nonce,
                                             mac_tag, aes_key)
     return plain_text
Exemple #20
0
    def test_no_database(self):
        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Block.get_ids_list()

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Block.get(sha256(b'something').digest())

        private_key = SigningKey.generate()
        public_key = PublicKey.from_signing_key(private_key)

        operations = [
            Operation(OperationRev(), 'http://example0.com/', [public_key]),
            Operation(OperationRev(), 'http://example1.com/', [public_key])
        ]

        for op in operations:
            sign_object(public_key, private_key, op)

        block = Block.from_operations_list(BlockRev(), int(time.time()), operations)
        block.mine()
        sign_object(public_key, private_key, block)

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            block.put()

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            block.remove()
Exemple #21
0
    def setUp(self):

        self.patcher1 = patch("addressimo.util.get_id")
        self.patcher2 = patch("addressimo.util.create_json_response")
        self.patcher3 = patch("addressimo.util.request")
        self.patcher4 = patch("addressimo.util.VerifyingKey", wraps=VerifyingKey)

        self.mockGetId = self.patcher1.start()
        self.mockCreateJsonResponse = self.patcher2.start()
        self.mockRequest = self.patcher3.start()
        self.mockVerifyingKey = self.patcher4.start()

        self.mockRequest.url = "http://addressimo.com/address/0123456789abcdef/sf"
        self.mockRequest.data = "this is some crazy random data, dude! you know you gotta love this!"

        from ecdsa.keys import SigningKey
        from ecdsa.curves import SECP256k1

        self.sk = SigningKey.from_string(TEST_PRIVKEY.decode("hex"), curve=SECP256k1)
        sig = self.sk.sign(self.mockRequest.url + self.mockRequest.data, hashfunc=sha256, sigencode=sigencode_der)

        self.mockRequest.headers = {
            "x-identity": VerifyingKey.from_string(TEST_PUBKEY.decode("hex"), curve=curves.SECP256k1)
            .to_der()
            .encode("hex"),
            "x-signature": sig.encode("hex"),
        }

        self.mockIdObj = Mock()
        self.mockIdObj.auth_public_key = TEST_PUBKEY

        # Mock the decorator function -> We run self.decorated
        self.mock_func = MagicMock(return_value="fake_response")
        self.mock_func.__name__ = "mock_func"
        self.decorated = requires_valid_signature(self.mock_func)
 def __init__(self, private_key: str):
     # byes.fromhex expect a hex string without 0x
     private_key = self.remove_starting_0x(private_key)
     pem = SigningKey.from_string(bytes.fromhex(private_key),
                                  curve=SECP256k1).to_pem()
     self.signing_key = jwk.JWK.from_pem(pem)
     self.algorithm = 'ES256K'
Exemple #23
0
    def test_generate(self):
        from ecdsa import SigningKey, NIST521p

        sk = SigningKey.generate(curve=NIST521p)
        pri = sk.privkey
        pub = pri.public_key
        param = dict(
            crv=sk.curve,
            x=pub.point.x(),
            y=pub.point.y(),
            d=pri.secret_multiplier)

        # Curve
        from ecdsa.ellipticcurve import Point, CurveFp
        from ecdsa.ecdsa import curve_521

        self.assertTrue(isinstance(curve_521, CurveFp))
        self.assertTrue(isinstance(param['crv'].curve, CurveFp))
        self.assertEqual(curve_521, param['crv'].curve)
        self.assertEqual(pub.point.curve(), curve_521)

        # Point
        p_new = Point(curve_521, param['x'], param['y'])
        self.assertEqual(p_new, pub.point)
        self.assertTrue(isinstance(pub.point, Point))

        # Public Key
        from ecdsa.ecdsa import Public_key, generator_521
        self.assertEqual(generator_521, pub.generator)
        pub_new = Public_key(generator_521, p_new)

        # Private Key
        from ecdsa.ecdsa import Private_key
        pri_new = Private_key(pub_new, param['d'])

        # Signature
        from ecdsa.ecdsa import string_to_int, Signature
        from hashlib import sha512
        from uuid import uuid1
        rnd = uuid1().int
        msg = "hello, it's me.".encode('utf8')
        digest = string_to_int(sha512(msg).digest())
        signature_new = pri_new.sign(digest, rnd)
        signature_old = pri.sign(digest, rnd)
        self.assertTrue(isinstance(signature_new, Signature))
        self.assertEqual(signature_new.r, signature_old.r)
        self.assertEqual(signature_new.s, signature_old.s)
        import six      # python3 no long
        self.assertTrue(type(signature_new.r) in six.integer_types)
        self.assertTrue(type(signature_new.s) in six.integer_types)

        # Verify
        print(pub.verifies(digest, signature_new))
        print(pub_new.verifies(digest, signature_old))

        #
        print(dir(pri_new))
        print(dir(pub_new))
        print(dir(pub_new.curve))
Exemple #24
0
 def ec_get_public_key_by_private_key(private_key: bytes):
     if not isinstance(private_key, bytes):
         raise BotException(BotError.invalid_private_key)
     if len(private_key) != 32:
         raise BotException(BotError.invalid_private_key)
     private_key = SigningKey.from_string(string=private_key, curve=SECP256k1)
     public_key = private_key.get_verifying_key().to_string()
     return public_key
Exemple #25
0
def generate_key(identifier):
    from brave.core.application.model import Application

    key = SigningKey.generate(NIST256p, hashfunc=sha256)
    Application.objects(
        id=identifier,
        key__private=None  # Make sure we don't override an existing one.
    ).update(set__key__private=hexlify(key.to_string()))
Exemple #26
0
 def generate_signature(private_key: bytes, msg: bytes):
     if not isinstance(private_key, bytes):
         raise BotException(BotError.invalid_private_key)
     if len(private_key) != 32:
         raise BotException(BotError.invalid_private_key)
     private_key = SigningKey.from_string(string=private_key, curve=SECP256k1)
     signature = private_key.sign(msg)
     return signature
Exemple #27
0
 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__()
Exemple #28
0
    def setUp(self):
        self.private_keys = [SigningKey.generate(curve=NIST256p) for _ in range(3)]
        self.public_keys = [PublicKey.from_signing_key(private_key) for private_key in self.private_keys]

        self.operation = [
            Operation(OperationRev(), 'http://example.com/', [self.public_keys[1], self.public_keys[2]]),
            None, None
        ]
Exemple #29
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))
Exemple #30
0
    def setUp(self):
        self.private_key = SigningKey.generate()
        self.public_key = PublicKey.from_signing_key(self.private_key)

        self.operations = [Operation(
            OperationRev(), 'http://example.com/', [self.public_key]) for _ in range(Block.MIN_OPERATIONS + 1)]
        for op in self.operations:
            sign_object(self.public_key, self.private_key, op)
Exemple #31
0
    def setUp(self):
        initialise_database('test_database_file')

        self.private_key = SigningKey.generate()
        self.public_key = PublicKey.from_signing_key(self.private_key)
        # self.uuids = [uuid4() for _ in range(3)]

        self.operations = [[
            Operation(OperationRev(),'http://example0.com/v0/', [self.public_key]),
            Operation(OperationRev(),'http://example1.com/v0/', [self.public_key])
        ]]

        for op in self.operations[0]:
            sign_object(self.public_key, self.private_key, op)

        self.operations.append([
            Operation(OperationRev.from_obj(self.operations[0][0]), 'http://example0.com/v1/', [self.public_key]),
            Operation(OperationRev.from_obj(self.operations[0][1]), 'http://example1.com/v1/', [self.public_key]),
            Operation(OperationRev(), 'http://example2.com/v0/', [self.public_key])
        ])

        for op in self.operations[1]:
            sign_object(self.public_key, self.private_key, op)

        self.operations.append([
            Operation(OperationRev.from_obj(self.operations[1][0]),'http://example0.com/v2/', [self.public_key]),
            Operation(OperationRev.from_obj(self.operations[1][1]), 'http://example1.com/v2/', [self.public_key])
        ])

        for op in self.operations[2]:
            sign_object(self.public_key, self.private_key, op)

        self.operations.append([
            Operation(OperationRev.from_obj(self.operations[1][1]), 'http://alternative1.com/', [self.public_key]),
            Operation(OperationRev.from_obj(self.operations[1][2]), 'http://alternative2.com/', [self.public_key])
        ])

        for op in self.operations[3]:
            sign_object(self.public_key, self.private_key, op)

        timestamp = int(time.time()) - 100

        self.blocks = [Block.from_operations_list(BlockRev(), timestamp, self.operations[0])]
        self.blocks[0].mine()
        sign_object(self.public_key, self.private_key, self.blocks[0])
        self.blocks.append(
            Block.from_operations_list(BlockRev.from_obj(self.blocks[0]), timestamp + 20, self.operations[1]))
        self.blocks[1].mine()
        sign_object(self.public_key, self.private_key, self.blocks[1])
        self.blocks.append(
            Block.from_operations_list(BlockRev.from_obj(self.blocks[1]), timestamp + 40, self.operations[2]))
        self.blocks[2].mine()
        sign_object(self.public_key, self.private_key, self.blocks[2])
        self.blocks.append(
            Block.from_operations_list(BlockRev.from_obj(self.blocks[1]), timestamp + 60, self.operations[3]))
        self.blocks[3].mine()
        sign_object(self.public_key, self.private_key, self.blocks[3])
Exemple #32
0
    def setUp(self):
        initialise_database('test_database_file')

        self.operations = [
            Operation(OperationRev(), 'http://example.com/' + url, [PublicKey.from_signing_key(SigningKey.generate())])
            for url in ('first/', 'second/')]

        for op in self.operations:
            sk = SigningKey.generate()
            sign_object(PublicKey.from_signing_key(sk), sk, op)

        block = Block.from_operations_list(BlockRev(), 42, self.operations)
        block.mine()
        sk = SigningKey.generate()
        sign_object(PublicKey.from_signing_key(sk), sk, block)
        block.put()

        self.identifiers = [Identifier.from_operation(op) for op in self.operations]
Exemple #33
0
    def _parse_ecc_ssleay(data):
        """
        Parse binary structure of the old SSLeay file format used by OpenSSL.

        For ECDSA keys.
        """
        private_key = SigningKey.from_der(compatHMAC(data))
        secret_mult = private_key.privkey.secret_multiplier
        return Python_ECDSAKey(None, None, private_key.curve.name, secret_mult)
Exemple #34
0
def generate_key(identifier):
    from brave.core.application.model import Application
    
    key = SigningKey.generate(NIST256p, hashfunc=sha256)
    Application.objects(
            id = identifier,
            key__private = None  # Make sure we don't override an existing one.
        ).update(
            set__key__private = hexlify(key.to_string())
        )
Exemple #35
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']
Exemple #36
0
def authorized():
    # Perform the initial API call and direct the user.

    # Convert Key text into objects
    config['api.private'] = SigningKey.from_string(unhexlify(config['api.private']), curve=NIST256p, hashfunc=sha256)
    config['api.public'] = SigningKey.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
    token = request.args.get('token', '')

    if token == '':
        abort(401)

    # Make the authentication call to the CORE Service
    result = api.core.info(token=token)

    return jsonify(result)
Exemple #37
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()
Exemple #38
0
    def setUp(self):

        initialise_database('test_database_file')

        self.private_key = SigningKey.generate()
        self.public_key = PublicKey.from_signing_key(self.private_key)

        self.operations = [
            Operation(OperationRev(), 'http://example.com/', [self.public_key]),
            Operation(OperationRev(), 'http://example2.com/', [self.public_key]),
            Operation(OperationRev(), 'http://example3.com/', [self.public_key])
        ]
Exemple #39
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__()
Exemple #40
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)
 def generate_decrypt_aes_key(private_key: bytes, encode_g_tilde: bytes):
     if not isinstance(private_key, bytes):
         raise SDKException(ErrorCode.other_error('the length of private key should be 32 bytes.'))
     if len(private_key) != 32:
         raise SDKException(ErrorCode.other_error('the length of private key should be 32 bytes.'))
     str_g_tilde_x = encode_g_tilde[1:33]
     str_g_tilde_y = encode_g_tilde[33:65]
     g_tilde_x = string_to_number(str_g_tilde_x)
     g_tilde_y = string_to_number(str_g_tilde_y)
     g_tilde = Point(NIST256p.curve, g_tilde_x, g_tilde_y, NIST256p.order)
     h_tilde = g_tilde * SigningKey.from_string(string=private_key, curve=NIST256p).privkey.secret_multiplier
     seed = b''.join([encode_g_tilde, number_to_string(h_tilde.x(), NIST256p.order)])
     aes_key = pbkdf2(seed, 32)
     return aes_key
Exemple #42
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>'
Exemple #43
0
 def decrypt_with_cbc_mode(cipher_text: bytes, private_key: bytes, iv: bytes, encode_g_tilde: bytes):
     if not isinstance(private_key, bytes):
         raise BotException(BotError.invalid_private_key)
     if len(private_key) != 32:
         raise BotException(BotError.invalid_private_key)
     str_g_tilde_x = encode_g_tilde[1:33]
     str_g_tilde_y = encode_g_tilde[33:65]
     g_tilde_x = string_to_number(str_g_tilde_x)
     g_tilde_y = string_to_number(str_g_tilde_y)
     g_tilde = Point(SECP256k1.curve, g_tilde_x, g_tilde_y, SECP256k1.order)
     h_tilde = g_tilde * SigningKey.from_string(string=private_key, curve=SECP256k1).privkey.secret_multiplier
     seed = b''.join([encode_g_tilde, number_to_string(h_tilde.x(), SECP256k1.order)])
     aes_key = pbkdf2(seed, 32)
     plain_text = AESHandler.aes_cbc_decrypt(cipher_text, iv, aes_key)
     return plain_text
Exemple #44
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)
Exemple #45
0
    def test_no_database(self):
        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Operation.get_ids_list()

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Operation.get(sha256(b'something').digest())

        operation = Operation(OperationRev(), 'http://example.com/', [])
        sk = SigningKey.generate()
        sign_object(PublicKey.from_signing_key(sk), sk, operation)

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            operation.put(BlockRev())

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            operation.remove(BlockRev())
Exemple #46
0
 def get_public_key_by_bytes_private_key(private_key: bytes):
     if not isinstance(private_key, bytes):
         raise SDKException(ErrorCode.other_error('The type of private key should be bytes.'))
     if len(private_key) != 32:
         raise SDKException(ErrorCode.other_error('The length of private key should be 32 bytes.'))
     private_key = SigningKey.from_string(string=private_key, curve=NIST256p)
     public_key = private_key.get_verifying_key()
     order = public_key.pubkey.order
     x_int = public_key.pubkey.point.x()
     y_int = public_key.pubkey.point.y()
     x_str = number_to_string(x_int, order)
     if y_int % 2 == 0:
         point_str = b''.join([b'\x02', x_str])
     else:
         point_str = b''.join([b'\x03', x_str])
     return point_str
Exemple #47
0
def getSignature(hexa, key):
    """
	Generate signature using private key.

	Arguments:
	hexa (str) -- data as hex string
	key (str) -- a private key as hex string

	Return hex
	"""
    signingKey = SigningKey.from_string(unhexlify(key), SECP256k1,
                                        hashlib.sha256)
    return hexlify(
        signingKey.sign_deterministic(unhexlify(hexa),
                                      hashlib.sha256,
                                      sigencode=sigencode_der_canonize))
Exemple #48
0
 def __after__(self, result, *args, **kw):
     """Generate the JSON response and sign."""
     
     key = SigningKey.from_string(unhexlify(request.service.key.private), curve=NIST256p, hashfunc=sha256)
     
     response = Response(status=200, charset='utf-8')
     response.date = datetime.utcnow()
     response.last_modified = result.pop('updated', None)
     
     ct, body = render('json:', result)
     response.headers[b'Content-Type'] = str(ct)  # protect against lack of conversion in Flup
     response.body = body
     
     canon = "{req.service.id}\n{resp.headers[Date]}\n{req.url}\n{resp.body}".format(
                 req = request,
                 resp = response
Exemple #49
0
def getSignature(tx, privateKey):
    """
	Generate transaction signature using private key.

	Arguments:
	tx (dict) -- a transaction description
	privateKey (str) -- a private key as hex string

	Return str
	"""
    signingKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1,
                                        hashlib.sha256)
    return hexlify(
        signingKey.sign_deterministic(getBytes(tx),
                                      hashlib.sha256,
                                      sigencode=sigencode_der_canonize))
Exemple #50
0
def getSignatureFromBytes(data, privateKey):
    """
	Generate data signature using private key.

	Arguments:
	data (bytes) -- data in bytes
	privateKey (str) -- a private key as hex string

	Return str
	"""
    signingKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1,
                                        hashlib.sha256)
    return hexlify(
        signingKey.sign_deterministic(data,
                                      hashlib.sha256,
                                      sigencode=sigencode_der_canonize))
Exemple #51
0
    def test_no_database(self):
        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Identifier.get_uuid_list()

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            Identifier.get(uuid4())

        operation = Operation(OperationRev(), 'http://example.com/', [])
        sk = SigningKey.generate()
        sign_object(PublicKey.from_signing_key(sk), sk, operation)
        identifier = Identifier.from_operation(operation)

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            identifier.put()

        with self.assertRaisesRegex(pmpi.database.Database.InitialisationError, "initialise database first"):
            identifier.remove()
Exemple #52
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)
Exemple #53
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__()
Exemple #54
0
    def public_key(self):
        """
        """

        if self._public_key:
            return self._public_key

        point = SigningKey.from_secret_exponent(
            secexp=int(self.secret_exponent, 16),
            curve=SECP256k1,
            hashfunc=hashlib.sha256,
        ).verifying_key.pubkey.point

        x = hex(point.x())[2:].strip('L')
        y = hex(point.y())[2:].strip('L')

        if self.__compressed:
            return ''.join(('02' if point.y() % 2 == 0 else '03', x))
        else:
            return ''.join(('04', x, y))
Exemple #55
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)
def generate_private_key():
    """
    () -> hex

    Generate a private key and 
    Return respective public key pair using the Elliptical Curve Digital Signiture Algorithm.
    
    SECP256k1 curve. -> curve
    Generate a 'random' number to use in the generation of the private key. -> se
    Generate the key with the two above inputs and pass it through a SHA-256 hash. -> sha256(key) -> verifying_key
    Return the hexideciaml conversion of verifying key (public key pair to the private key generated) verifying_key -> hex

    This is our private key's public key pair.
    """

    curve = ecdsa.curves.SECP256k1
    se = random_secret_exponent(curve.order)
    key = SigningKey.from_secret_exponent(se, curve, hashlib.sha256)
    verifying_key = key.get_verifying_key()
    verifying_key_string = verifying_key.to_string()
    bitcoin_byte = b'04'
    key_hex = hexlify(key.to_string())
    return hexlify(key.to_string())
Exemple #57
0
def generate_keypair() -> (SigningKey, str):
    sk = SigningKey.generate(NIST256p)
    vk = sk.get_verifying_key()
    return sk, vk.to_string().hex()
Exemple #58
0
    ec["publicKey"] = ec_rfc5915["publicKey"]
    p8["version"] = 0
    p8["privateKeyAlgorithm"] = AlgorithmIdentifier()
    p8["privateKeyAlgorithm"]["algorithm"] = "1.2.840.10045.2.1"
    p8["privateKeyAlgorithm"]["parameters"] = ObjectIdentifier(
        ec_rfc5915["parameters"])
    p8["privateKey"] = DER_Encode(ec)
    der = DER_Encode(p8)
    #print; dumpasn1(der)
    #print; dumpasn1(der_test_keys["ec_pkcs8"])
    print
    print "Reencoded PKCS #8 {} static data".format(
        "matches" if der == der_test_keys["ec_pkcs8"] else "doesn't match")

    # Try doing same thing with ecdsa package ASN.1 utilities.
    sk = SigningKey.from_der(der_test_keys["ec_rfc5915"])
    vk = ECDSA_DER.encode_bitstring("\x00\x04" +
                                    sk.get_verifying_key().to_string())
    ec = ECDSA_DER.encode_sequence(
        ECDSA_DER.encode_integer(1),
        ECDSA_DER.encode_octet_string(sk.to_string()),
        ECDSA_DER.encode_constructed(1, vk))
    p8 = ECDSA_DER.encode_sequence(
        ECDSA_DER.encode_integer(0),
        ECDSA_DER.encode_sequence(encoded_oid_ecPublicKey,
                                  sk.curve.encoded_oid),
        ECDSA_DER.encode_octet_string(ec))
    print
    print "ECDSA-library PKCS #8 encoding {} pyasn1 PKCS #8 encoding".format(
        "matches" if p8 == der_test_keys["ec_pkcs8"] else "doesn't match")
Exemple #59
0
def make_key_from_entropy_source(entropy=None):
    return SigningKey.generate(SECP256k1, entropy=entropy)