예제 #1
0
def recoverECDSAKey(token, hashalg, curve, compressed):
    header, body, sig = token.split(".")
    rs = base64.b64decode(sig + "==")
    n = len(rs) // 2
    r = int(rs[:n].hex(), 16)
    s = int(rs[n:].hex(), 16)
    # compute the 2 points having r has X coordinate
    y1, y2 = mod_sqrt(r**3 + curve.a * r + curve.b, curve.p)
    R1 = Point(r, y1, curve)
    R2 = Point(r, y2, curve)
    # compute r^1
    r_inv = int(gmpy2.invert(r, curve.q))
    # compute message hash
    message = header + "." + body
    h = int(hashalg.new(message.encode()).hexdigest(), 16)
    G = Point(curve.gx, curve.gy, curve)
    # recover the two possible public keys
    k1 = r_inv * (s * R1 - h * G)
    k2 = r_inv * (s * R2 - h * G)
    k1_ = ECC.construct(curve=curve.name.lower(), point_x=k1.x, point_y=k1.y)
    k2_ = ECC.construct(curve=curve.name.lower(), point_x=k2.x, point_y=k2.y)
    print("Found 2 public ECDSA keys !")
    print(f"x={k1.x}\ny={k1.y}")
    print(k1_.export_key(format="PEM", compress=compressed))
    print("")
    print(f"x={k2.x}\ny={k2.y}")
    print(k2_.export_key(format="PEM", compress=compressed))
예제 #2
0
    def test_construct(self):
        seed = unhexlify(
            "4adf5d37ac6785e83e99a924f92676d366a78690af59c92b6bdf14f9cdbcf26fdad478109607583d633b60078d61d51d81b7509c5433b0d4c9"
        )
        Px = 0x72a01eea003a35f9ac44231dc4aae2a382f351d80bf32508175b0855edcf389aa2bbf308dd961ce361a6e7c2091bc78957f6ebcf3002a617
        Py = 0x9e0d08d84586e9aeefecacb41d049b831f1a3ee0c3eada63e34557b30702b50ab59fb372feff7c30b8cbb7dd51afbe88444ec56238722ec1
        d = 0xb07cf179604f83433186e5178760c759c15125ee54ff6f8dcde46e872b709ac82ed0bd0a4e036d774034dcb18a9fb11894657a1485895f80
        point = EccPoint(Px, Py, curve="Ed448")

        # Private key only
        key = ECC.construct(curve="Ed448", seed=seed)
        self.assertEqual(key.pointQ, point)
        self.assertTrue(key.has_private())

        # Public key only
        key = ECC.construct(curve="Ed448", point_x=Px, point_y=Py)
        self.assertEqual(key.pointQ, point)
        self.assertFalse(key.has_private())

        # Private and public key
        key = ECC.construct(curve="Ed448", seed=seed, point_x=Px, point_y=Py)
        self.assertEqual(key.pointQ, point)
        self.assertTrue(key.has_private())

        # Other names
        key = ECC.construct(curve="ed448", seed=seed)
