def sign(message, basePoint, basePointOrder, secretKey):
   modR = FiniteField(basePointOrder, 1)
   oneTimeSecret = generateSecretKey(len(bin(basePointOrder)) - 3) # numbits(order) - 1

   auxiliaryPoint = oneTimeSecret * basePoint
   signature = modR(oneTimeSecret).inverse() * (modR(message) + modR(secretKey) * modR(auxiliaryPoint[0]))

   return (message, auxiliaryPoint, signature)
def authentic(signedMessage, basePoint, basePointOrder, publicKey):
   modR = FiniteField(basePointOrder, 1)
   (message, auxiliary, signature) = signedMessage

   sigInverse = modR(signature).inverse()
   c, d = sigInverse * modR(message), sigInverse * modR(auxiliary[0])
   auxiliaryChecker = int(c) * basePoint + int(d) * publicKey

   print("Checking if %s == %s" % (auxiliaryChecker, auxiliary))
   return auxiliaryChecker == auxiliary
Exemplo n.º 3
0

if __name__ == "__main__":
    #TCP_IP = 'localhost'
    TCP_IP = '192.168.11.4'
    TCP_PORT = 5005
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))

    with open('cert', 'r') as cert:
        data = cert.read()
    encodeddata = "-----BEGIN CERTIFICATE-----\n" + str(
        base64.b64encode(data.encode('utf-8')).decode(
            'utf-8')) + "\n-----END CERTIFICATE-----"
    #Curve Exchange info
    F = FiniteField(412220184797, 1)
    curve = EllipticCurve(a=F(10717230661382162362098424417014722231813),
                          b=F(22043581253918959176184702399480186312))
    G = Point(curve, F(56797798272), F(349018778637))
    s.recv(1024)
    s.close()
    s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s1.connect((TCP_IP, TCP_PORT))
    s1.sendall(encodeddata.encode('utf-8'))
    s1.close()

    s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s2.connect((TCP_IP, TCP_PORT))

    #Private key:
    private_key = 6895697291
Exemplo n.º 4
0
    def to_dense(self):
        mat = np.empty((self.m, self.n), dtype='O')
        mat.fill(self.zero)
        for (i, j), val in self.items():
            mat[i, j] = val
        return mat

    def __repr__(self):
        return repr(self.rowdicts)


#-
# Examples
if __name__ == '__main__':
    Fp = FiniteField(
        52435875175126190479447740508185965837690552500527637822603658699938581184513,
        1)  # (# noqa: E501)
    Poly = polynomialsOver(Fp)

    n = 8
    omega = get_omega(Fp, n)
    PolyEvalRep = polynomialsEvalRep(Fp, omega, n)

    f = Poly([1, 2, 3, 4, 5])
    xs = tuple([omega**i for i in range(n)])
    ys = tuple(map(f, xs))
    # print('xs:', xs)
    # print('ys:', ys)

    assert f == PolyEvalRep(xs, ys).to_coeffs()
Exemplo n.º 5
0
from finitefield.finitefield import FiniteField
from linearsolver.linearsolver import someSolution

FF = FiniteField(13)
A = [
    [FF(4), FF(2), FF(9), FF(1)],
    [FF(4), FF(3), FF(6), FF(1)],
    [FF(2), FF(11), FF(5), FF(1)],
]

B = someSolution(A)
def authentic(signedMessage, basePoint, basePointOrder, publicKey):
   modR = FiniteField(basePointOrder, 1)
   (message, auxiliary, signature) = signedMessage

   sigInverse = modR(signature).inverse()
   c, d = sigInverse * modR(message), sigInverse * modR(auxiliary[0])
   auxiliaryChecker = int(c) * basePoint + int(d) * publicKey

   print("Checking if %s == %s" % (auxiliaryChecker, auxiliary))
   return auxiliaryChecker == auxiliary



if __name__ == "__main__":
   F = FiniteField(1061, 1)

   # Totally insecure curve: y^2 = x^3 + 3x + 181
   curve = EllipticCurve(a=F(3), b=F(181))
   basePoint = Point(curve, F(2), F(81))
   basePointOrder = 349
   secretKey = generateSecretKey(8) # 255 < 349, which is not quite uniform but good for demonstration purposes
   publicKey = secretKey * basePoint

   print(('Public information:\n\tfield: %s\n\tcurve: %s\n\tnumber of points on curve: %d x %d\n\t' +
         'base point: %s\n\tpublic key: %s') % (F.__name__, curve, basePointOrder, 3, basePoint, publicKey))

   message = 123
   signedMessage = sign(message, basePoint, basePointOrder, secretKey)
   print('Signed message: %s' % (signedMessage,))
