Ejemplo n.º 1
0
def generateKey(keySize):
    # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
    print('Generating p prime...')
    p = rabinMiller.generateLargePrime(keySize)
    print('Generating q prime...')
    q = rabinMiller.generateLargePrime(keySize)
    n = p * q
    print("\nN is: " + str(n) + "\n")
    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        e = random.randrange(2**(keySize - 1), 2**(keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # Step 3: Calculate d, the mod inverse of e.
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
    print("\nD is: ", d)  #Esta es la que se queda el propietario
    print("\nE is: ", e)  #Esta es la que se publica junto a n
    publicKey = (n, e)
    privateKey = (n, d)
    print('\nPublic key:', publicKey)
    print('\nPrivate key:', privateKey)
    return (publicKey, privateKey)
Ejemplo n.º 2
0
def generateKey(keySize):
    # Create public/private keys keySize bits in size
    p = 0
    q = 0
    # Create two primes, p and q. Calculate n = p * q
    print("Generating p prime...")
    while p == q:
        p = primeNum.generateLargePrime(keySize)
        q = primeNum.generateLargePrime(keySize)
    n = p * q

    # Create number e that is relatively prime to (p-1)*(q-1)
    print("Generating e that is relatively prime to (p-1) * (q-1)...")
    while True:
        # Keep trying rand numbers for e until one is valid
        e = random.randrange(2**(keySize - 1), 2**keySize)
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # Calculate d, mod inverse of e
    print("Calculating d that is the mod inverse of e...")
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print(f"Public key: {publicKey}")
    print(f"Private key: {privateKey}")

    return publicKey, privateKey
Ejemplo n.º 3
0
def generateKey(keySize):
    # Creates a public/private key pair with keys that are keySize bits in
    # size. This function may take a while to run.

    # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
    print('Generating p prime...')
    p = rabinMiller.generateLargePrime(keySize)
    print('Generating q prime...')
    q = rabinMiller.generateLargePrime(keySize)
    n = p * q

    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        # Keep trying random numbers for e until one is valid.
        e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # Step 3: Calculate d, the mod inverse of e.
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print('Public key:', publicKey)
    print('Private key:', privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 4
0
def inv_matrix_mod(m, n):
    """
    Calculates inverse m (mod n). Uses the numpy library to calculate the
    determinant and adj. matrix.

    Textbook example
    >>> m = [[1, 2],
    ...      [3, 4]]
    >>> inv_matrix_mod(m, 11)
    [[9, 1], [7, 5]]

    Textbook example 3x3
    >>> m = [[1, 1, 1],
    ...      [1, 2, 3],
    ...      [1, 4, 9]]
    >>> inv_matrix_mod(m, 11)
    [[3, 3, 6], [8, 4, 10], [1, 4, 6]]

    Random example
    >>> m = [[4, 7],
    ...      [2, 6]]
    >>> inv_matrix_mod(m, 11)
    [[5, 7], [2, 7]]

    Invalid example
    >>> m = [[4, 7],
    ...      [2, 6]]
    >>> inv_matrix_mod(m, 15)
    []

    :param m: Matrix
    :param n: modulus
    :return: [] if det(m), n are not relatively prime
             m (mod n), otherwise
    """
    import numpy as np
    import cryptomath

    size = len(m)

    # Matrix determinant
    det = int(np.around(np.linalg.det(m)))

    # if gcd(determinant, n) is not 1, return empty matrix
    if not cryptomath.gcd(det, n) == 1:
        return []

    # calculate adj(matrix) and mod inverse of determinant
    m_inv = det * np.linalg.inv(m)
    # print m_inv
    inv = cryptomath.findModInverse(det, n)

    # multiply matrix inverse with mod inverse and take (mod n) to get positive
    # values. Return inv m (mod n)
    for i in range(size):
        for j in range(size):
            m_inv[i][j] = int(np.around(m_inv[i][j] * inv % n))

    m_inv = m_inv.astype(int).tolist()
    return m_inv
def generateKey(keySize):
    # Creates a public/private key pair with keys that are keySize bits in
    # size. This function may take a while to run.

    # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
    print('Generating p prime...')
    p = rabinMiller.generateLargePrime(keySize)
    print('Generating q prime...')
    q = rabinMiller.generateLargePrime(keySize)
    n = p * q

    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        # Keep trying random numbers for e until one is valid.
        e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # Step 3: Calculate d, the mod inverse of e.
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print('Public key:', publicKey)
    print('Private key:', privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 6
0
def affineTranslate(message, key, mode):

    keyA, keyB = getKeyParts(key)
    checkKeys(keyA, keyB, mode)
    translatedMessage = ''
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))

    for symbol in message:
        if mode == 0:
            # encrypt this symbol
            if symbol in SYMBOLS:
                symIndex = SYMBOLS.find(symbol)
                translatedMessage += SYMBOLS[(symIndex * keyA + keyB) %
                                             len(SYMBOLS)]
            else:
                translatedMessage += symbol  # just append this symbol unencrypted
        elif mode == 1:
            if symbol in SYMBOLS:
                # decrypt this symbol
                symIndex = SYMBOLS.find(symbol)
                translatedMessage += SYMBOLS[(symIndex - keyB) *
                                             modInverseOfKeyA % len(SYMBOLS)]
            else:
                translatedMessage += symbol  # just append this symbol undecrypted
    return translatedMessage
Ejemplo n.º 7
0
def blockSizeHack(block, n, e):
    # This function decrypts the message from the given blocks, as well as the public key
    # block size is 1
    
    primeFactors = []
    
    blockSize = 1
    messageLength = len(block)

    #Finding the prime factors of n 
    for i in range(1, n + 1):

        if n % i == 0 :
            if primeNum.isPrime(i):

                primeFactors.append(i)

        #since n is semiprime, there are no composite numbers as factors other than itself. once we find the first 2 prime factors we can break 
        if len(primeFactors) >= 2:
            break

    p, q = getpq(primeFactors)


    r = (p-1) * (q-1)
    d = cryptomath.findModInverse(e, r)

    # use the decryptmessage from publicKeyCipher.py to figure out the message
    decryptedMessage = pkc.decryptMessage(block, messageLength, (n,d), blockSize)

    return decryptedMessage
Ejemplo n.º 8
0
55. def decryptMessage(key, message):
56.     keyA, keyB = getKeyParts(key)
57.     checkKeys(keyA, keyB, 'decrypt')
58.     plaintext = ''
59.     modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))
60.    
61.     for symbol in message:
62.         if symbol in SYMBOLS:
63.             # decrypt this symbol
64.             symIndex = SYMBOLS.find(symbol)
65.             plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
66.         else:
67.             plaintext += symbol # just append this symbol undecrypted
68.     return plaintext
69.
70.
71. def getRandomKey():
72.     while True:
73.         keyA = random.randint(2, len(SYMBOLS))
74.         keyB = random.randint(2, len(SYMBOLS))
75.         if cryptomath.gcd(keyA, len(SYMBOLS)) == 1:
76.             return keyA * len(SYMBOLS) + keyB
77.
78.
79. # If affineCipher.py is run (instead of imported as a module) call
80. # the main() function.
81. if __name__ == '__main__':
82.     main()
Ejemplo n.º 9
0
def generateKey(keySize):
   # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
   print('Generating p prime...')
   p = Rabin_Miller.generateLargePrime(keySize)
   print('Generating q prime...')
   q = Rabin_Miller.generateLargePrime(keySize)
   n = p * q
	
   # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
   print('Generating e that is relatively prime to (p-1)*(q-1)...')
   while True:
      e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
      if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
         break
   
   """
   The specified pair of numbers, n and e, form the RSA public key. e is a number that is greater than 1 but less than
   (p - 1) and (q - 1) and e is coprime to (p - 1) and (q - 1).
   """
   # Step 3: Calculate d, the mod inverse of e.
   print('Calculating d that is mod inverse of e...')
   d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
   publicKey = (n, e)
   privateKey = (n, d)
   print('Public key:', publicKey)
   print('Private key:', privateKey)
   return (publicKey, privateKey)
