コード例 #1
0
def isComposite(a, k, m, n):
        if ModularExponentiation.modExp(a, m, n) == 1:  # test to see if a^m mod n == 1, if so n is probably prime
            return False
        for i in range(k):
            # test to see if a^(m*(2^i)) mod n is -1, where 0 <= i < k
            # This covers the a^m mod n == -1 as well as all future increments by the power of 2
            # because a^(m*(2*i)) mod n = (a^m)^(2*i) mod n, where 0 <= i < k
            if ModularExponentiation.modExp(a, 2**i * m, n) == n-1:  # if this result is -1 then it is probably prime
                return False
        return True  # if the result was never -1 after k iterations, this number is composite
コード例 #2
0
def Encrypt(message):
    PublicKeyFile = open("K1", "r")

    prime = int(PublicKeyFile.readline())  # the prime number
    PrimitiveRoot = int(PublicKeyFile.readline())  # the primitve root of the prime
    h = int(PublicKeyFile.readline())  # PrimitiveRoot^x mod prime    Where x is the random number in the private key

    PublicKeyFile.close()

    CiphertextFile = open("Cipher", "w")
    for character in message:  # for every ascii character that is in the string message
        k = random.randint(0, prime - 1)  # Find a random number, k, where 0 <= k <= p-1
        r = ModularExponentiation.modExp(PrimitiveRoot, k, prime)  # Compute r, where r = PrimitiveRoot^k mod prime
        t = (
            ModularExponentiation.modExp(h, k, prime) * ord(character) % prime
        )  # Compute t, where t = (h^k mod prime) * [ascii value of character] mod prime
        CiphertextFile.write(str(r) + " " + str(t) + "\n")  # writes these values to the file named 'Cipher'

    CiphertextFile.close()
コード例 #3
0
def primitiveRoot(p):
    while True:  # until a primitive root is found
        g = random.randint(2, p-1)  # take a random integer value 2 <= g <= p-1
        if ModularExponentiation.modExp(g, p-1, p) == 1:  # Test to see if g is a primitive root
            return g  # if it is a primitive root, return g
コード例 #4
0
__author__ = 'David'

import ModularExponentiation as ME
import random

"""
This module is used to ensure the correctness of the Modular Exponentiation module.
Python has a built in modular exponentiation function so this test is very simple.
The current setting has this testing 10000 random values x, y, n where x^y mod n is calculated
by both the pow function and my modular exponentiation function. If they differ increment the error
counter and alert the tester
"""

if __name__ == '__main__':
    ErrorCount = 0
    for i in range(10000):
        x = random.randint(2, 10000)
        y = random.randint(2, 10000)
        n = random.randint(1000, 20000)
        powVale = pow(x, y, n)
        ModExpVal = ME.modExp(x, y, n)
        if(ModExpVal != powVale):
            print('Error! PowVal = ', powVale, 'ModExpVal = ', ModExpVal)
            ErrorCount += 1
    print(ErrorCount)