Ejemplo n.º 1
0
class KeyAgreementTests(TestCase):
    def setUp(self):
        self.secp128r1 = get_params("secg", "secp128r1", "projective")
        self.add = self.secp128r1.curve.coordinate_model.formulas[
            "add-2007-bl"]
        self.dbl = self.secp128r1.curve.coordinate_model.formulas[
            "dbl-2007-bl"]
        self.mult = LTRMultiplier(self.add, self.dbl)
        self.priv_a = Mod(0xDEADBEEF, self.secp128r1.order)
        self.mult.init(self.secp128r1, self.secp128r1.generator)
        self.pub_a = self.mult.multiply(int(self.priv_a))
        self.priv_b = Mod(0xCAFEBABE, self.secp128r1.order)
        self.pub_b = self.mult.multiply(int(self.priv_b))

    @parameterized.expand([
        ("NONE", ECDH_NONE),
        ("SHA1", ECDH_SHA1),
        ("SHA224", ECDH_SHA224),
        ("SHA256", ECDH_SHA256),
        ("SHA384", ECDH_SHA384),
        ("SHA512", ECDH_SHA512),
    ])
    def test_all(self, name, algo):
        result_ab = algo(self.mult, self.secp128r1, self.pub_a,
                         self.priv_b).perform()
        result_ba = algo(self.mult, self.secp128r1, self.pub_b,
                         self.priv_a).perform()
        self.assertEqual(result_ab, result_ba)
Ejemplo n.º 2
0
 def setUp(self):
     self.secp128r1 = get_params("secg", "secp128r1", "projective")
     self.base = self.secp128r1.generator
     self.coords = self.secp128r1.curve.coordinate_model
     self.mult = LTRMultiplier(self.coords.formulas["add-1998-cmo"],
                               self.coords.formulas["dbl-1998-cmo"],
                               self.coords.formulas["z"],
                               always=True)
     self.mult.init(self.secp128r1, self.base)
Ejemplo n.º 3
0
 def setUp(self):
     self.secp128r1 = get_params("secg", "secp128r1", "projective")
     self.add = self.secp128r1.curve.coordinate_model.formulas[
         "add-2007-bl"]
     self.dbl = self.secp128r1.curve.coordinate_model.formulas[
         "dbl-2007-bl"]
     self.mult = LTRMultiplier(self.add, self.dbl)
     self.msg = 0xCAFEBABE.to_bytes(4, byteorder="big")
     self.priv = Mod(0xDEADBEEF, self.secp128r1.order)
     self.mult.init(self.secp128r1, self.secp128r1.generator)
     self.pub = self.mult.multiply(self.priv.x)
Ejemplo n.º 4
0
 def setUp(self):
     self.secp128r1 = get_params("secg", "secp128r1", "projective")
     self.add = self.secp128r1.curve.coordinate_model.formulas[
         "add-2007-bl"]
     self.dbl = self.secp128r1.curve.coordinate_model.formulas[
         "dbl-2007-bl"]
     self.mult = LTRMultiplier(self.add, self.dbl)
     self.priv_a = Mod(0xDEADBEEF, self.secp128r1.order)
     self.mult.init(self.secp128r1, self.secp128r1.generator)
     self.pub_a = self.mult.multiply(int(self.priv_a))
     self.priv_b = Mod(0xCAFEBABE, self.secp128r1.order)
     self.pub_b = self.mult.multiply(int(self.priv_b))
Ejemplo n.º 5
0
 def setUp(self):
     self.secp128r1 = get_params("secg", "secp128r1", "projective")
     self.add = self.secp128r1.curve.coordinate_model.formulas[
         "add-2007-bl"]
     self.dbl = self.secp128r1.curve.coordinate_model.formulas[
         "dbl-2007-bl"]
     self.mult = LTRMultiplier(self.add, self.dbl)
