椭圆曲线点乘法有时会产生错误的结果

问题描述 投票:1回答:1

我试图在Python中使用标量乘法来实现椭圆曲线点,并且在某些情况下我会得到不正确的结果并且正在努力弄清楚可能出错的问题。

这是执行计算的函数:

def __mul__(self, other):
    """
    Scalar multiplication of a point with a integer
    The point gets added to itself other times
    This can be efficiently computed using binary
    representation of the scalar

    :param other: int number to multiply the point with
    :return: Point point after applying the multiplication
    """
    if other < 1 or other > self.order():
        raise Exception("Scalar for point mult is out of range")

    # Convert into binary representation
    scalar_bin = str(bin(other))[2:]

    new_point = self.curve().g()
    # Iterate through every bit of the scalar
    # double the current point and if it is a 1 bit
    # we add the generator point
    for i in range(1, len(scalar_bin)):
        new_point = new_point + new_point
        if scalar_bin[i] == "1":
            new_point = new_point + self.curve().g()
    return new_point

我已经测试了多个值,有时会得到正确的,有时不正确的结果。以下是secp256k1曲线的一些示例:

Correct case:

Point: 
x: 55066263022277343669578718895168534326250603453777594175500187360389116729240
y: 32670510020758816978083085130507043184471273380659243275938904335757337482424

Scalar:
24917563387128992525586541072555299775466638713533702470001729610242625242518

Result:
x: 30761640594611050927920473896980176618852175787129035469672454552631110981601
y: 71589730992642335000963807008595655528549796860255114743222783656832671116115

Incorrect case:

Point:
x: 55763821349469695143251444157857527262741225298806100934200365505846997750729
y: 108311437762381308673474438597429390041179265557837286648496266777408263200496

Scalar:
14153923515125836933174734651094672686604752309351060890449588899992278900437

Result:
x: 33276244942913720410563273329803338573012270278748134958920446992664092974057
y: 38066195899997010281080208319525128360573241938488491930954474962286948555539
python math cryptography elliptic-curve ecdsa
1个回答
0
投票

所以我想出了这个问题并且任何人都很难看到因为数学似乎是正确的,但是我做了一个编程错误,如果你看一下上下文中的函数就不容易看到。

所呈现的代码将始终对曲线的生成点进行标量乘法,而不是自我实际引用的点。 Self是一个点的实例,但在概述的代码中从不直接引用,而是将曲线生成器点相乘。

new_point = self.curve().g()

应该被替换

new_point = self

new_point = new_point + self.curve().g()

通过

new_point = new_point + self

我仍然有点不清楚这些代码在某些情况下如何产生正确的例子。

© www.soinside.com 2019 - 2024. All rights reserved.