Example #1
0
    def generate_triples(self, field, quantity=1, gather=True):
        """Generate *quantity* multiplication triples using PRSS.

        These are random numbers *a*, *b*, and *c* such that ``c =
        ab``. This function can be used in pre-processing.

        Returns a tuple with the number of triples generated and a
        Deferred which will yield a singleton-list with a 3-tuple.
        """

        # This adjusted to the PRF based on SHA1 (160 bits).
        quantity = min(quantity, max(int(160 /numdigits(field.modulus - 1, 2)), 1))

        a_t = self.prss_share_random_multi(field, quantity)
        b_t = self.prss_share_random_multi(field, quantity)
        r_t, r_2t = self.prss_double_share(field, quantity)
        c_t = [0] * quantity

        for i in range(quantity):
            # Multiply a and b without resharing.
            c_2t = gather_shares([a_t[i], b_t[i]])
            c_2t.addCallback(lambda (a, b): a * b)

            d_2t = c_2t - r_2t[i]
            d = self.open(d_2t, threshold=2*self.threshold)
            c_t[i] = r_t[i] + d

        if gather:
            return [gatherResults(triple) for triple in zip(a_t, b_t, c_t)]
        else:
            return zip(a_t, b_t, c_t)
Example #2
0
File: active.py Project: lu562/viff
    def generate_triples(self, field, quantity=1, gather=True):
        """Generate *quantity* multiplication triples using PRSS.

        These are random numbers *a*, *b*, and *c* such that ``c =
        ab``. This function can be used in pre-processing.

        Returns a tuple with the number of triples generated and a
        Deferred which will yield a singleton-list with a 3-tuple.
        """

        # This adjusted to the PRF based on SHA1 (160 bits).
        quantity = min(quantity,
                       max(int(160 / numdigits(field.modulus - 1, 2)), 1))

        a_t = self.prss_share_random_multi(field, quantity)
        b_t = self.prss_share_random_multi(field, quantity)
        r_t, r_2t = self.prss_double_share(field, quantity)
        c_t = [0] * quantity

        for i in range(quantity):
            # Multiply a and b without resharing.
            c_2t = gather_shares([a_t[i], b_t[i]])
            c_2t.addCallback(lambda (a, b): a * b)

            d_2t = c_2t - r_2t[i]
            d = self.open(d_2t, threshold=2 * self.threshold)
            c_t[i] = r_t[i] + d

        if gather:
            return [gatherResults(triple) for triple in zip(a_t, b_t, c_t)]
        else:
            return zip(a_t, b_t, c_t)
Example #3
0
    def rerandomize(self, nworkers=None, use_threads=False, progress=None):
        """ Rerandomizes blocks: they will still decrypt to the same
            plaintext. """
        _progress = None
        if progress is not None:

            def _progress(n):
                progress(float(n) / self.nblocks)

        if not nworkers:
            nworkers = multiprocessing.cpu_count()
        l.debug("Rerandomizing %s blocks on %s workers ...", self.nblocks,
                nworkers)
        start_time = time.time()
        gp = self.group_params
        self.data['blocks'] = pol.parallel.parallel_map(
            _eg_rerandomize_block,
            self.data['blocks'],
            args=(gp.g, gp.p),
            nworkers=nworkers,
            use_threads=use_threads,
            initializer=_eg_rerandomize_block_initializer,
            chunk_size=16,
            progress=_progress)
        secs = time.time() - start_time
        kbps = self.nblocks * gmpy.numdigits(gp.p, 2) / 1024.0 / 8.0 / secs
        if progress is not None:
            progress(1.0)
        l.debug(" done in %.2fs; that is %.2f KB/s", secs, kbps)
Example #4
0
File: safe.py Project: bwesterb/pol
    def rerandomize(self, nworkers=None, use_threads=False, progress=None):
        """ Rerandomizes blocks: they will still decrypt to the same
            plaintext. """
        _progress = None
        if progress is not None:

            def _progress(n):
                progress(float(n) / self.nblocks)

        if not nworkers:
            nworkers = multiprocessing.cpu_count()
        l.debug("Rerandomizing %s blocks on %s workers ...", self.nblocks, nworkers)
        start_time = time.time()
        gp = self.group_params
        self.data["blocks"] = pol.parallel.parallel_map(
            _eg_rerandomize_block,
            self.data["blocks"],
            args=(gp.g, gp.p),
            nworkers=nworkers,
            use_threads=use_threads,
            initializer=_eg_rerandomize_block_initializer,
            chunk_size=16,
            progress=_progress,
        )
        secs = time.time() - start_time
        kbps = self.nblocks * gmpy.numdigits(gp.p, 2) / 1024.0 / 8.0 / secs
        if progress is not None:
            progress(1.0)
        l.debug(" done in %.2fs; that is %.2f KB/s", secs, kbps)