Ejemplo n.º 6
0
    def test_ecdsa_sign(self):
        self.target.allocate_sig(SignatureEnum.ALG_ECDSA_SHA)
        self.target.allocate(KeypairEnum.KEYPAIR_LOCAL, KeyBuildEnum.BUILD_KEYPAIR, 256,
                             KeyClassEnum.ALG_EC_FP)
        self.target.set(KeypairEnum.KEYPAIR_LOCAL, CurveEnum.secp256r1, ParameterEnum.DOMAIN_FP)
        self.target.generate(KeypairEnum.KEYPAIR_LOCAL)
        data = "Some text over here.".encode()
        ecdsa_resp = self.target.ecdsa_sign(KeypairEnum.KEYPAIR_LOCAL, True,
                                            SignatureEnum.ALG_ECDSA_SHA, data)
        self.assertTrue(ecdsa_resp.success)
        export_public_resp = self.target.export(KeypairEnum.KEYPAIR_LOCAL, KeyEnum.PUBLIC,
                                                ParameterEnum.W)
        pubkey_bytes = export_public_resp.get_param(KeypairEnum.KEYPAIR_LOCAL, ParameterEnum.W)
        pubkey = self.secp256r1.curve.decode_point(pubkey_bytes)
        pubkey_projective = pubkey.to_model(self.secp256r1_projective.curve.coordinate_model, self.secp256r1.curve)

        sig = SignatureResult.from_DER(ecdsa_resp.signature)
        mult = LTRMultiplier(
                self.secp256r1_projective.curve.coordinate_model.formulas["add-2016-rcb"],
                self.secp256r1_projective.curve.coordinate_model.formulas["dbl-2016-rcb"])
        ecdsa = ECDSA_SHA1(copy(mult), self.secp256r1_projective,
                           self.secp256r1_projective.curve.coordinate_model.formulas[
                               "add-2016-rcb"],
                           pubkey_projective)
        self.assertTrue(ecdsa.verify_data(sig, data))
Ejemplo n.º 7
0
    def test_ecdh_raw(self):
        self.target.allocate_ka(KeyAgreementEnum.ALG_EC_SVDP_DH)
        self.target.allocate(KeypairEnum.KEYPAIR_LOCAL, KeyBuildEnum.BUILD_KEYPAIR, 256,
                             KeyClassEnum.ALG_EC_FP)
        self.target.set(KeypairEnum.KEYPAIR_LOCAL, CurveEnum.secp256r1, ParameterEnum.DOMAIN_FP)
        self.target.generate(KeypairEnum.KEYPAIR_LOCAL)
        mult = LTRMultiplier(
                self.secp256r1_projective.curve.coordinate_model.formulas["add-2016-rcb"],
                self.secp256r1_projective.curve.coordinate_model.formulas["dbl-2016-rcb"])
        keygen = KeyGeneration(copy(mult), self.secp256r1_projective)
        priv, pubkey_projective = keygen.generate()

        ecdh_resp = self.target.ecdh_direct(KeypairEnum.KEYPAIR_LOCAL, True,
                                            TransformationEnum.NONE,
                                            KeyAgreementEnum.ALG_EC_SVDP_DH,
                                            bytes(pubkey_projective.to_affine()))
        self.assertTrue(ecdh_resp.success)
        export_privkey_resp = self.target.export(KeypairEnum.KEYPAIR_LOCAL, KeyEnum.PRIVATE,
                                                 ParameterEnum.S)
        privkey = Mod(int.from_bytes(
                export_privkey_resp.get_param(KeypairEnum.KEYPAIR_LOCAL, ParameterEnum.S), "big"),
                self.secp256r1.curve.prime)

        ecdh = ECDH_SHA1(copy(mult), self.secp256r1_projective, pubkey_projective, privkey)
        expected = ecdh.perform()
        self.assertEqual(ecdh_resp.secret, expected)
