コード例 #1
0
ファイル: RSA1.py プロジェクト: iprabhat29/Security_IOT
def keygen(p, q):
    n = p * q
    phi = (p - 1) * (q - 1)
    e = random.randrange(1, phi)
    g = cryptomath.gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = cryptomath.gcd(e, phi)
    d = cryptomath.multiplicative_inverse(e, phi)
    return ((e, n), (d, n))
コード例 #2
0
def affine_decode(text: str, alpha: int, beta: int) -> str:
    """
    Decodes a text encrypted with an affine cypher with the known alpha and 
    beta parameters.  Affine cyphers are of the form ax + b (mod26) = E, where 
    'a' (alpha) is a number gcd(a,26) = 1; 'b' (beta) is any positive or 
    negative integer; and E is the position of the new letter in the alphabet.

    Args:
        text (str): The encrypted message to decrypt.
        alpha (int): The multiplied factor of the affine encryption algorithm 
        (a, where ax + b (mod26) = E).
        beta (int): The shifted amount of the affine encryption algorithm (b, 
        where ax + b (mod26) = E).
 
    Raises:
        AffineAlphaException or EmptyTextException

    Returns:
        str: The decrypted message.
    """
    if cryptomath.gcd(alpha, 26) != 1:
        raise AffineAlphaException
    decodeArray = list(__prep_text(text))
    if len(decodeArray) == 0:
        raise EmptyTextException
    plainText = ""
    for symbol in decodeArray:
        x = (_ALPHABET.index(symbol) - beta) * cryptomath.find_mod_inverse(
            alpha, 26)
        plainText = plainText + _ALPHABET[x % 26]
    return plainText
コード例 #3
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
コード例 #4
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)
コード例 #5
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)
コード例 #6
0
def hackAffine(message):
    print('Hacking...')

    print('Press Ctrl-C or Ctrl-D to quit at any time.')

    # brute-fore by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            # Check with the user if the decrypt key was correct.
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done, or Enter to continue:')
            response = input('> ')

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #7
0
def random_key():
    while (True):
        key_a = random.randint(2, len(SYMBOLS))
        key_b = random.randint(2, len(SYMBOLS))

        if cryptomath.gcd(key_a, len(SYMBOLS)) == 1:
            return key_a * len(SYMBOLS) + key_b\
コード例 #8
0
ファイル: makeRsaKeys.py プロジェクト: Aaron-Cai/PythonCipher
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)
コード例 #9
0
def hackAffine(message):
    print('Hacking...')

    print('(Press Ctrl-C or Ctrl-D to quit at any time.)')

    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done, or just press Enter to continue hacking:')
            response = input('> ')
            if response.strip().upper().startswith('D'):
               return decryptedText
            return None
コード例 #10
0
def affine_encode(text: str, alpha: int, beta: int) -> str:
    """
    Encodes a provided text using an affine cipher of the form ax + b (mod 26) 
    = E; where a is parameter alpha and b is parameter beta.

    Args:
        text (str): The text to encrypt.
        alpha (int): The multiplied factor of the affine encryption algorithm 
        (a, where ax + b (mod26) = E).
        beta (int): The shifted amount of the affine encryption algorithm (b, 
        where ax + b (mod26) = E).

    Raises:
        AffineAlphaException
        EmptyTextException

    Returns:
        str: The encrypted message.
    """
    if cryptomath.gcd(alpha, 26) != 1:
        raise AffineAlphaException
    encodeArray = list(__prep_text(text))
    if len(encodeArray) == 0:
        raise EmptyTextException
    cipherText = ""
    for symbol in encodeArray:
        encodeIndex = (alpha * _ALPHABET.index(symbol) + beta) % 26
        cipherText = cipherText + _ALPHABET[encodeIndex]
    return cipherText
コード例 #11
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)
コード例 #12
0
def hackAffine(message):
    print('Hacking...')

    # Python programs can be stopped at any time by pressing Ctrl-C (on
    # Windows) or Ctrl-D (on Mac and Linux)
    print('(Press Ctrl-C or Ctrl-D to quit at any time.)')

    # brute force by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            # Check with the user if the decrypted key has been found.
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done, or just press Enter to continue hacking:')
            response = input('> ')

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #13
0
def hackAffine(message):
    global SILENT_MODE