Exemplo n.º 7
0
from finitefield.finitefield import FiniteField

q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
Fq = FiniteField(q, 1)


# Twisted Edwards Curve
class ProjectiveEdwards(object):
    def __init__(self, a, d):
        self.a = a
        self.d = d

        self.disc = a * d * (a - d) * (a - d) * (a - d) * (a - d)
        self.j = 16 * (a * a + 14 * a * d + d * d) * (a * a + 14 * a * d + d * d) * \
                 (a * a + 14 * a * d + d * d) / self.disc
        if not self.isSmooth():
            raise Exception("The curve %s is not smooth!" % self)

    def isSmooth(self):
        return self.disc != 0

    def testPoint(self, x, y):
        return self.a * x * x + y * y == 1 + self.d * x * x * y * y

    def __str__(self):
        # return '%sx^2 + y^2 = 1 + %sx^2y^2' % (self.a, self.d)
        return "Projective: "

    def __repr__(self):
        return str(self)
    return privateKey * receiveFunction()


def slowOrder(point):
    Q = point
    i = 1
    while True:
        if type(Q) is Ideal:
            return i
        else:
            Q = Q + point
            i += 1


if __name__ == "__main__":
    F = FiniteField(3851, 1)

    # Totally insecure curve: y^2 = x^3 + 324x + 1287
    curve = EllipticCurve(a=F(324), b=F(1287))

    # order is 1964
    basePoint = Point(curve, F(920), F(303))

    aliceSecretKey = generateSecretKey(8)
    bobSecretKey = generateSecretKey(8)

    print('Secret keys are %d, %d' % (aliceSecretKey, bobSecretKey))

    alicePublicKey = sendDH(aliceSecretKey, basePoint, lambda x: x)
    bobPublicKey = sendDH(bobSecretKey, basePoint, lambda x: x)
from elliptic_basic import EllipticCurve, Point
from finitefield.finitefield import FiniteField

# as we have known, finite field using euclidean for finding inverse
if __name__ == "__main__":
    F5 = FiniteField(5, 1)
    C = EllipticCurve(a=F5(1), b=F5(1))
    P = Point(C, F5(2), F5(1))

    print(P, 2*P, 3*P)

    #  fieldsize 25
    F25 = FiniteField(5, 2)
    print(F25.idealGenerator)

    curve = EllipticCurve(a=F25([1]), b=F25([1]))

    x = F25([2, 1])
    y = F25([0, 2])
    print(y*y - x*x*x - x - 1)
    print(curve.testPoint(x, y))

    P = Point(curve, F25([2]), F25([1]))
    print(-P, P+P, 4*P, 9*P)
Exemplo n.º 10
0
from copy import deepcopy
from welchberlekamp import makeEncoderDecoder
from finitefield.finitefield import FiniteField

## Setup ##
n = 3  # Number of Packets we want to send
k = 2  # Maximum number of errors we can tolerate
p = 11  # We're working on finite field modulo p
Fp = FiniteField(p)
enc, dec, solveSystem = makeEncoderDecoder(n + 2 * k, n, p)

## Encode Message like this ##
message = [3, 4, 0]
encoded = enc(message)
print("The encoded message is:")
print(encoded)