Ejemplo n.º 8
0
    def test_ecdh(self):
        self.target.allocate_ka(KeyAgreementEnum.ALG_EC_SVDP_DH)
        self.target.allocate(KeypairEnum.KEYPAIR_BOTH, KeyBuildEnum.BUILD_KEYPAIR, 256,
                             KeyClassEnum.ALG_EC_FP)
        self.target.set(KeypairEnum.KEYPAIR_BOTH, CurveEnum.secp256r1, ParameterEnum.DOMAIN_FP)
        self.target.generate(KeypairEnum.KEYPAIR_BOTH)
        ecdh_resp = self.target.ecdh(KeypairEnum.KEYPAIR_LOCAL, KeypairEnum.KEYPAIR_REMOTE, True,
                                     TransformationEnum.NONE, KeyAgreementEnum.ALG_EC_SVDP_DH)
        self.assertTrue(ecdh_resp.success)
        export_public_resp = self.target.export(KeypairEnum.KEYPAIR_LOCAL, KeyEnum.PUBLIC,
                                                ParameterEnum.W)
        pubkey_bytes = export_public_resp.get_param(KeypairEnum.KEYPAIR_LOCAL, ParameterEnum.W)
        pubkey = self.secp256r1.curve.decode_point(pubkey_bytes)
        export_privkey_resp = self.target.export(KeypairEnum.KEYPAIR_REMOTE, KeyEnum.PRIVATE,
                                                 ParameterEnum.S)
        privkey = Mod(int.from_bytes(
                export_privkey_resp.get_param(KeypairEnum.KEYPAIR_REMOTE, ParameterEnum.S), "big"),
                self.secp256r1.curve.prime)
        pubkey_projective = pubkey.to_model(self.secp256r1_projective.curve.coordinate_model, self.secp256r1.curve)

        mult = LTRMultiplier(
                self.secp256r1_projective.curve.coordinate_model.formulas["add-2016-rcb"],
                self.secp256r1_projective.curve.coordinate_model.formulas["dbl-2016-rcb"])
        ecdh = ECDH_SHA1(mult, self.secp256r1_projective, pubkey_projective, privkey)
        expected = ecdh.perform()
        self.assertEqual(ecdh_resp.secret, expected)
Ejemplo n.º 9
0
 def test_one(self):
     model = ShortWeierstrassModel()
     coords = model.coordinates["projective"]
     scalarmult = {
         "cls": LTRMultiplier,
         "add": coords.formulas["add-1998-cmo"],
         "dbl": coords.formulas["dbl-1998-cmo"],
         "scl": None,
         "always": True,
         "complete": False,
         "short_circuit": True
     }
     configs = list(
         all_configurations(model=model,
                            coords=coords,
                            scalarmult=scalarmult,
                            **self.base_independents()))
     self.assertEqual(len(configs), 1)
     scalarmult = LTRMultiplier(coords.formulas["add-1998-cmo"],
                                coords.formulas["dbl-1998-cmo"], None, True,
                                False, True)
     configs = list(
         all_configurations(model=model,
                            coords=coords,
                            scalarmult=scalarmult,
                            **self.base_independents()))
     self.assertEqual(len(configs), 1)
     configs = list(
         all_configurations(model=model,
                            scalarmult=scalarmult,
                            **self.base_independents()))
     self.assertEqual(len(configs), 1)
