コード例 #1
0
def point_scalar_multiplication_double_and_add(a, b, p, x, y, scalar):
    """
    Implement Point multiplication with a scalar:
        r * (x, y) = (x, y) + ... + (x, y)    (r times)

    Reminder of Double and Multiply algorithm: r * P
        Q = infinity
        for i = 0 to num_bits(P)-1
            if bit i of r == 1 then
                Q = Q + P
            P = 2 * P
        return Q

    """
    assert Bn.is_prime(p)
    Q = (None, None)
    P = (x, y)

    for i in range(scalar.num_bits()):
        if scalar.is_bit_set(i):
            Q = point_add(a, b, p, P[0], P[1], Q[0], Q[1])
        else:
            # Wasteful point addition, added to prevent side channel attack
            W = point_add(a, b, p, P[0], P[1], Q[0], Q[1])
        P = point_double(a, b, p, P[0], P[1])
    return Q
コード例 #2
0
def point_double(a, b, p, x, y):
    """Define "doubling" an EC point.
     A special case, when a point needs to be added to itself.

     Reminder:
        lam = (3 * xp ^ 2 + a) * (2 * yp) ^ -1 (mod p)
        xr  = lam ^ 2 - 2 * xp
        yr  = lam * (xp - xr) - yp (mod p)

    Returns the point representing the double of the input (x, y).
    """
    assert Bn.is_prime(p)

    # Point at infinity
    if x is None and y is None:
        return (None, None)

    xr, yr = None, None
    lam = ((3 * (x * x) + a) * Bn.mod_inverse((2 * y), p)) % p
    xr = ((lam * lam) - 2 * x) % p
    yr = (lam * (x - xr) - y) % p
    return xr, yr
コード例 #3
0
def point_add(a, b, p, x0, y0, x1, y1):
    """Define the "addition" operation for 2 EC Points.

    Reminder: (xr, yr) = (xq, yq) + (xp, yp)
    is defined as:
        lam = (yq - yp) * (xq - xp)^-1 (mod p)
        xr  = lam^2 - xp - xq (mod p)
        yr  = lam * (xp - xr) - yp (mod p)

    Return the point resulting from the addition. Raises an Exception if the points are equal.
    """

    ## Curve: y^2 = x^3 + ax + b

    # ADD YOUR CODE BELOW
    assert isinstance(p, Bn) and p > 0
    assert Bn.is_prime(p)

    if (x0 is None) and (y0 is None):
        if x1 is None and y1 is None:
            return None, None
        else:
            return x1, y1
    elif x1 is None and y1 is None:
        return x0, y0

    if x0 == x1 and y0 == y1:
        raise Exception('EC Points must not be equal')

    xr, yr = None, None

    try:
        lam = ((y0 - y1) * (Bn.mod_inverse((x0 - x1), p))) % p
        xr = (lam**2 - x0 - x1) % p
        yr = (lam * (x0 - xr) - y0) % p
        return (xr, yr)
    except Exception:
        return (None, None)