## Decode Message like this ##
received = deepcopy(encoded)
received[0] = Fp(2)  #Changing a message in received.
received[1] = Fp(1)  #Changing a message in received.
received[2] = Fp(0)  #Changing a message in received.
received[3] = Fp(2)  #Changing a message in received.
received[4] = Fp(10)  #Changing a message in received.
print("The received message is:")
print(received)
decoded = dec(received)
print("Decoded message is:")
print(decoded)
Exemplo n.º 11
0
def makeEncoderDecoder(n, k, p):
    if not k <= n <= p:
        raise Exception(
            "Must have k <= n <= p but instead had (n,k,p) == (%r, %r, %r)" %
            (n, k, p))

    Fp = FiniteField(p)
    Poly = polynomialsOver(Fp)
    maxE = ((n - k) // 2)  # maximum allowed number of errors

    # message is a list of integers at most p
    def encode(message):
        if not all(x < p for x in message):
            raise Exception(
                "Message is improperly encoded as integers < p. It was:\n%r" %
                message)

        def row(i, b):
            return [Fp(i**(j)) for j in range(k)] + [Fp(b)]

        system = [row(i, message[i]) for i in range(k)]

        interpolated = someSolution(system, freeVariableValue=1)
        thePoly = Poly(interpolated)
        print("Original message is:")
        print(message)
        print("The polynomial encoding the message is:")
        print(thePoly)
        return [thePoly(Fp(i)) for i in range(n)]

    def solveSystem(encodedMessage, debug=True):
        for e in range(maxE, 0, -1):
            ENumVars = e
            QNumVars = e + k

            def row(i, x, r):
                return ([r * x**j for j in range(ENumVars)] +
                        [-1 * x**j
                         for j in range(QNumVars)] + [-r * x**ENumVars]
                        )  # the "extended" part of the linear system

            system = ([
                row(i, a, b) for (i, (a, b)) in enumerate(encodedMessage)
            ])
            # Add one more row in the end ensure coefficient of x^e in E(x) is 1

            if debug:
                print("\nSystem of equations is:\n\n")
                for row in system:
                    print("\t%r" % (row, ))

            solution = someSolution(system, freeVariableValue=1)
            E = Poly([solution[j] for j in range(ENumVars)] + [Fp(1)])
            Q = Poly([solution[j] for j in range(ENumVars, len(solution))])

            if debug:
                print("\nReduced system is:\n\n")
                for row in system:
                    print("\t%r" % (row, ))

                print("Solution is %r" % (solution, ))
                print("Q is %r" % (Q, ))
                print("E is %r" % (E, ))

            P, remainder = Q.__divmod__(E)
            if remainder == 0:
                return Q, E

        raise Exception("found no divisors!")

    def decode(encodedMessage):
        encodedMessage = [[Fp(i), encodedMessage[i]]
                          for i in range(len(encodedMessage))]
        Q, E = solveSystem(encodedMessage)

        Pcoefs, remainder = Q.__divmod__(E)
        if remainder != 0:
            raise Exception("Q is not divisibly by E!")
        P = Poly(Pcoefs)
        print("Decoded polynomial r(x) = Q(x) / E(x) is: ")
        print(P)
        return [P(Fp(i)) for i in range(k)]

    return encode, decode, solveSystem
from functools import reduce
sys.path += ['elliptic-curves-finite-fields']
from finitefield.finitefield import FiniteField
from finitefield.polynomial import polynomialsOver
from finitefield.euclidean import extendedEuclideanAlgorithm
from elliptic import EllipticCurve, Point, Ideal
import elliptic
import os
import random
from polynomials import polynomialsOver, eval_poly, interpolate
from prime_mod_sqrt import prime_mod_sqrt
from itertools import combinations

# Parameters for MPC
# We make use of a field Fp() that is a large prime number
Fp = FiniteField(
    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, 1)
Poly = polynomialsOver(Fp)

# For convenience, upgrade the polynomial class with static methods.
# If f is a Poly, then you can call f(x) to evaluate the polynomial
Poly.__call__ = eval_poly
Poly.interpolate = staticmethod(
    lambda *args, **kwargs: interpolate(Poly, *args, **kwargs))
"""
## Generate a random polynomial with a given degree
"""


def random_poly_with_intercept(Poly, s, k):
    # Returns a degree-k polynomial f
    # such that f(0) = s
    # NIST Approved Curve
    curve_name = 'secp256k1'
    # Field characteristic.
    p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
    # Curve coefficients.
    a = 0
    b = 7
    # Base point.
    g = (0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
         0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8)
    # Subgroup order.
    n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
    # Subgroup cofactor.
    h = 1

    F = FiniteField(p, 1)

    curve = EllipticCurve(a=F(a), b=F(b))

    basePoint = Point(curve, F(g[0]), F(g[1]))
    print(basePoint)

    aliceSecretKey = generateSecretKey(32)
    bobSecretKey = generateSecretKey(32)

    print('Secret keys are %d, %d' % (aliceSecretKey, bobSecretKey))

    alicePublicKey = sendDH(aliceSecretKey, basePoint, lambda x: x)
    bobPublicKey = sendDH(bobSecretKey, basePoint, lambda x: x)

    sharedSecret1 = receiveDH(bobSecretKey, lambda: alicePublicKey)
def makeEncoderDecoder(n, k, p):
    if not k <= n <= p:
        raise Exception(
            "Must have k <= n <= p but instead had (n,k,p) == (%r, %r, %r)" %
            (n, k, p))

    Fp = FiniteField(p)
    Poly = polynomialsOver(Fp)
    maxE = ((n - k) // 2)  # maximum allowed number of errors

    # message is a list of integers at most p
    def encode(message):
        if not all(x < p for x in message):
            raise Exception(
                "Message is improperly encoded as integers < p. It was:\n%r" %
                message)

        thePoly = Poly(message)
        return [[Fp(i), thePoly(Fp(i))] for i in range(n)]

    def solveSystem(encodedMessage, debug=False):
        for e in range(maxE, 0, -1):
            ENumVars = e + 1
            QNumVars = e + k

            def row(i, a, b):
                return ([b * a**j for j in range(ENumVars)] +
                        [-1 * a**j for j in range(QNumVars)] + [0]
                        )  # the "extended" part of the linear system

            system = (
                [row(i, a, b) for (i, (a, b)) in enumerate(encodedMessage)] +
                [[0] * (ENumVars - 1) + [1] + [0] * (QNumVars) + [1]])
            # ensure coefficient of x^e in E(x) is 1

            if debug:
                print("\ne is %r" % e)
                print("\nsystem is:\n\n")
                for row in system:
                    print("\t%r" % (row, ))

            solution = someSolution(system, freeVariableValue=1)
            E = Poly([solution[j] for j in range(e + 1)])
            Q = Poly([solution[j] for j in range(e + 1, len(solution))])

            if debug:
                print("\nreduced system is:\n\n")
                for row in system:
                    print("\t%r" % (row, ))

                print("solution is %r" % (solution, ))
                print("Q is %r" % (Q, ))
                print("E is %r" % (E, ))

            P, remainder = Q.__divmod__(E)
            if remainder == 0:
                return Q, E

        raise Exception("found no divisors!")

    def decode(encodedMessage):
        Q, E = solveSystem(encodedMessage)

        P, remainder = Q.__divmod__(E)
        if remainder != 0:
            raise Exception("Q is not divisibly by E!")

        return P.coefficients

    return encode, decode, solveSystem
from finitefield.finitefield import FiniteField

import itertools


def findPoints(curve, field):
    print('Finding all points over %s' % (curve))
    print('The ideal generator is %s' % (field.idealGenerator))

    degree = field.idealGenerator.degree()
    subfield = field.primeSubfield
    xs = [
        field(x) for x in itertools.product(range(subfield.p), repeat=degree)
    ]
    ys = [
        field(x) for x in itertools.product(range(subfield.p), repeat=degree)
    ]

    points = [
        Point(curve, x, y) for x in xs for y in ys if curve.testPoint(x, y)
    ]
    return points


F25 = FiniteField(5, 2)
curve = EllipticCurve(a=F25(1), b=F25(1))
points = findPoints(curve, F25)

for point in points:
    print colored(point, 'yellow')
Exemplo n.º 16
0
from finitefield.finitefield import FiniteField
import random
import os
import sys

##
# This is the definition of secp256k1, Bitcoin's elliptic curve.
# You can probably skip this, it's a bunch of well-known numbers
##

# First the finite field
# q = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F
# this a a scratter using elliptic curve over finite fields
q = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
# q = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1
Fq = FiniteField(q, 1)  # elliptic curve over F_q

# Then the curve, always of the form y^2 = x^3 + {a6}
# The curve E: y2 = x3+ax+b over Fp is defined by:

# a = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
# b = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000007
curve = GeneralizedEllipticCurve(a6=Fq(7))  # Ex: y2 = x3+7

# base point, a generator of the group
# The base point G in compressed form is:

# G = 02 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798

Gx = Fq(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)
Gy = Fq(0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
Exemplo n.º 17
0
#| ## Polynomials library
#| We start with a library, `finite_field/`, for polynomials over finite fields,
#| represented by coefficients. The library includes:
#|  - Constructing a polynomial from a list of coefficients
#|  - Addition, scaling, multiplication of polynomials
#|  - Euclidean division of polynomials
#|  - Lagrange interpolation of polynomials
#|
#| The library is adapted from tutorials by Jeremy Kun.
#| See [A Programmer's Introudction to Mathematics](https://github.com/pim-book/programmers-introduction-to-mathematics)
#| and [Programming with Finite Fields](https://jeremykun.com/2014/03/13/programming-with-finite-fields/)
from finitefield.finitefield import FiniteField
from finitefield.polynomial import polynomialsOver

# Example: Fp(53)
Fp = FiniteField(53, 1)
Poly = polynomialsOver(Fp)


def _polydemo():
    p1 = Poly([1, 2, 3, 4, 5])
    # print(p1)
    # 1 + 2 t + 3 t^2 + 4 t^3 + 5 t^5


_polydemo()

#| ## Choosing a field and pairing-friendly elliptic curve
#| We need to define a finite field to work with, that corresponds to the order
#| of a pairing-friendly curve.
#| To keep notation down to a minimum, BabySNARK is defined for a symmetric (Type-1)