Ejemplo n.º 10
0
class ContextTests(TestCase):
    def setUp(self):
        self.secp128r1 = get_params("secg", "secp128r1", "projective")
        self.base = self.secp128r1.generator
        self.coords = self.secp128r1.curve.coordinate_model
        self.mult = LTRMultiplier(
            self.coords.formulas["add-1998-cmo"],
            self.coords.formulas["dbl-1998-cmo"],
            self.coords.formulas["z"],
            always=True,
        )
        self.mult.init(self.secp128r1, self.base)

    def test_null(self):
        with local() as ctx:
            self.mult.multiply(59)
        self.assertIsInstance(ctx, NullContext)

    def test_default(self):
        token = setcontext(DefaultContext())
        self.addCleanup(resetcontext, token)

        with local(DefaultContext()) as ctx:
            result = self.mult.multiply(59)
        self.assertEqual(len(ctx.actions), 1)
        action = next(iter(ctx.actions.keys()))
        self.assertIsInstance(action, ScalarMultiplicationAction)
        self.assertEqual(len(getcontext().actions), 0)
        self.assertEqual(result, action.result)

    def test_default_no_enter(self):
        with local(DefaultContext()) as default, self.assertRaises(ValueError):
            default.exit_action(RandomModAction(7))

    def test_path(self):
        with local(PathContext([0, 1])) as ctx:
            key_generator = KeyGeneration(self.mult, self.secp128r1, True)
            key_generator.generate()
        self.assertIsInstance(ctx.value, ScalarMultiplicationAction)
        with local(PathContext([0, 1, 7])) as ctx:
            key_generator = KeyGeneration(self.mult, self.secp128r1, True)
            key_generator.generate()

    def test_str(self):
        with local(DefaultContext()) as default:
            self.mult.multiply(59)
        str(default)
        str(default.actions)
        with local(NullContext()) as null:
            self.mult.multiply(59)
        str(null)
Ejemplo n.º 11
0
def main(profiler, mod, operations, directory):
    with TemporaryConfig() as cfg:
        cfg.ec.mod_implementation = mod
        p256 = get_params("secg", "secp256r1", "projective")
        coords = p256.curve.coordinate_model
        add = coords.formulas["add-2016-rcb"]
        dbl = coords.formulas["dbl-2016-rcb"]
        mult = LTRMultiplier(add, dbl)
        click.echo(
            f"Profiling {operations} {p256.curve.prime.bit_length()}-bit scalar multiplication executions..."
        )
        one_point = p256.generator
        with Profiler(profiler, directory,
                      f"mult_ltr_rcb_p256_{operations}_{mod}"):
            for _ in range(operations):
                mult.init(p256, one_point)
                one_point = mult.multiply(
                    0x71A55E0C1ABB3A0E069419E0F837BC195F1B9545E69FC51E53C4D48D7FEA3B1A
                )
Ejemplo n.º 12
0
 def test_basic(self, name, scalar):
     mult = LTRMultiplier(
         self.add,
         self.dbl,
         self.scale,
         always=False,
         complete=False,
         short_circuit=True,
     )
     with local(MultipleContext()) as ctx:
         mult.init(self.secp128r1, self.base)
         mult.multiply(scalar)
     muls = list(ctx.points.values())
     self.assertEqual(muls[-1], scalar)
Ejemplo n.º 13
0
 def test_basic_build(self):
     platform = Platform.HOST
     hash_type = HashType.SHA1
     mod_rand = RandomMod.REDUCE
     mult = Multiplication.BASE
     sqr = Squaring.BASE
     red = Reduction.BASE
     inv = Inversion.GCD
     params = get_params("secg", "secp128r1", "projective")
     model = params.curve.model
     coords = params.curve.coordinate_model
     add = coords.formulas["add-1998-cmo"]
     dbl = coords.formulas["dbl-1998-cmo"]
     scl = coords.formulas["z"]
     formulas = [add, dbl, scl]
     scalarmult = LTRMultiplier(add, dbl, scl)
     config = DeviceConfiguration(model, coords, formulas, scalarmult,
                                  hash_type, mod_rand, mult, sqr, red, inv,
                                  platform, True, True, True)
     temp = tempfile.mkdtemp()
     render_and_build(config, temp, True)