# ketikkan code dari slide 8 - 11 atau menggunakan versi Anda.
    print("Hacking...")
    print("Ctrl-C or Ctrl-D to quit at any time")

    for key in range(len(affineCipher.SYMBOLS)**2):
        keyA=affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS))!=1:
            continue

        decryptedtext=affineCipher.decryptMessage(key,message)
        if not SILENT_MODE:
            print(f"Tried key {key}... ({decryptedtext[:40]})")

        if detectEnglish.isEnglish(decryptedtext):
            print("Possible encryption hack: ")
            print(f"Key: {key}")
            print(f"Decrypted message: {decryptedtext[:200]}")
            print("Enter D for done, or just press Enter to continue hacking: ")
            response=input("> ")
            if response.upper()=="D":
                return decryptedtext
        
    return None
コード例 #14
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
コード例 #15
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)
コード例 #16
0
ファイル: rsa.py プロジェクト: alcdsb/SSL-Handshake-simulator
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
コード例 #17
0
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)
コード例 #18
0
ファイル: rsa.py プロジェクト: ychen810811/crypto_python
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)
コード例 #19
0
def hackAffine(message):
    print('Hacking...')

    # To stop:
    # Ctrl-C
    print('(Ctrl-C to quit)')

    # brute-force by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            # Check w/user to see if key found
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done, or just press enter to continue')
            response = input('> ')

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #20
0
def random_key():
    while True:
        keyA = random.randint(2, len(SYMBOLS))
        keyB = random.randint(2, len(SYMBOLS))

        if cryptomath.gcd(keyA, len(SYMBOLS)) == 1:
            return keyA * len(SYMBOLS) + keyB
コード例 #21
0
def get_random_key():
    while True:
        key_A = random.randint(2, len(SYMBOLS))
        key_B = random.randint(2, len(SYMBOLS))

        if cryptomath.gcd(key_A, len(SYMBOLS)) == 1:
            return (key_A * len(SYMBOLS)) + key_B
コード例 #22
0
def hackAffine(message):
    print('Hacking...')

    # Python programs can be stopped at any time by pressing Ctrl-C (on
    # Windows) or Ctrl-D (on Mac and Linux)
    print('(Press Ctrl-C or Ctrl-D to quit at any time.)')

    # brute-force by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            # Check with the user if the decrypted key has been found.
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done, or just press Enter to continue hacking:')
            response = input('> ')

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #23
0
def hackAffine(message):
    print "\nAttempting to decode message...\n"

    # Brute-force by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS)**2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print 'Tried Key %s... (%s)' % (key, decryptedText[:40])

        startTime = time.time()
        isEnglish = detectEnglish.isEnglish(decryptedText)
        totalTime = round(time.time() - startTime, 2)
        print 'English detection time: %s seconds' % totalTime

        if isEnglish:
            print "\nPossible decrypted message:"
            print "   Key %s: %s" % (key, decryptedText[:100])
            response = raw_input(
                "\nEnter D if done, or any other key to continue the attack: ")

            if response.strip().upper().startswith('D'):
                return decryptedText

    return None
コード例 #24
0
def hackAffine(message):
    print('Hacking...')
    print('(Press Ctrl-C or Ctrl-D to quit at any time.)')

    #brute-force by looping through each key
    for key in range(len(affineCipher.SYMBOLS)**2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)):
            continue

        decryptedText = affineCipher.decryptMessage(key, message)
        if not SILENT_MODE:
            print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

        if detectEnglish.isEnglish(decryptedText):
            #Check with the user f the decrypted key has been found
            print()
            print('Possible encryption hack:')
            print('Key: %s' % (key))
            print('Decrypted message: ' + decryptedText[:200])
            print()
            print('Enter D for done,or just press Enter to Continue Hacking')
            response = input('>')
            if response.strip().upper().startswith('D'):
                return decryptedText
            return None
            #if affineHacker.py is run as module
            if __name__ == '__main__':
                main()
コード例 #25
0
def hackAffine(message):
    print("Hacking .....")

    for key in range(
            0, E_15_Affine_Cipher.ascii_length**2
    ):  # ** represents to the power of, its to the power of 2, as same as multiplying by two, as A and B have the same range
        keyA = E_15_Affine_Cipher.getKeySections(
            key
        )[0]  # 0, only takes the first element, as we just need to check A is valid to speed up the programme
        #        print   (E_15_Affine_Cipher.getKeySections(key))
        if ((cryptomath.gcd(keyA, E_15_Affine_Cipher.ascii_length)) != 1):
            continue  # if the key is not coprime then continue back at the for loop, i.e. break from currnet iteration but continue onto the next


#        print( E_15_Affine_Cipher.decrypt(message, key, False)) #False sent to determine decryption mode

        plaintext = E_15_Affine_Cipher.decrypt(
            message, key, False)  #False sent to determine decryption mode

        if (E_12_English_detect.isEnglish(plaintext)):
            print("tried key %s giving plain text : %s " % (key, plaintext))
            happy = raw_input(
                'English detected, enter D for done or N to continue hacking')

            if (happy.strip().upper().startswith('D')):
                return plaintext

    return None