Ejemplo n.º 10
0
	def getTranslatedMessage(self):
		if self.mode[0] == 'd':
			self.keyA, self.keyB = self.getKeyParts(self.key)
			self.checkKeys(self.keyA, self.keyB, 'decrypt')
			plaintext = ''
			modInverseOfKeyA = cryptomath.findModInverse(self.keyA, self.SYMBOLS)

			for symbol in self.message:
				if symbol in self.SYMBOLS_str:
				# decrypt this symbol
					symIndex = self.SYMBOLS_str.find(symbol)
					plaintext += self.SYMBOLS_str[(symIndex - self.keyB) * modInverseOfKeyA % self.SYMBOLS]
				else:
					plaintext += symbol # just append this symbol undecrypted
			return plaintext
		else:
			self.keyA, self.keyB = self.getKeyParts(self.key)
			self.checkKeys(self.keyA, self.keyB, 'encrypt')
			ciphertext = ''
			for symbol in self.message:
				if symbol in self.SYMBOLS_str:
				# encrypt this symbol
					symIndex = self.SYMBOLS_str.find(symbol)
					ciphertext += self.SYMBOLS_str[(symIndex * self.keyA + self.keyB) % self.SYMBOLS]
				else:
					ciphertext += symbol # just append this symbol unencrypted
			return ciphertext