Ejemplo n.º 14
0
    def test_ecdsa_verify(self):
        self.target.allocate_sig(SignatureEnum.ALG_ECDSA_SHA)
        self.target.allocate(
            KeypairEnum.KEYPAIR_LOCAL,
            KeyBuildEnum.BUILD_KEYPAIR,
            256,
            KeyClassEnum.ALG_EC_FP,
        )
        self.target.set(KeypairEnum.KEYPAIR_LOCAL, CurveEnum.secp256r1,
                        ParameterEnum.DOMAIN_FP)
        mult = LTRMultiplier(
            self.secp256r1_projective.curve.coordinate_model.
            formulas["add-2016-rcb"],
            self.secp256r1_projective.curve.coordinate_model.
            formulas["dbl-2016-rcb"],
        )
        keygen = KeyGeneration(copy(mult), self.secp256r1_projective)
        priv, pubkey_projective = keygen.generate()
        self.target.set(
            KeypairEnum.KEYPAIR_LOCAL,
            CurveEnum.external,
            ParameterEnum.W,
            ECTesterTarget.encode_parameters(ParameterEnum.W,
                                             pubkey_projective.to_affine()),
        )
        ecdsa = ECDSA_SHA1(
            copy(mult),
            self.secp256r1_projective,
            self.secp256r1_projective.curve.coordinate_model.
            formulas["add-2016-rcb"],
            pubkey_projective,
            priv,
        )
        data = "Some text over here.".encode()
        sig = ecdsa.sign_data(data)

        ecdsa_resp = self.target.ecdsa_verify(KeypairEnum.KEYPAIR_LOCAL,
                                              SignatureEnum.ALG_ECDSA_SHA,
                                              sig.to_DER(), data)
        self.assertTrue(ecdsa_resp.success)
Ejemplo n.º 15
0
class SignatureTests(TestCase):
    def setUp(self):
        self.secp128r1 = get_params("secg", "secp128r1", "projective")
        self.add = self.secp128r1.curve.coordinate_model.formulas[
            "add-2007-bl"]
        self.dbl = self.secp128r1.curve.coordinate_model.formulas[
            "dbl-2007-bl"]
        self.mult = LTRMultiplier(self.add, self.dbl)
        self.msg = 0xCAFEBABE.to_bytes(4, byteorder="big")
        self.priv = Mod(0xDEADBEEF, self.secp128r1.order)
        self.mult.init(self.secp128r1, self.secp128r1.generator)
        self.pub = self.mult.multiply(self.priv.x)

    @parameterized.expand([
        ("SHA1", ECDSA_SHA1),
        ("SHA224", ECDSA_SHA224),
        ("SHA256", ECDSA_SHA256),
        ("SHA384", ECDSA_SHA384),
        ("SHA512", ECDSA_SHA512),
    ])
    def test_all(self, name, algo):
        signer = algo(self.mult, self.secp128r1, privkey=self.priv)
        self.assertTrue(signer.can_sign)
        sig = signer.sign_data(self.msg)
        verifier = algo(self.mult,
                        self.secp128r1,
                        add=self.add,
                        pubkey=self.pub)
        self.assertTrue(verifier.can_verify)
        self.assertTrue(verifier.verify_data(sig, self.msg))

        none = ECDSA_NONE(self.mult,
                          self.secp128r1,
                          add=self.add,
                          pubkey=self.pub,
                          privkey=self.priv)
        digest = signer.hash_algo(self.msg).digest()
        sig = none.sign_hash(digest)
        self.assertTrue(none.verify_hash(sig, digest))

    def test_cannot(self):
        ok = ECDSA_NONE(self.mult,
                        self.secp128r1,
                        add=self.add,
                        pubkey=self.pub,
                        privkey=self.priv)
        data = b"aaaa"
        sig = ok.sign_data(data)

        no_priv = ECDSA_NONE(self.mult, self.secp128r1, pubkey=self.pub)
        with self.assertRaises(RuntimeError):
            no_priv.sign_data(data)
        with self.assertRaises(RuntimeError):
            no_priv.sign_hash(data)
        no_pubadd = ECDSA_NONE(self.mult, self.secp128r1, privkey=self.priv)
        with self.assertRaises(RuntimeError):
            no_pubadd.verify_data(sig, data)
        with self.assertRaises(RuntimeError):
            no_pubadd.verify_hash(sig, data)

        with self.assertRaises(ValueError):
            Signature(self.mult, self.secp128r1)

    @parameterized.expand([
        ("SHA1", ECDSA_SHA1),
        ("SHA224", ECDSA_SHA224),
        ("SHA256", ECDSA_SHA256),
        ("SHA384", ECDSA_SHA384),
        ("SHA512", ECDSA_SHA512),
    ])
    def test_fixed_nonce(self, name, algo):
        signer = algo(self.mult, self.secp128r1, privkey=self.priv)
        sig_one = signer.sign_data(self.msg, nonce=0xABCDEF)
        sig_other = signer.sign_data(self.msg, nonce=0xABCDEF)
        verifier = algo(self.mult,
                        self.secp128r1,
                        add=self.add,
                        pubkey=self.pub)
        self.assertTrue(verifier.verify_data(sig_one, self.msg))
        self.assertTrue(verifier.verify_data(sig_other, self.msg))
        self.assertEqual(sig_one, sig_other)

    def test_der(self):
        sig = SignatureResult(0xAAAAA, 0xBBBBB)
        self.assertEqual(sig, SignatureResult.from_DER(sig.to_DER()))
        self.assertNotEqual(sig, "abc")