コード例 #26
0
def hackAffine(message):
    print('Hacking...')
    print('(Press Ctrl-C or Ctrl-D to stop at any time)')

    for key in range(len(affine_cipher.SYMBOLS) ** 2):
        keyA = affine_cipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affine_cipher.SYMBOLS)) != 1:
            continue

        text = affine_cipher.decryptMessage(key, message)
        if SILENT_MODE is False:
            print()
            print('+: key:\t%s' % (key))
            print('+: msg:\t%s' % (text[200:]))
            print()

        if detectEnglish.isEnglish(text) is True:
            print()
            print('+: key:\t%s' % (key))
            print('+: msg:\t%s' % (text[200:]))
            print()
            print('Enter D for done, or just press Enter to continue')
            prompt = input('> ')
            if prompt.upper().startswith('D') is True:
                return text
    return None
コード例 #27
0
def getRandomKey():
    keyA = random.randint(2, len(SYMBOLS))
    keyB = random.randint(2, len(SYMBOLS))
    if cryptomath.gcd(keyA, len(SYMBOLS)) == 1:
        return keyA * len(SYMBOLS) + keyB

    return getRandomKey()
コード例 #28
0
    def hackAffine(message):
        print('Hacking...')

        print('(Press Ctrl-C or Ctrl-D to quit at any time.)')

        for key in range(len(SYMBOLS)**2):
            keyA = getKeyParts(key)[0]
            if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
                continue

            decryptedText = decryptMessage(key, message)
            if not SILENT_MODE:
                print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

            if detectEnglish.isEnglish(decryptedText):

                print()
                print('Possible encryption hack:')
                print('Key: %s' % (key))
                print('Decrypted message: ' + decryptedText[:200])
                print()
                print('Enter D if done, anything else to continue hacking:')
                response = input('> ')

                if response.strip().upper().startswith('D'):
                    return decryptedText
        return None
コード例 #29
0
def prueba(msg):
    l = list()
    for keyA in range(2, 80):
        key = keyA * len(affineCipher.SYMBOLS) + 1
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) == 1:
            l.append((key, affineCipher.encryptMessage(key, msg)))
    return random.choice(l)
コード例 #30
0
 def getRandomKey(self):
     while True:
         self.keyA = random.randint(2, self.SYMBOLS)
         self.keyB = random.randint(2, self.SYMBOLS)
         if cryptomath.gcd(self.keyA, self.SYMBOLS) == 1:
             self.key = self.keyA * self.SYMBOLS + self.keyB
             return self.keyA * self.SYMBOLS + self.keyB
コード例 #31
0
def getRandomKey():
    while True:
        keyA = random.randint(2, len(SYMBOLS))
        keyB = random.randint(2, len(SYMBOLS))
        # check co-prime
        if cryptomath.gcd(keyA, len(SYMBOLS)) == 1:
            return keyA * len(SYMBOLS) + keyB
コード例 #32
0
def hack_affine(message):
    for key in range(len(affine_cipher.SYMBOLS) ** 2):
        key_a = affine_cipher.get_key_parts(key)[0]
        if cryptomath.gcd(key_a, len(affine_cipher.SYMBOLS)) != 1:
            continue

        text_decrypted = affine_cipher.decrypt_message(key, message)
        OUTPUT_FILE_OBJ.write("Tried Key %s... (%s)\n" % (key, text_decrypted[:40]))
        if not SILENT_MODE:
            print("Tried Key %s: %s..." % (key, text_decrypted[:100]))

        if detect_english.is_english(text_decrypted):
            global TIME_CHECKPOINT = time.time() - TIME_CHECKPOINT
            global TIME_ELAPSED += TIME_CHECKPOINT
            print("\nPossible encryption hack:")
            print("Key: %s" % (key))
            print("Decrypted message: " + text_decrypted[:200])
            print("\nEnter D for done, or just press Enter to continue hacking:")

            response = input("> ")
            if response.strip().upper().startswith("D"):
                OUTPUT_FILE_OBJ.write("\n\nKey used: %s\nDecrypted message: %s" % (key, text_decrypted))
                OUTPUT_FILE_OBJ.write("\nTotal time elapsed: %s" % (format(TIME_ELAPSED, ".5f")))
                OUTPUT_FILE_OBJ.close()
                return text_decrypted

    TIME_ELAPSED = time.time() - TIME_START
    OUTPUT_FILE_OBJ.write("\nDecryption failed.")
    OUTPUT_FILE_OBJ.write("\nTotal time elapsed: %s" % (format(TIME_ELAPSED, ".5f")))
    OUTPUT_FILE_OBJ.close()
    return None