Ejemplo n.º 11
0
def generateKey(keysize):
    p = 0
    q = 0

    print('Generating p prime...')
    while p == q:
        p = primeNum.generateLargePrime(keysize)
        q = primeNum.generateLargePrime(keysize)
    n = p * q

    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        e = random.randrange(2**(keysize - 1), 2**(keysize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print('Public key:', publicKey)
    print('Private key:', privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 12
0
def genkeys(key):
    print "Generating two primes"
    p = E_23_RM.generateLargePrime(key)
    #    print "p produced"
    q = E_23_RM.generateLargePrime(key)
    #    print "q produced"
    n = p * q

    #create a number relatively prime to (p-1)*(q-1), this will be e
    while True:
        #       print "generating...."
        e = random.randrange(2**(key - 1), 2**(key))  # create random number e
        if cryptomath.gcd(e, (p - 1) *
                          (q - 1)) == 1:  #check if e relatively prime
            break

    #find the mod inverse
    d = cryptomath.findModInverse(e, ((p - 1) * (q - 1)))

    pubkey = (n, e)
    privkey = (n, d)

    print("public key is %s and the private key is %s" % (pubkey, privkey))

    return (pubkey, privkey)
Ejemplo n.º 13
0
def main():

    #msg = "\"Encryption works. Properly implemented strong crypto systems are one of the few things that you can rely on. Unfortunately, endpoint security is so terrifically weak that NSA can frequently find ways around it.\"— Edward Snowden"
    msg = "AFFINE CIPHER"
    Key = 187
    print('Key %s' % (Key))
    keyA = Key // len(
        Letters
    )  # KeyA is determined by the user defined key, floor-divided by number of characters presented in Letters
    keyB = Key % len(
        Letters
    )  # KeyB is determined by user defined key, then get the remainder when dividing by number of characters in Letters
    modInverseKeyA = cryptomath.findModInverse(
        keyA, len(Letters)
    )  # Call the function findModInverse from cryptomath module to calculate the modulo inverse of keyA and number of characters in Letters
    print("\n")
    print("Affine Key-A:", keyA)
    print("Affine Key-B:", keyB)
    print("Affine Mod-Inverse key-A:", modInverseKeyA)
    print("\n")
    translated = encrypt(Key, msg)
    print("Affine ciphertext:")
    print(translated)  # Get the encrypted text

    print("\n")
    translated2 = decrypt(Key, translated)
    print("Affine plaintext:")
    print(translated2)  # Get the decrypted text
Ejemplo n.º 14
0
    def getTranslatedMessage(self):
        if self.mode[0] == 'd':
            self.keyA, self.keyB = self.getKeyParts(self.key)
            self.checkKeys(self.keyA, self.keyB, 'decrypt')
            plaintext = ''
            modInverseOfKeyA = cryptomath.findModInverse(
                self.keyA, self.SYMBOLS)

            for symbol in self.message:
                if symbol in self.SYMBOLS_str:
                    # decrypt this symbol
                    symIndex = self.SYMBOLS_str.find(symbol)
                    plaintext += self.SYMBOLS_str[(symIndex - self.keyB) *
                                                  modInverseOfKeyA %
                                                  self.SYMBOLS]
                else:
                    plaintext += symbol  # just append this symbol undecrypted
            return plaintext
        else:
            self.keyA, self.keyB = self.getKeyParts(self.key)
            self.checkKeys(self.keyA, self.keyB, 'encrypt')
            ciphertext = ''
            for symbol in self.message:
                if symbol in self.SYMBOLS_str:
                    # encrypt this symbol
                    symIndex = self.SYMBOLS_str.find(symbol)
                    ciphertext += self.SYMBOLS_str[(symIndex * self.keyA +
                                                    self.keyB) % self.SYMBOLS]
                else:
                    ciphertext += symbol  # just append this symbol unencrypted
            return ciphertext
Ejemplo n.º 15
0
def generateKey(keySize):
	print 'generating p prime...'
	p = rabinMiller.generateLargePrime(keySize)
	print 'generating q prime...'
	q = rabinMiller.generateLargePrime(keySize)
	n = p * q

	print 'generating e that is relatively to (p-1)*(q-1)'
	while True:
		e = random.randrange(2 ** (keySize-1),2 ** keySize)
		if cryptomath.gcd(e,(p-1) * (q-1) == 1):
			print 'calcuting d that is mod inverse of e...'
			d = cryptomath.findModInverse(e,(p-1) * (q-1))
			if d != None:
				break
	
	publicKey = (n,e)
	privateKey = (n,d)

	print 'public key'
	print publicKey
	print 'private key'
	print privateKey

	return (publicKey,privateKey)
def generateKey(keySize):
    # Creates public/private keys keySize bits in size.
    p = 0
    q = 0
    # Step 1: Create two prime numbers, p and q. Calculate n = p * q:
    print('Generating p prime...')
    while p == q:
        p = primeNum.generateLargePrime(keySize)
        q = primeNum.generateLargePrime(keySize)
    n = p * q
    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1):
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        # Keep trying random numbers for e until one is valid:
        e = random.randrange(2**(keySize - 1), 2**(keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break
    # Step 3: Calculate d, the mod inverse of e:
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
    publicKey = (n, e)
    privateKey = (n, d)
    print('Public key:', publicKey)
    print('Private key:', privateKey)
    return (publicKey, privateKey)
Ejemplo n.º 17
0
def generateKey(keySize):
    p = 0
    q = 0
    # Step1: create two prime numbers, p and q. calculate n = p * q:
    print('Generating p prime...')
    while p == q:
        p = primeNum.generateLargePrime(keySize)
        q = primeNum.generateLargePrime(keySize)
    n = p * q

    # Step2: Create a number e that is relatively prime to (p-1)*(q-1):
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    x = (p - 1) * (q - 1)
    while True:
        e = random.randrange(2**(keySize - 1), 2**(keySize))
        if cryptomath.gcd(e, x) == 1:
            break

    # Step3: Calculate d, the mod inverse of e:
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, x)

    publicKey = (n, e)
    privateKey = (n, d)

    print('Public Key:\n', publicKey)
    print('Private Key:\n', privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 18
0
def keypair(size=1024):
    # Step 1: generate 2 large primes p and q, calculate n = p * q
    p, q = cryptomath.largeprime(size), cryptomath.largeprime(size)
    n = p * q
    if DEBUG_LEVEL > 0:
        print('p = %s' % p)
        print('q = %s' % q)
        print('n = %s' % n)
    # Step 2: generate a random e which is relatively prime with
    # (p - 1) * (q - 1)
    t = (p - 1) * (q - 1)
    while True:
        e = random.randrange(2 ** (size - 1), 2 ** size)
        if cryptomath.gcd(e, t) == 1:
            break
    if DEBUG_LEVEL > 0:
        print('t = %s' % t)
        print('e = %s' % e)
    # Step 3: calculate d which is the mod inverse of e
    d = cryptomath.findModInverse(e, t)
    if DEBUG_LEVEL > 0:
        print('d = %s' % d)
    pub = (n, e)
    pri = (n, d)
    if DEBUG_LEVEL > 0:
        print('Pub: ', pub)
        print('Pri: ', pri)
    # Return the key pair
    return (pub, pri)
Ejemplo n.º 19
0
def generateKey(keySize):
    # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
    print('Generating p prime...')
    p = rabinMiller.generateLargePrime(keySize)
    print('Generating q prime...')
    q = rabinMiller.generateLargePrime(keySize)
    n = p * q

    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
    print('Generating e that is relatively prime to (p-1)*(q-1)...')
    while True:
        e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # Step 3: Calculate d, the mod inverse of e.
    print('Calculating d that is mod inverse of e...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print('Public key:', publicKey)
    print('Private key:', privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 20
0
def generateKey(keySize):
    #create pasangan public key dan private key
    #Step 1,generate bilangan prima , n = p * q
    print('Create bilangan prima p...')
    p = rabinMiller.generateLargePrime(keySize)
    print('Create bilangan prima q...')
    q =  rabinMiller.generateLargePrime(keySize)
    n = p * q
    
    #Step 2,generate bilangan e (relatif prima) dengan (p-1)*(q-1)
    print('Create e(relatif prima) ...')
    while True:
        #looping terus hingga di dapat bilangan e yang valid
        e = random.randrange(2 **(keySize-1), 2 ** (keySize))
        if cryptomath.gcd(e , (p-1)*(q-1)) == 1:
            break
        
    #Step 3,hitung d,mod inverse dari e
    print('Generate d,mod inverse e...')
    d = cryptomath.findModInverse(e, (p-1)&(q-1))
    
    publicKey = (n,e)
    privateKey = (n,d)
    
    print('Public key : ',publicKey)
    print('Private key : ',privateKey)
    
    return (publicKey,privateKey)
Ejemplo n.º 21
0
def generateKey(keySize):
    # Creates a public/private key pair with keys that are keySize bits in size.
    #This function may take a while to run

    # Step 1: Create two prime numbers, p and q. Calculate n = p * q.
    print("Generating p prime...")
    p = primeNum.generateLargePrime(keySize)
    print("Generating q prime...")
    q = primeNum.generateLargePrime(keySize)
    n = p * q

    # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
    print("Generating e that is relitively prime to (p-1)*(q-1)...")
    while True:
        # keep trying random numbers for e until a valid one is found
        e = random.randrange(2**(keySize - 1), 2**(keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    # step 3: calculate d, the mod inverse of e
    print("calculating d, the mod inverse of e")
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    print("Public Key")
    print("Private Key")

    return (publicKey, privateKey)
Ejemplo n.º 22
0
def processMessage(mode, key, content):

    if mode == 'encrypt':
        keyA, keyB = getKeyParts(key)
        checkKeys(keyA, keyB, mode)
        ciphertext = ''
        for symbol in content:
            if symbol in SYMBOLS:
                #encrypt the symbol
                symIndex = SYMBOLS.find(symbol)
                ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]

        return ciphertext

    elif mode == 'decrypt':
        keyA, keyB = getKeyParts(key)
        checkKeys(keyA, keyB, mode)
        plaintext = ''
        modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))

        for symbol in content:
            if symbol in SYMBOLS:
                #decrypt the symbol
                symIndex = SYMBOLS.find(symbol)
                plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA %
                                     len(SYMBOLS)]
            else:
                plaintext += symbol

        return plaintext

    else:
        sys.exit('Invalid mode applied! Quitting...')
Ejemplo n.º 23
0
def generateRSAkey(keySize=1024):
    '''
    Known e, calculating p and q, output publicKey and privateKey in special format
    
    if want the e is unknown:

    p = generateLargePrime(keySize)
    q = generateLargePrime(keySize)
    n = p*q
    while True:
        e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
            break'''
    e = 65537
    while True:
        p = generateLargePrime(keySize)
        q = generateLargePrime(keySize)
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
            break
    n = p * q
    publicKey = str64encode(n) + b' ' + str64encode(e)
    privateKey = str64encode(n) + b' ' + str64encode(d)

    return publicKey, privateKey
Ejemplo n.º 24
0
def decrypt(message, kys, mode):
    KeyA, KeyB = getKeySections(kys)
    checkKeys(KeyA, KeyB, mode)
    inveseA = cryptomath.findModInverse(
        KeyA, ascii_length)  #finds the inverse of the key A
    plaintext = ''
    for symbol in message:
        plaintext += chr(((ord(symbol) - KeyB) * inveseA) % ascii_length)
    return plaintext
Ejemplo n.º 25
0
def decryptpesan(pesan, ka, kb):
    hasil = ''
    modInverseOfka = cryptomath.findModInverse(ka, len(simbol))
    for Simbol in pesan:
        if Simbol in simbol:
            index = simbol.find(Simbol)
            hasil += simbol[(index - kb) * modInverseOfka % len(simbol)]
        else:
            hasil += Simbol
    return hasil, modInverseOfka
Ejemplo n.º 26
0
def affineCipherDec(input, a, b):
	alphabet="abcdefghijklmnopqrstuvwxyz"
	s=""
	c=int(cryptomath.findModInverse(a, 26))
	for j in range(len(input)):
		for i in range(26):
			if input[j]==alphabet[i]:
				n=((i-b)*c)%26
				s+=alphabet[n]
	print(s)
Ejemplo n.º 27
0
 def GenerateKeyPair(self, amount_of_bits):
     q = cryptomath.choose_random_prime(amount_of_bits, 'q')
     p = cryptomath.choose_random_prime(amount_of_bits, 'p')
     n = q * p
     euler_n = (q - 1) * (p - 1)
     e = pow(2, 16) + 1
     d = cryptomath.findModInverse(e, euler_n)
     self.public_key = [e, n]
     self.private_key = d
     self.recived_keys = []
     self.q_and_p = [q, p]
def AffineDec(ciphertext, key1, key2):
    plaintext = ''
    for p in ciphertext:
        if p in LETTERS:
            planIndex = LETTERS.find(p)
            plaintext += LETTERS[(planIndex - key2) *
                                 findModInverse(key1, len(LETTERS)) %
                                 len(LETTERS)]
        else:
            plaintext += p
    return plaintext
def main():
    if len(sys.argv) != 4:
        sys.stderr.write('Usage: %s p q e\n' % sys.argv[0])
        sys.exit(1)

    p, q, e = [long(a, 16) for a in sys.argv[1:]]

    conf = get_asn1conf(build_key(p, q, e))

    sys.stderr.write(helptext)
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
    print conf
Ejemplo n.º 30
0
def decryptMessage(key, message):
    keyA, keyB = getKeyParts(key)
    checkKeys(keyA,keyB,'decrypt')
    plaintext = ''
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))
    for symbol in message:
        if symbol in SYMBOLS:
            symIndex = SYMBOLS.find(symbol)
            plaintext += SYMBOLS[(symIndex - keyA) * modInverseOfKeyA  % len(SYMBOLS)]
        else:
            plaintext += symbol
    return plaintext
Ejemplo n.º 31
0
def cipher(text, a, b, mode):
    if cryptomath.gcd(a, alph_len) != 1:
        return None
    text = [tuple(text[i:i + 2]) for i in range(0, len(text), 2)]
    text = [letters_map[i] * alph_len + letters_map[j] for i, j in text]
    text = [(a * X + b) % alph_len**2
            for X in text] if mode == "encrypt" else [
                cryptomath.findModInverse(a, alph_len**2) * (X - b) %
                alph_len**2 for X in text
            ]
    text = ''.join(list(map(lambda x: bigrams_map[x], text)))
    return text
Ejemplo n.º 32
0
def decryptMessage(keyA, keyB, Message):
    checkKeys(keyA, keyB, 'decrypt')
    plaintext = ''
    modInverse = cryptomath.findModInverse(keyA, 26)

    for symbol in Message:
        if symbol in SYMBOLS:
            symIndex = SYMBOLS.find(symbol)
            plaintext += SYMBOLS[(symIndex - keyB) * modInverse % 26]
        else:
            plaintext += symbol
    return plaintext
Ejemplo n.º 33
0
def affine_decrypt(text, key):
    keyA, keyB = getKey(key)
    decrypted_text = ""
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))

    for symbol in text:
        if symbol in SYMBOLS:
            symIndex = SYMBOLS.find(symbol)
            decrypted_text += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
        else:
            decrypted_text += symbol
    return decrypted_text