Example #5
0
def fibonacci_term_number(length):
    '''
    Find Fibonacci's term number for number that contains over (length) digits
    '''
    index = long(1)
    #Initial step divisor value
    step_div = 1
    num = gmpy.mpz(0)
    while gmpy.numdigits(num) != length:

        golden_ratio = gmpy.mpf(((1 + gmpy.fsqrt(5)) / 2)**gmpy.mpf(index) / gmpy.fsqrt(5))
        num = gmpy.mpz(gmpy.fround(golden_ratio, 0))

        if gmpy.numdigits(num) < length:
            index += length / step_div
        #If the previous step was too large, then we go back and reduce it to 2 times
        if gmpy.numdigits(num) > length:
            index -= length / step_div
            step_div *= 2
    return index
Example #6
0
    def __init__(self, key, max):
        """Create a PRF keyed with the given key and max.

        The key must be a string whereas the max must be a number.
        Output value will be in the range zero to max, with zero
        included and max excluded.

        To make a PRF what generates numbers less than 1000 do:

        >>> f = PRF("key", 1000)

        The PRF can be evaluated by calling it on some input:

        >>> f("input")
        327L

        Creating another PRF with the same key gives identical results
        since f and g are deterministic functions, depending only on
        the key:

        >>> g = PRF("key", 1000)
        >>> g("input")
        327L

        We can test that f and g behave the same on many inputs:

        >>> [f(i) for i in range(100)] == [g(i) for i in range(100)]
        True

        Both the key and the max is used when the PRF is keyed. This
        means that

        >>> f = PRF("key", 1000)
        >>> g = PRF("key", 10000)
        >>> [f(i) for i in range(100)] == [g(i) for i in range(100)]
        False
        """
        self.max = max

        # Number of bits needed for a number in the range [0, max-1].
        bit_length = numdigits(max - 1, 2)

        # Number of whole digest blocks needed.
        blocks = int(ceil(bit_length / 8.0 / sha1().digest_size))

        # Number of whole bytes needed.
        self.bytes = int(ceil(bit_length / 8.0))
        # Number of bits needed from the final byte.
        self.bits = bit_length % 8

        self.sha1s = []
        for i in range(blocks):
            # TODO: this construction is completely ad-hoc and not
            # known to be secure...

            # Initial seed is key + str(max). The maximum is included
            # since we want PRF("input", 100) and PRF("input", 1000)
            # to generate different output.
            seed = key + str(max)

            # The i'th generator is seeded with H^i(key + str(max))
            # where H^i means repeated hashing i times.
            for _ in range(i):
                seed = sha1(seed).digest()
            self.sha1s.append(sha1(seed))
Example #7
0
    def __init__(self, key, max):
        """Create a PRF keyed with the given key and max.

        The key must be a string whereas the max must be a number.
        Output value will be in the range zero to max, with zero
        included and max excluded.

        To make a PRF what generates numbers less than 1000 do:

        >>> f = PRF("key", 1000)

        The PRF can be evaluated by calling it on some input:

        >>> f("input")
        327L

        Creating another PRF with the same key gives identical results
        since f and g are deterministic functions, depending only on
        the key:

        >>> g = PRF("key", 1000)
        >>> g("input")
        327L

        We can test that f and g behave the same on many inputs:

        >>> [f(i) for i in range(100)] == [g(i) for i in range(100)]
        True

        Both the key and the max is used when the PRF is keyed. This
        means that

        >>> f = PRF("key", 1000)
        >>> g = PRF("key", 10000)
        >>> [f(i) for i in range(100)] == [g(i) for i in range(100)]
        False
        """
        self.max = max

        # Number of bits needed for a number in the range [0, max-1].
        bit_length = numdigits(max-1, 2)

        # Number of whole digest blocks needed.
        blocks = int(ceil(bit_length / 8.0 / sha.digest_size))

        # Number of whole bytes needed.
        self.bytes = int(ceil(bit_length / 8.0))
        # Number of bits needed from the final byte.
        self.bits = bit_length % 8

        self.sha1s = []
        for i in range(blocks):
            # TODO: this construction is completely ad-hoc and not
            # known to be secure...

            # Initial seed is key + str(max). The maximum is included
            # since we want PRF("input", 100) and PRF("input", 1000)
            # to generate different output.
            seed = key + str(max)

            # The i'th generator is seeded with H^i(key + str(max))
            # where H^i means repeated hashing i times.
            for _ in range(i):
                seed = sha.new(seed).digest()
            self.sha1s.append(sha.new(seed))