コード例 #33
0
def break_affine():
    keys = []
    for i in rus_and_encrypted:
        Y1 = bigrams_map[i[2]]
        Y2 = bigrams_map[i[3]]
        X1 = bigrams_map[i[0]]
        X2 = bigrams_map[i[1]]
        X1_X2 = X1 - X2
        Y1_Y2 = Y1 - Y2
        if X1_X2 < 0:
            X1_X2 += alph_len**2
        if Y1_Y2 < 0:
            Y1_Y2 += alph_len**2
        a_keys = cryptomath.linear_equation(X1_X2, Y1_Y2, alph_len**2)

        if not isinstance(a_keys, list):
            a_keys = [a_keys]
        if None not in a_keys:
            for a in a_keys:
                if cryptomath.gcd(a, alph_len**2) != 1:
                    continue

                b = (Y1 - a * X1) % alph_len**2
                if b < 0:
                    b += alph_len**2
                if (a, b) in keys:
                    continue

                keys.append((a, b))

    for key in keys:
        candidate = affine.cipher(text, key[0], key[1], 'decrypt')
        if icx(candidate) >= 0.050:
            print(key)
            print(candidate)
コード例 #34
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)
コード例 #35
0
def hack(message):
    print('hacking...')

    # range of possible keys for affine cypher is len(set size) ^ 2
    for key in range(len(affineCypher.SYMBOLS) ** 2):
        keyA = affineCypher.getKeyParts(key)[0]
        # keyA must satisfy gcd(keyA, len(set size)) == 1
        if cryptomath.gcd(keyA, len(affineCypher.SYMBOLS)) != 1:
            continue # skip current key if gcd isnt 1

        decryptedText = affineCypher.decrypt(key, message)
        if not SILENT_MODE:
            print('tried key: %s' % key)
            print('text: %s...' % decryptedText)

        if DetectEnglish.isEnglish(decryptedText):
            print('Found possible hack')
            print('Key: %s' % key)
            print('Message: %s' % decryptedText)
            print()
            print('Enter D for done, or just press Enter to continue hacking:')            
            response = input('> ')

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #36
0
ファイル: affine.py プロジェクト: jancybsec/ciphersleuth
	def getRandomKey(self):
		while True:
			self.keyA = random.randint(2, self.SYMBOLS)
			self.keyB = random.randint(2, self.SYMBOLS)
			if cryptomath.gcd(self.keyA, self.SYMBOLS) == 1:
				self.key=self.keyA * self.SYMBOLS + self.keyB
				return self.keyA * self.SYMBOLS + self.keyB
コード例 #37
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)
コード例 #38
0
ファイル: inventRsa.py プロジェクト: anggaeka333/rsaCipher
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)
コード例 #39
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)
コード例 #40
0
def checkKeys(keyA, keyB, mode):
    if keyA == 1 and mode == 'encrypt':
        sys.exit('The affine cipher becomes incredibly weak when keyA is 1.  Choose a different key.')
    if keyB == 0 and mode == 'encrypt':
        sys.exit('The affine cipher becomes incredibly weak when keyB is 0.  Choose a different key.')
    if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
        sys.exit('KeyA must be > 0 and 0 < keyB < %s.' % (len(SYMBOLS) - 1))
    if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
        sys.exit('KeyA (%s) and the symbol set size (%s) must be relatively prime.  Choose a different key.' % (keyA, len(SYMBOLS)))