Ejemplo n.º 34
0
	def decode(self,sentence,key):
		""" CT to OT """
		keyA, keyB = key[0],key[1]
		translated=''
		modInverseOfKeyA = cryptomath.findModInverse(keyA, MAX_KEY_SIZE)

		if not modInverseOfKeyA is None:
			#print("inverse ok")
			for c in sentence:
				i = (cipher.ctoi[c] - keyB) * modInverseOfKeyA %MAX_KEY_SIZE
				translated+=cipher.itoc[i]
		#print(translated)
		return translated
Ejemplo n.º 35
0
def decryptMessage(key, message):
    keyA, keyB = getKeyParts(key)
    checkKeys(keyA, keyB, 'decrypt')
    keyA, keyB = getKeyParts(key)
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))
    plaintext = ''
    for symbol in message:
        if symbol in SYMBOLS:
            # decrypt this symbol
            symIndex = SYMBOLS.find(symbol)
            plaintext += SYMBOLS[( (symIndex - keyB) % len(SYMBOLS)) * modInverseOfKeyA % len(SYMBOLS)]
        else:
            plaintext += symbol # just append this symbol undecrypted
    return plaintext
Ejemplo n.º 36
0
def decryptMessage(key, message):
    keyA, keyB = getKeyParts(key)
    checkKeys(keyA, keyB, 'decrypt')
    plaintext = ''
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))

    for symbol in message:
        # Decrypt the symbol:
        symbolIndex = SYMBOLS.find(symbol)
        plaintext += SYMBOLS[(symbolIndex - keyB) * modInverseOfKeyA %
                             len(SYMBOLS)]
    else:
        plaintext += symbol  # Append the symbol without decrypting.
    return plaintext