Ejemplo n.º 16
0
    def test_basic_multipliers(self, name, num, add, dbl):
        ltr = LTRMultiplier(self.coords.formulas[add],
                            self.coords.formulas[dbl], self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            ltr.multiply(1)
        ltr.init(self.secp128r1, self.base)
        res_ltr = ltr.multiply(num)
        rtl = RTLMultiplier(self.coords.formulas[add],
                            self.coords.formulas["dbl-1998-cmo"], self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            rtl.multiply(1)
        rtl.init(self.secp128r1, self.base)
        res_rtl = rtl.multiply(num)
        self.assertEqual(res_ltr, res_rtl)

        ltr_always = LTRMultiplier(self.coords.formulas[add],
                                   self.coords.formulas[dbl], self.coords.formulas["z"],
                                   always=True)
        rtl_always = RTLMultiplier(self.coords.formulas[add],
                                   self.coords.formulas[dbl], self.coords.formulas["z"],
                                   always=True)
        ltr_always.init(self.secp128r1, self.base)
        rtl_always.init(self.secp128r1, self.base)
        res_ltr_always = ltr_always.multiply(num)
        res_rtl_always = rtl_always.multiply(num)
        self.assertEqual(res_ltr, res_ltr_always)
        self.assertEqual(res_rtl, res_rtl_always)

        bnaf = BinaryNAFMultiplier(self.coords.formulas[add],
                                   self.coords.formulas[dbl],
                                   self.coords.formulas["neg"], self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            bnaf.multiply(1)
        bnaf.init(self.secp128r1, self.base)
        res_bnaf = bnaf.multiply(num)
        self.assertEqual(res_bnaf, res_ltr)

        wnaf = WindowNAFMultiplier(self.coords.formulas[add],
                                   self.coords.formulas[dbl],
                                   self.coords.formulas["neg"], 3, self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            wnaf.multiply(1)
        wnaf.init(self.secp128r1, self.base)
        res_wnaf = wnaf.multiply(num)
        self.assertEqual(res_wnaf, res_ltr)

        ladder = SimpleLadderMultiplier(self.coords.formulas[add],
                                        self.coords.formulas[dbl],
                                        self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            ladder.multiply(1)
        ladder.init(self.secp128r1, self.base)
        res_ladder = ladder.multiply(num)
        self.assertEqual(res_ladder, res_ltr)

        coron = CoronMultiplier(self.coords.formulas[add],
                                self.coords.formulas[dbl],
                                self.coords.formulas["z"])
        with self.assertRaises(ValueError):
            coron.multiply(1)
        coron.init(self.secp128r1, self.base)
        res_coron = coron.multiply(num)
        self.assertEqual(res_coron, res_ltr)