if __name__ == '__main__':
    try:
        import gmpy
    except ImportError:
        pass
    else:
        ints = range(400)
        for n in ints:
            try:
                assert gmpy.digits(n, 2) == digits(n)
            except AssertionError:
                print 'digits fail %d' % n
                raise
            try:
                assert gmpy.numdigits(n, 2) == numdigits(n)
            except AssertionError:
                print 'numdigits fail %d' % n
                raise
            try:
                assert gmpy.popcount(n) == popcount(n)
            except AssertionError:
                print 'popcount fail %d' % n
                raise
        for n in list(ints):
            for i in ints:
                try:
                    assert gmpy.getbit(n, i) == getbit(n, i)
                except AssertionError:
                    print 'getbit fail %d, %d' % (n, i)
                    raise
Example #9
0
        gmp_initial_time += 1


def calculate_division(test, n):
    # print n
    # print 'number of digits in test is {} in base 2'.format(_g.numdigits(test,2))
    # print 'number of digits in n is {} in base 2'.format(_g.numdigits(n,2))
    prime = _g.next_prime(test)
    # print prime
    if _g.is_prime(prime):
        # print 'I got a prime {}'.format(prime)
        if n % prime == 0:
            print n
            print 'success'
            # print prime


# print 'hello'

a = _g.mpz(3)
b = _g.mpz(4)
a * b
n = _g.mpz(
    24273618023607084486640780738570808771621986433484759110890007663285083070301411494342166417501975875434396254572210883097197606002792961188765714012586572973883316624919480269976588918378510060114863169458998238884707186422078503198409711517331925718724992482313607561083572145615542689766892477475245783591560768105522701218201319805109927490758320089753382216289985913622881684008449778824296369632718648732093073866955919245262132806601747308245712568619870175403589653143883582535983611659536338442969098602432733731978529775504102960957720743400991276136582059048290901573859913873714239909117158697715526500669
)

digits = _g.numdigits(n, 2)
print 'number of digits in n is {}'.format(digits)
# print n
# calculate_seconds()
calculate_seed(n)
Example #10
0
                # print rvalue
                gmp_initial_ppid += 1
            gmp_initial_pid += 1
        # print gmp_initial_time
        gmp_initial_time += 1
        
def calculate_division(test, n):
    # print n
    # print 'number of digits in test is {} in base 2'.format(_g.numdigits(test,2))
    # print 'number of digits in n is {} in base 2'.format(_g.numdigits(n,2))
    prime = _g.next_prime(test)
    # print prime
    if _g.is_prime(prime):
        # print 'I got a prime {}'.format(prime)
        if n % prime == 0:
            print n
            print 'success'
            # print prime
    
# print 'hello'

a = _g.mpz(3)
b = _g.mpz(4)
a * b
n = _g.mpz(24273618023607084486640780738570808771621986433484759110890007663285083070301411494342166417501975875434396254572210883097197606002792961188765714012586572973883316624919480269976588918378510060114863169458998238884707186422078503198409711517331925718724992482313607561083572145615542689766892477475245783591560768105522701218201319805109927490758320089753382216289985913622881684008449778824296369632718648732093073866955919245262132806601747308245712568619870175403589653143883582535983611659536338442969098602432733731978529775504102960957720743400991276136582059048290901573859913873714239909117158697715526500669)

digits = _g.numdigits(n,2)
print 'number of digits in n is {}'.format(digits)
# print n
# calculate_seconds()
calculate_seed(n)