Ejemplo n.º 37
0
def decryptMessage(keyA, keyB, message):
    if cryptomath.gcd(keyA, len(LETTERS)) != 1:
        sys.exit('The key (%s) and the size of the alphabet (%s) are not relatively prime. Choose a different key.' % (keyA, len(LETTERS)))

    plaintext = ''
    modInverseOfKeyA = cryptomath.findModInverse(keyA, len(LETTERS))

    for symbol in message:
        if symbol in LETTERS:
            # decrypt this symbol
            symIndex = LETTERS.find(symbol)
            plaintext += LETTERS[(symIndex - keyB) * modInverseOfKeyA % len(LETTERS)]
        else:
            # just append this symbol unencrypted
            plaintext += symbol
    return plaintext
Ejemplo n.º 38
0
def generate_key(key_size):
    print('Генерация числа p...')
    p = rabinMiller.generateLargePrime(key_size)
    print('Генерация числа q...')
    q = rabinMiller.generateLargePrime(key_size)
    n = p * q

    print('Генерация числа e...')
    while True:
        e = random.randrange(2 ** (key_size - 1), 2 ** key_size)
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break

    print('Рассчет d...')
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    public_key = (n, e)
    private_key = (n, d)

    print('Открытый ключ:', public_key)
    print('Закрытый ключ:', private_key)

    return public_key, private_key