コード例 #41
0
def checkKeys(keyA,keyB,mode):
    if keyA == 1 and mode == 'encrypt':
        sys.exit('The affine cipher becomes incredibly weak when key A is set to 1. Choose a different key.')
    if keyB == 0 and mode == 'encrypt':
        sys.exit('The affine cipher becomes incredibly weak when key B is set to 0. Choose a different key.')
    if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
        sys.exit('Key A must be greater than 0 and Key B must be between 0 and %s.' % len(SYMBOLS)-1)
    if cryptomath.gcd(keyA,len(SYMBOLS)) != 1:
        sys.exit('Key A (%s) and the symbol set size (%s) are not relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))
コード例 #42
0
ファイル: uniciph.py プロジェクト: theRoda/uniciph
def testAffine(self):
	self = self.strip()
	for key in range(len(affineCipher.SYMBOLS) ** 2):
		keyA = affineCipher.getKeyParts(key)[0]
		if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
			continue

		decryptedText = affineCipher.decryptMessage(key, self)
		print('Tried Key %s : (%s)' % (key, decryptedText[:40]))
		checkMatch(decryptedText, key, 'Affine')
コード例 #43
0
ファイル: affine.py プロジェクト: jancybsec/ciphersleuth
	def checkKeys(self, keyA, keyB, mode):
		self.okay = True
		if self.keyA == 1 and self.mode == 'e':
			self.okay = False
			return 'The affine cipher becomes incredibly weak when key A is set to 1. Choose a different key.'
		if self.keyB == 0 and self.mode == 'e':
			self.okay = False
			return 'The affine cipher becomes incredibly weak when key B is set to 0. Choose a different key.'
		if self.keyA < 0 or self.keyB < 0 or self.keyB > (self.SYMBOLS - 1):
			self.okay = False
			return 'Key A must be greater than 0 and Key B must be between 0 and %s.' % (self.SYMBOLS - 1)
		if cryptomath.gcd(self.keyA, self.SYMBOLS) != 1:
			self.okay = False
			return 'Key A (%s) and the symbol set size (%s) are not relatively prime. Choose a different key.' % (self.keyA, self.SYMBOLS)
コード例 #44
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
コード例 #45
0
ファイル: affine3.py プロジェクト: YarlinWare/metadecryptor
def hackAffine(message):
    # Python programs can be stopped at any time by pressing Ctrl-C (on
    # Windows) or Ctrl-D (on Mac and Linux)
    # brute-force by looping through every possible key
    for key in range(len(affineCipher.SYMBOLS) ** 2):
        keyA = affineCipher.getKeyParts(key)[0]
        if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
            continue

        decryptedText = affineCipher.decryptMessage(key, message)

        if detectEnglish.isEnglish(decryptedText):
            # Check with the user if the decrypted key has been found.
            print('\nKey: %s' % (key))
            response = 'D'

            if response.strip().upper().startswith('D'):
                return decryptedText
    return None
コード例 #46
0
def encryptMessage(keyA, keyB, message):
    # key strength and validity checks
    if keyA == 1:
        sys.exit('The affine cipher becomes incredibly weak when keyA is set to 1. Choose a different key.')
    if keyB == 0:
        sys.exit('The affine cipher becomes incredibly weak when keyB is set to 0. Choose a different key.')

    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)))

    ciphertext = ''
    for symbol in message:
        if symbol in LETTERS:
            # encrypt this symbol
            symIndex = LETTERS.find(symbol)
            ciphertext += LETTERS[(symIndex * keyA + keyB) % len(LETTERS)]
        else:
            # just append this symbol unencrypted
            ciphertext += symbol
    return ciphertext
コード例 #47
0
ファイル: Main.py プロジェクト: brandonskerritt51/Ciphey
def hackAffine(message):
	# Comment the code
	# and put this into its own module??
	for key in range(len(affineCipher.SYMBOLS) ** 2):
		keyA = affineCipher.getKeyParts(key)[0]
		if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
			continue

		decryptedText = affineCipher.decryptMessage(key, message)

		print('Tried Key %s... (%s)' % (key, decryptedText[:40]))

		if detectEnglish.isEnglish(decryptedText):
			# Check with the user if the decrypted key has been found.
			CipherName = ("Affine cipher with key of {}".format(key))

			englishMSG = ("key {}: {}".format(key, decryptedText))

			EnglishDetected(CipherName, EnglishMSG, File)

	return None
コード例 #48
0
ファイル: rsa_generate_keys.py プロジェクト: CDMMKY/git-repo
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
コード例 #49
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)
コード例 #50
0
ファイル: testScript.py プロジェクト: mgsullivan/scripts
import cryptomath
print (cryptomath.gcd(24,32))
print (cryptomath.gcd(37,41))
print (cryptomath.findModInverse(7,26))
print (cryptomath.findModInverse(8953851,26))
コード例 #51
0
def getRandomKey():
    while True:
        keyA = random.randint(2,len(SYMBOLS))
        keyB = random.randint(2,len(SYMBOLS))
        if cryptomath.gcd(keyA,len(SYMBOLS)) == 1:
            return keyA * len(SYMBOLS) + keyB
コード例 #52
0
# This program proves that the keyspace of the affine cipher is limited
# to len(SYMBOLS) ^ 2.

import affineCipher
import cryptomath
message = 'Make things as simple as possible, but not simpler.'
for keyA in range(2, 100):
    key = keyA * len(affineCipher.SYMBOLS) + 1

    if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) == 1:
        print(keyA, affineCipher.encryptMessage(key, message))