예제 #3
0
def create_ref_keys():
    key_lines = load_file("ecc_p256.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:5]))
    public_key_xy = compact(key_lines[6:11])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    return (ECC.construct(curve="P-256", d=private_key_d),
            ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
예제 #4
0
def create_ref_keys():
    key_lines = load_file("ecc_p256.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:5]))
    public_key_xy = compact(key_lines[6:11])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    return (ECC.construct(curve="P-256", d=private_key_d),
            ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
예제 #5
0
def create_ref_keys_p521():
    key_len = 66
    key_lines = load_file("ecc_p521.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:7]))
    public_key_xy = compact(key_lines[8:17])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
    public_key_y = bytes_to_long(public_key_xy[key_len+1:])

    return (ECC.construct(curve="P-521", d=private_key_d),
            ECC.construct(curve="P-521", point_x=public_key_x, point_y=public_key_y))
예제 #6
0
    def sign_with_provided_privkey(dict_of_privkey_numbers, message):
        """

        :param dict_of_privkey_numbers: dictionary with numbers to recreate key
        {'x': large int, 'y': large int, 'd': large int}

        :param message: str or bytes
        :return: signature
        """

        if not isinstance(message, (bytes, str)):
            return None
        elif isinstance(message, str):
            message = message.encode()

        key = None
        try:
            key = ECC.construct(curve="P-256",
                                point_x=dict_of_privkey_numbers["x"],
                                point_y=dict_of_privkey_numbers["y"],
                                d=dict_of_privkey_numbers["d"])
        except KeyError as e:  # does not have all required ECC attributes x, y and d for private key con
            print(f"in digitalsigner.py: exception occured:\n{e}")

        except AttributeError as e:  # x, y, d might are not ints.

            if isinstance(dict_of_privkey_numbers["x"], str):
                try:
                    key = ECC.construct(curve="P-256",
                                        point_x=PKI.convert_dict_keys_to_int(
                                            dict_of_privkey_numbers["x"]),
                                        point_y=PKI.convert_dict_keys_to_int(
                                            dict_of_privkey_numbers["y"]),
                                        d=PKI.convert_dict_keys_to_int(
                                            dict_of_privkey_numbers["d"]))
                except Exception as e:
                    print(f"in digitalsigner.py: exception occured:\n{e}")
            else:
                print(f"in digitalsigner.py: exception occured:\n{e}")

        except ValueError as e:  # the numbers provided do not represent a valid point on ECC curve
            print(f"in digitalsigner.py: exception occured:\n{e}")

        if key is None:
            return None

        hash_of_message = SHA256.new(message)

        signer = DSS.new(key, mode="fips-186-3")

        digital_signature = signer.sign(hash_of_message)
        digital_signature = base64.b85encode(digital_signature).decode()

        return digital_signature
예제 #7
0
def create_ref_keys_p521():
    key_len = 66
    key_lines = load_file("ecc_p521.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:7]))
    public_key_xy = compact(key_lines[8:17])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
    public_key_y = bytes_to_long(public_key_xy[key_len+1:])

    return (ECC.construct(curve="P-521", d=private_key_d),
            ECC.construct(curve="P-521", point_x=public_key_x, point_y=public_key_y))
예제 #8
0
    def load_from_params(curve=None, x=None, y=None):
        """
		Construct public key from the components
		"""
        if curve == ECDSAPublicKey.NIST_P_256:
            return ECDSAPublicKey(
                key=ECC.construct(curve='NIST P-256', point_x=x, point_y=y))
        elif curve == ECDSAPublicKey.NIST_P_384:
            return ECDSAPublicKey(
                key=ECC.construct(curve='NIST P-384', point_x=x, point_y=y))
        else:
            raise Exception("Unsupported curve")
예제 #9
0
    def load_pub_key(self, importedKey=True, x_y_only=False, user_or_wallet="user"):

        if user_or_wallet == "user":
            pubkey = self.user_instance.fl.open_file_from_json(
                self.pubkey_file, in_folder=self.user_instance.fl.get_keys_folder_path())
        else:
           pubkey = self.user_instance.fl.open_file_from_json(
               self.pubkey_file, in_folder=self.user_instance.fl.get_wallets_folder_path())

        if not pubkey:  # no public key saved with user name
            return False

        if importedKey is True and x_y_only is False:

            # construct public key and return a key object or importedKey
            x_int = base64.b85decode(pubkey["x"].encode())
            x_int = int.from_bytes(x_int, "big")

            y_int = base64.b85decode(pubkey["y"].encode())
            y_int = int.from_bytes(y_int, "big")
            return ECC.construct(point_x=x_int, point_y=y_int, curve="P-256")
        elif x_y_only is True:
            # returns a dictionary with {"x": base85 string, "y": base85 string}
            # this string can be turned back into number using:
            # x_int = base64.b85decode(string.encode())
            # x_int = int.from_bytes(x_int, "big")
            return pubkey
        else:
            # turn back to original bytes from base85encoded string/bytes
            pubkey_bytes = base64.b85decode(pubkey['x'].encode())+base64.b85decode(pubkey['y'].encode())

            # looking for bytes probably to generate user id
            # bytes is done by concatenating the bytes of x and y. see explanation above on how to get the bytes

            return pubkey_bytes
    def test_equality(self):
        private_key = ECC.construct(d=3, curve="P-521")
        private_key2 = ECC.construct(d=3, curve="P-521")
        private_key3 = ECC.construct(d=4, curve="P-521")

        public_key = private_key.public_key()
        public_key2 = private_key2.public_key()
        public_key3 = private_key3.public_key()

        self.assertEqual(private_key, private_key2)
        self.assertNotEqual(private_key, private_key3)

        self.assertEqual(public_key, public_key2)
        self.assertNotEqual(public_key, public_key3)

        self.assertNotEqual(public_key, private_key)
예제 #11
0
	def test():
		key = ECC.generate(curve='secp256r1')
		print key.public_key()
		x = key.public_key().pointQ.x
		y = key.public_key().pointQ.y

		hx=hex(int(str(x)))
		bytearray.fromhex(hx[2:64])[::-1]
		reversed_arr=result[::-1]

		x=key.public_key().pointQ.x
		hx=hex(int(str(x)))
		rx = bytearray.fromhex(hx[2:66])[::-1]


		y=key.public_key().pointQ.y
		hy=hex(int(str(y)))
		ry = bytearray.fromhex(hy[2:66])[::-1]	

		''.join('{:02x}'.format(x) for x in rx+ry)

		addr=SHA256.new(rx+ry).hexdigest()[:40]


		"".join("{:02x}".format(ord(c)) for c in pps)


		p = ECC.construct(curve='secp256r1',d=70054409939411066367955879351487264564474994114056648764946442729447023254584)
		signer = DSS.new(p, 'fips-186-3')
		pps=signer.sign(h)
예제 #12
0
    def __gen_sym_key(device_public_key_string_xy):

        _ECC_CURVE = 'secp256r1'

        # Construct ECC point from device public key
        device_kpub_int_x = int.from_bytes(device_public_key_string_xy[:32], byteorder='big')
        device_kpub_int_y = int.from_bytes(device_public_key_string_xy[32:], byteorder='big')
        device_kpub_p = ECC.construct(curve=_ECC_CURVE, point_x=device_kpub_int_x, point_y=device_kpub_int_y)

        # Create user private / public key pair
        user_key_pair = ECC.generate(curve=_ECC_CURVE)

        # The shared secret is calculated using the device public point and the private key.
        # The secret is the x-coordinate of the resulting point
        shared_secret_int = (device_kpub_p.pointQ * user_key_pair.d).x

        # Calculate symmetric key from shared secret using hmac-sha256 and static data "config"
        shared_secret_string = int(shared_secret_int).to_bytes(32, byteorder='big')
        h = HMAC.new(shared_secret_string, msg=b'config', digestmod=SHA256)

        # Truncate to get shared private key (16 bytes)
        symmetric_key = h.digest()[0:16]

        # Create public key byte strings
        user_kpub_string_x = int(user_key_pair.pointQ.x).to_bytes(32, byteorder='big')
        user_kpub_string_y = int(user_key_pair.pointQ.y).to_bytes(32, byteorder='big')

        return symmetric_key, user_kpub_string_x + user_kpub_string_y
    def get_public_key_from_shared_key(shared_key, cryptographic_group):
        # for x25519 and x448 we don't have to do anything
        if cryptographic_group == b"\x00\x1d" or cryptographic_group == b"\x00\x1e":
            return shared_key

        # for secpr1 the shared key again has this format:
        # struct {
        #     uint8 legacy_form = 4;
        #     opaque X[coordinate_length];
        #     opaque Y[coordinate_length];
        # } UncompressedPointRepresentation;
        shared_key = shared_key[1:len(shared_key)]
        # the size of x/y depends on the cryptographic group
        # secp256r1
        if cryptographic_group == b"\x00\x17":
            coordinate_byte_size = 32
            curve_name = "P-256"
        # secp384r1
        elif cryptographic_group == b"\x00\x18":
            coordinate_byte_size = 48
            curve_name = "P-384"
        # secp521r1
        elif cryptographic_group == b"\x00\x19":
            coordinate_byte_size = 66
            curve_name = "P-521"
        # retrieve x and y from the shared key and turn them into bytes
        xBin = shared_key[0:coordinate_byte_size]
        x = int.from_bytes(xBin, Crypto_Helper.ENDINESS, signed=False)
        yBin = shared_key[coordinate_byte_size:coordinate_byte_size +
                          coordinate_byte_size]
        y = int.from_bytes(yBin, Crypto_Helper.ENDINESS, signed=False)
        # TODO find cryptography.hazmat alternative so we only have to use a single library
        ecc_curve = ECC.construct(curve=curve_name, point_x=x, point_y=y)
        return ecc_curve.public_key().export_key(format="DER")
예제 #14
0
    def create_standard_key_store(self, private_key=None):

        if private_key is None:
            key_pair = self.create_key_pair()
        else:
            key_pair = ECC.construct(curve='P-256', d=int(private_key, 16))

        self.ECCkey = key_pair

        private_key_int = key_pair.d
        private_key_bytes = private_key_int.to_bytes()
        public_key_ECC = key_pair.public_key()

        self.private_key = private_key_bytes

        signature_redeem_script_bytes = self.create_standard_redeem_script(
            public_key_ECC)
        program_hash = utility.script_to_program_hash(
            signature_redeem_script_bytes)
        self.public_key = utility.encode_point(is_compressed=True,
                                               public_key_ECC=public_key_ECC)
        self.sign_script = signature_redeem_script_bytes
        self.program_hash = program_hash
        self.address = utility.program_hash_to_address(program_hash).decode()
        self.store_wallet_data()
예제 #15
0
    def test_equality(self):
        private_key = ECC.construct(seed=b'H' * 57, curve="Ed448")
        private_key2 = ECC.construct(seed=b'H' * 57, curve="ed448")
        private_key3 = ECC.construct(seed=b'C' * 57, curve="Ed448")

        public_key = private_key.public_key()
        public_key2 = private_key2.public_key()
        public_key3 = private_key3.public_key()

        self.assertEqual(private_key, private_key2)
        self.assertNotEqual(private_key, private_key3)

        self.assertEqual(public_key, public_key2)
        self.assertNotEqual(public_key, public_key3)

        self.assertNotEqual(public_key, private_key)
예제 #16
0
def ECDSA_times(tests_information):
    key_params = [line.strip('\n') for line in open("ECDSA_key_params.txt")]
    q = int(key_params[0], 16)
    x = int(key_params[1], 16)
    ux = int(key_params[2], 16)
    uy = int(key_params[3], 16)
    key = ECC.construct(curve='NIST P-521', d=x, point_x=ux, point_y=uy)
    sign_times = []
    verify_times = []
    for t in tests_information:
        [hash_type, message] = t.split(',')
        h = hashed_message(hash_type, message)

        #sign
        start_time = time.perf_counter()
        sign = ECDSA_sign(key, h)
        elapsed_time = time.perf_counter() - start_time
        sign_times.append(elapsed_time)

        #verification
        start_time = time.perf_counter()
        ECDSA_verify(sign, key, h)
        elapsed_time = time.perf_counter() - start_time
        verify_times.append(elapsed_time)

    return [sign_times, verify_times]
예제 #17
0
파일: test_ECC.py 프로젝트: shubhanus/taiga
    def test_equality(self):

        private_key = ECC.construct(d=3, curve="P-256")
        private_key2 = ECC.construct(d=3, curve="P-256")
        private_key3 = ECC.construct(d=4, curve="P-256")

        public_key = private_key.public_key()
        public_key2 = private_key2.public_key()
        public_key3 = private_key3.public_key()

        self.assertEqual(private_key, private_key2)
        self.assertNotEqual(private_key, private_key3)

        self.assertEqual(public_key, public_key2)
        self.assertNotEqual(public_key, public_key3)

        self.assertNotEqual(public_key, private_key)
예제 #18
0
    def load_from_params(curve=None, x=None, y=None):
        """
		Construct public key from the components
		"""
        if curve == ECDSALowPublicKey.SECP160R1:
            return ECDSAPublicKey(
                key=ECC.construct(curve='SECP160R1', point_x=x, point_y=y))
        else:
            raise Exception("Unsupported curve")
 def construct_public_key(xy):
     """Constructs an ECC-public key starting from the bytes sequences representing the public key.
     :param xy: the bytes sequences representing the public key,
         as of the concatenation of the bytes sequences representing :param x and :param y
     :returns an EccKey object containing the public key corresponding to the couple of coordinates x and y"""
     coordinate_size = len(xy) // 2
     x = int.from_bytes(xy[:coordinate_size], 'big')
     y = int.from_bytes(xy[coordinate_size:], 'big')
     return ECC.construct(curve=STANDARD_CURVE, point_x=x, point_y=y)
예제 #20
0
def create_secrets_before():
    # Generate private keys
    privkeys = [ecc.generate(curve='secp256r1') for _ in range(DEPL_COUNT)]

    # Calculate public key points
    pubkeys = [ecc.construct(curve='secp256r1',d=privkey.d).public_key()._point for privkey in privkeys]

    # Generate broadcast keys
    brdcst_privkey = ecc.generate(curve='secp256r1')
    brdcst_public = ecc.construct(curve='secp256r1',d=brdcst_privkey.d).public_key()._point
    brdcst_keys = [brdcst_privkey,brdcst_public]

    # Uniquely identify this deployment
    depl_nonce = get_random_bytes(16)

    # Generate secrets for each depl_id
    for depl_id in range(DEPL_COUNT):
        make_a_secret(depl_id, depl_nonce, privkeys[depl_id], pubkeys, brdcst_keys)
예제 #21
0
def run_test_ecdsa_sign_deterministic():
    init_dmem()
    rres, sres = run_sign(d, kexp, msg_digest_int)
    rresb = rres.to_bytes(32, byteorder='big', signed=False)
    sresb = sres.to_bytes(32, byteorder='big', signed=False)
    rsresb = b''.join([rresb, sresb])
    verkey = ECC.construct(curve='p256', point_x=x, point_y=y, d=d)
    verifier = DSS.new(verkey, 'fips-186-3')
    try:
        verifier.verify(msg_digest, rsresb)
    except ValueError:
        raise Exception('ECDSA sign (deterministic) failed')
    def test_construct(self):
        curve = _curves['p521']
        key = ECC.construct(curve="P-521", d=1)
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, _curves['p521'].G)

        key = ECC.construct(curve="P-521", point_x=curve.Gx, point_y=curve.Gy)
        self.failIf(key.has_private())
        self.assertEqual(key.pointQ, curve.G)

        # Other names
        ECC.construct(curve="p521", d=1)
        ECC.construct(curve="secp521r1", d=1)
        ECC.construct(curve="prime521v1", d=1)
예제 #23
0
    def decorated_function(*args, **kwargs):
        # Rule out Inspect operation
        if request.args.get('key'):
            return f(*args, **kwargs)

        token = request.headers.get('X-Auth-Token')
        encoded_public_key = request.headers.get('X-Public-Key')
        encoded_signature = request.headers.get('X-Signature')

        if token is None or encoded_public_key is None or encoded_signature is None:
            return jsonify({
                "error":
                "One or more required fields do not exist in the header"
            }), 401
        payload, key = get_payload(token)

        if payload is None:
            return jsonify({"error": "Invalid token"}), 401
        # Check if token exists
        if redis.get(key) is None:
            return jsonify({"error": "Token does not exist"}), 401

        g.user = payload.get('user')

        method_operation_map = {
            'GET': 'download',
            'POST': 'upload',
            'DELETE': 'remove',
        }
        # Check if token is available to perform operation
        if method_operation_map.get(
                request.method) != payload.get('operation').get('name'):
            return jsonify({
                "error":
                "Token is only available to perform %s" %
                payload.get('operation').get('name')
            }), 401

        # Verify signature
        try:
            public_key_bytes = bytes.fromhex(encoded_public_key)
            public_key_obj = ECC.construct(
                curve='P-256',
                point_x=int.from_bytes(public_key_bytes[1:33], 'big'),
                point_y=int.from_bytes(public_key_bytes[33:65], 'big'))
            verifier = DSS.new(key=public_key_obj, mode='fips-186-3')
            digested_jwt = SHA256.new(str.encode(token))
            verifier.verify(digested_jwt, bytes.fromhex(encoded_signature))
        except ValueError:
            return jsonify({"error": "Verification failed"}), 401

        return f(*args, **kwargs)
예제 #24
0
    def test_raw(self):
        key = ECC.generate(curve="Ed448")
        x, y = key.pointQ.xy
        raw = bytearray(key._export_eddsa())
        sign_x = raw[56] >> 7
        raw[56] &= 0x7F
        yt = bytes_to_long(raw[::-1])
        self.assertEqual(y, yt)
        self.assertEqual(x & 1, sign_x)

        key = ECC.construct(point_x=0, point_y=1, curve="Ed448")
        out = key._export_eddsa()
        self.assertEqual(b'\x01' + b'\x00' * 56, out)
예제 #25
0
    def test_construct(self):

        curve = _curves['p384']
        key = ECC.construct(curve="P-384", d=1)
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, _curves['p384'].G)

        key = ECC.construct(curve="P-384", point_x=curve.Gx, point_y=curve.Gy)
        self.assertFalse(key.has_private())
        self.assertEqual(key.pointQ, curve.G)

        # Other names
        ECC.construct(curve="p384", d=1)
        ECC.construct(curve="secp384r1", d=1)
        ECC.construct(curve="prime384v1", d=1)
예제 #26
0
    def test_construct(self):

        curve = _curves['p521']
        key = ECC.construct(curve="P-521", d=1)
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, _curves['p521'].G)

        key = ECC.construct(curve="P-521", point_x=curve.Gx, point_y=curve.Gy)
        self.failIf(key.has_private())
        self.assertEqual(key.pointQ, curve.G)

        # Other names
        ECC.construct(curve="p521", d=1)
        ECC.construct(curve="secp521r1", d=1)
        ECC.construct(curve="prime521v1", d=1)
예제 #27
0
    def test_construct(self):

        key = ECC.construct(curve="P-256", d=1)
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, _curves['p256'].G)

        key = ECC.construct(curve="P-256", point_x=_curves['p256'].Gx,
                            point_y=_curves['p256'].Gy)
        self.failIf(key.has_private())
        self.assertEqual(key.pointQ, _curves['p256'].G)

        # Other names
        ECC.construct(curve="p256", d=1)
        ECC.construct(curve="secp256r1", d=1)
        ECC.construct(curve="prime256v1", d=1)
예제 #28
0
    def test_construct(self):

        key = ECC.construct(curve="P-256", d=1)
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, _curves['p256'].G)

        key = ECC.construct(curve="P-256", point_x=_curves['p256'].Gx,
                            point_y=_curves['p256'].Gy)
        self.assertFalse(key.has_private())
        self.assertEqual(key.pointQ, _curves['p256'].G)

        # Other names
        ECC.construct(curve="p256", d=1)
        ECC.construct(curve="secp256r1", d=1)
        ECC.construct(curve="prime256v1", d=1)
예제 #29
0
    def generate_key_from_parts(x: str, y: str, d=None, in_bytes=False):
        """
        used to generate key from x and y sent over the internet
        :param x: x + y used for pubkey generation
        :param y:
        :param d: x+y+d used for private key genereation
        :return: pubkey object
        """
        if in_bytes:
            # if in bytes then only for pubkey
            return base64.b85decode(x.encode())+base64.b85decode(y.encode())

        # if d is none returns pubkey
        return ECC.construct(curve="P-256", point_x=x, point_y=y, d=d)
예제 #30
0
 def test_repr(self):
     p1 = ECC.construct(
         curve='P-256',
         d=
         75467964919405407085864614198393977741148485328036093939970922195112333446269,
         point_x=
         20573031766139722500939782666697015100983491952082159880539639074939225934381,
         point_y=
         108863130203210779921520632367477406025152638284581252625277850513266505911389
     )
     self.assertEqual(
         repr(p1),
         "EccKey(curve='NIST P-256', point_x=20573031766139722500939782666697015100983491952082159880539639074939225934381, point_y=108863130203210779921520632367477406025152638284581252625277850513266505911389, d=75467964919405407085864614198393977741148485328036093939970922195112333446269)"
     )
예제 #31
0
    def test_construct(self):
        seed = unhexlify("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
        Px = 38815646466658113194383306759739515082307681141926459231621296960732224964046
        Py = 11903303657706407974989296177215005343713679411332034699907763981919547054807
        d = 36144925721603087658594284515452164870581325872720374094707712194495455132720
        point = EccPoint(Px, Py, curve="Ed25519")

        # Private key only
        key = ECC.construct(curve="Ed25519", seed=seed)
        self.assertEqual(key.pointQ, point)
        self.assertTrue(key.has_private())

        # Public key only
        key = ECC.construct(curve="Ed25519", point_x=Px, point_y=Py)
        self.assertEqual(key.pointQ, point)
        self.assertFalse(key.has_private())

        # Private and public key
        key = ECC.construct(curve="Ed25519", seed=seed, point_x=Px, point_y=Py)
        self.assertEqual(key.pointQ, point)
        self.assertTrue(key.has_private())

        # Other names
        key = ECC.construct(curve="ed25519", seed=seed)
예제 #32
0
    def load_priv_key(self, importedKey=True, encrypted=False, user_or_wallet="user"):
        """
        1. loads json object of [privkey_encrypted, tag, nonce, salt]
        2. Turns these from hex to bytes
        3. using these information and the provided password, it decrypts private key a

        :return: bytes
        """

        # load encryped private key list with tag, nonce and salt
        if user_or_wallet == "user":
            list_of_encrypted_privkey_tag_nonce_salt = FileAction.open_file_from_json(
                filename=self.privkey_file, in_folder=self.user_instance.fl.get_keys_folder_path())
        else:
            list_of_encrypted_privkey_tag_nonce_salt = FileAction.open_file_from_json(
                filename=self.privkey_file, in_folder=self.user_instance.fl.get_wallets_folder_path)

        # if it is an empty list then no key created and saved on username so generate new key
        if not list_of_encrypted_privkey_tag_nonce_salt:
            return b''

        if encrypted:
            return list_of_encrypted_privkey_tag_nonce_salt

        # turn elements from hex back to bytes
        list_of_encrypted_privkey_tag_nonce_salt = [bytes.fromhex(i) for i in list_of_encrypted_privkey_tag_nonce_salt]

        # decrypt encrypted key
        decrypted_key = Decrypt(list_of_encrypted_privkey_tag_nonce_salt, password=self.password).decrypt()

        if importedKey is True and decrypted_key:
            pubkey = self.load_pub_key(x_y_only=True, user_or_wallet=user_or_wallet)
            x_int = base64.b85decode(pubkey["x"].encode())
            x_int = int.from_bytes(x_int, "big")

            y_int = base64.b85decode(pubkey["y"].encode())
            y_int = int.from_bytes(y_int, "big")

            d_int = base64.b85decode(decrypted_key)
            d_int = int.from_bytes(d_int, "big")

            return ECC.construct(d=d_int, point_x=x_int, point_y=y_int, curve="P-256")
        else:
            return decrypted_key
예제 #33
0
    def validate_wallet_signature(msg, wallet_pubkey, signature):
        """

        :param msg:
        :param wallet_pubkey:
        :param signature:
        :return:
        """
        if signature is None:
            print(
                "Signature is None. probably cause something other than a string or byte being passed to signer"
            )
            return False
        try:
            x_int = base64.b85decode(wallet_pubkey["x"].encode())
            x_int = int.from_bytes(x_int, "big")

            y_int = base64.b85decode(wallet_pubkey["y"].encode())
            y_int = int.from_bytes(y_int, "big")
        except KeyError:
            return False
        except Exception as e:
            print(f"in DigitalsignerValidator: {e}")
            return False

        signature = signature.encode()
        signature = base64.b85decode(signature)

        # if it a string
        try:
            hash_of_message = SHA256.new(msg)
        except TypeError:
            hash_of_message = SHA256.new(msg.encode())

        try:
            wallet_pubkey = ECC.construct(point_x=x_int,
                                          point_y=y_int,
                                          curve="P-256").public_key()
            verifier = DSS.new(wallet_pubkey, mode="fips-186-3")
            verifier.verify(hash_of_message, signature=signature)
        except ValueError:
            return False
        else:
            return True
예제 #34
0
파일: test_ECC.py 프로젝트: shubhanus/taiga
    def test_construct(self):

        key = ECC.construct(curve="P-256", d=1)
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        key = ECC.construct(curve="P-256", point_x=_curve.Gx, point_y=_curve.Gy)
        self.assertFalse(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        # Other names
        ECC.construct(curve="secp256r1", d=1)
        ECC.construct(curve="prime256v1", d=1)
예제 #35
0
    def validate(msg, pubkey: dict, signature):
        """
        used to validate signature
        :param msg: string or byte string, message to validate signature(assignment statements, token transfers etc)
        :param signature: bytes string or hex string
        :param pubkey: {"x": base85 string, "y": base85 string}  # use base64.b85decode(pubkey["x"}.encode) to get
                        pubkey bytes
        :type pubkey: dict
        :return:
        """
        if signature is None:
            print(
                "Signature is None. probably cause something other than a string or byte being passed to signer"
            )
            return False
        try:
            x_int = base64.b85decode(pubkey["x"].encode())
            x_int = int.from_bytes(x_int, "big")

            y_int = base64.b85decode(pubkey["y"].encode())
            y_int = int.from_bytes(y_int, "big")
        except KeyError:
            return False

        signature = signature.encode()
        signature = base64.b85decode(signature)

        # if it a string
        try:
            hash_of_message = SHA256.new(msg)
        except TypeError:
            hash_of_message = SHA256.new(msg.encode())

        try:
            pubkey = ECC.construct(point_x=x_int, point_y=y_int,
                                   curve="P-256").public_key()
            verifier = DSS.new(pubkey, mode="fips-186-3")
            verifier.verify(hash_of_message, signature=signature)
        except ValueError:
            return False
        else:
            return True
예제 #36
0
    def test_construct(self):

        key = ECC.construct(curve="P-256", d=1)
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        key = ECC.construct(curve="P-256",
                            point_x=_curve.Gx,
                            point_y=_curve.Gy)
        self.failIf(key.has_private())
        self.assertEqual(key.pointQ, _curve.G)

        # Other names
        ECC.construct(curve="secp256r1", d=1)
        ECC.construct(curve="prime256v1", d=1)
예제 #37
0
 def test_repr(self):
     p1 = ECC.construct(curve='P-256',
                        d=75467964919405407085864614198393977741148485328036093939970922195112333446269,
                        point_x=20573031766139722500939782666697015100983491952082159880539639074939225934381,
                        point_y=108863130203210779921520632367477406025152638284581252625277850513266505911389)
     self.assertEqual(repr(p1), "EccKey(curve='NIST P-256', point_x=20573031766139722500939782666697015100983491952082159880539639074939225934381, point_y=108863130203210779921520632367477406025152638284581252625277850513266505911389, d=75467964919405407085864614198393977741148485328036093939970922195112333446269)")
예제 #38
0
#!/usr/bin/env python

# pip install --user pycryptodome

from Crypto.PublicKey import ECC
import sys

if len(sys.argv) < 2:
    sys.stderr.write("Usage: %s <ecdsa->priv_key value>\n" % sys.argv[0])
    sys.exit(-1)

o = ECC.construct(curve='P-256', d=int(sys.argv[1]))
print o.export_key(format="PEM")
예제 #39
0
 def construct(rsa_components, consistency_check=True):
     return ECC.construct(rsa_components, consistency_check)
예제 #40
0
                                  'qx': lambda x: int(x, 16),
                                  'qy': lambda x: int(x, 16),
                                  })

for idx, tv in enumerate(test_vectors_verify):

    if isinstance(tv, str):
        res = re.match(r"\[(P-[0-9]+),(SHA-[0-9]+)\]", tv)
        assert res
        curve_name = res.group(1)
        hash_name = res.group(2).replace("-", "")
        hash_module = load_hash_by_name(hash_name)
        continue

    hash_obj = hash_module.new(tv.msg)
    ecc_key = ECC.construct(curve=curve_name, point_x=tv.qx, point_y=tv.qy)
    verifier = DSS.new(ecc_key, 'fips-186-3')

    def positive_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        verifier.verify(hash_obj, signature)

    def negative_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        self.assertRaises(ValueError, verifier.verify, hash_obj, signature)

    if tv.result.startswith('p'):
        setattr(FIPS_ECDSA_Tests_KAT, "test_verify_positive_%d" % idx, positive_test)
    else:
        setattr(FIPS_ECDSA_Tests_KAT, "test_verify_negative_%d" % idx, negative_test)


test_vectors_sign = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "ECDSA"),
예제 #41
0
파일: test_dss.py 프로젝트: shubhanus/taiga
                                 {'result': lambda x: x,
                                  'qx': lambda x: int(x, 16),
                                  'qy': lambda x: int(x, 16),
                                  })

for idx, tv in enumerate(test_vectors_verify):

    if isinstance(tv, str):
        res = re.match("\[P-256,(SHA-[0-9]+)\]", tv)
        assert res
        hash_name = res.group(1).replace("-", "")
        hash_module = load_hash_by_name(hash_name)
        continue

    hash_obj = hash_module.new(tv.msg)
    key = ECC.construct(curve="P-256", point_x=tv.qx, point_y=tv.qy)
    verifier = DSS.new(key, 'fips-186-3')

    def positive_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        verifier.verify(hash_obj, signature)

    def negative_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s):
        self.assertRaises(ValueError, verifier.verify, hash_obj, signature)

    if tv.result.startswith('p'):
        setattr(FIPS_ECDSA_Tests, "test_verify_positive_%d" % idx, positive_test)
    else:
        setattr(FIPS_ECDSA_Tests, "test_verify_negative_%d" % idx, negative_test)


test_vectors_sign = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "ECDSA"),