Ejemplo n.º 39
0
def generateKey(keySize=DEFAULT_KEY_SIZE):
    # Creates a public/private key pair with keys that are keySize bits in
    # size. This function may take a while to run.

    # Step 1: Create two prime numbers, p and q.
    if not SILENT_MODE:
        print("Generating p prime...")
    p = rabinMiller.generateLargePrime(keySize)
    if not SILENT_MODE:
        print("Generating q prime...")
    q = rabinMiller.generateLargePrime(keySize)

    # Step 2: Create a number e.
    if not SILENT_MODE:
        print("Generating e that is relatively prime to (p-1)*(q-1)...")
    while True:
        # Come up with an e that is relatively prime to (p-1)*(q-1)
        e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
        if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
            break
    n = p * q

    # Step 3: Get the mod inverse of e.
    if not SILENT_MODE:
        print("Calculating d that is mod inverse of e...")
    d = cryptomath.findModInverse(e, (p - 1) * (q - 1))

    publicKey = (n, e)
    privateKey = (n, d)

    if not SILENT_MODE:
        print("Public key:")
        print(publicKey)
        print("Private key:")
        print(privateKey)

    return (publicKey, privateKey)
Ejemplo n.º 40
0
Archivo: dsa.py Proyecto: pb593/cam
     
     if(verify(h, r, s)):
         print("Signature verified")
     else:
         print("Signature verification failed")
     print("-------------------------------------------------------------")
         
         
 print("\nPart E\n")
 h1 = Sigs[0][0]
 h2 = Sigs[1][0]
 s1 = Sigs[0][2]
 s2 = Sigs[1][2]
 r = Sigs[0][1]
 
 invDeltaS = findModInverse(s1-s2, Q)
 k = (h1 - h2) * invDeltaS % Q
 kInv = findModInverse(k, Q)
 
 rInv = findModInverse(r, Q)
 # secret key
 x = (k * s1 - h1) * rInv % Q
 
 h3 = int(sha1("Wednesday"), 16)
 print(h3)
 sig = ( kInv * (h3 + x * r) ) % Q
 
 if(verify(h3, r, sig)):
     print("Fake signature verified!")
 else:
     print("Fake signature failed to verify. Try again...")
Ejemplo n.º 41
0
Archivo: dsa.py Proyecto: pb593/cam
def verify(h, r, s):   
    sInv = findModInverse(s, Q)
    vrf = F(pow(G, h*sInv, P) * pow(Y, r*sInv, P) % P)
    
    return (r == vrf)
Ejemplo n.º 42
0
import cryptomath
print (cryptomath.gcd(24,32))
print (cryptomath.gcd(37,41))
print (cryptomath.findModInverse(7,26))
print (cryptomath.findModInverse(8953851,26))