Esempio n. 1
0
def hackAffine(message):
    print('Hacking...')

    # Python programs can be stopped at any time by pressing Ctrl-C (on
    # Windows) or Ctrl-D (on macOS 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(SYMBOLS)**2):
        keyA = getKeyParts(key)[0]
        if gcd(keyA, len(SYMBOLS)) != 1:
            continue

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

        if 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
Esempio n. 2
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 = generateLargePrime(keySize)
        q = 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 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 = findModInverse(e, (p - 1) * (q - 1))

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

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

    return publicKey, privateKey
def checkKeys(keyA, keyB, mode):
    if keyA == 1 and mode == 'encrypt':
        sys.exit('Cipher is weak if key A is 1. Choose a different key.')
    if keyB == 0 and mode == 'encrypt':
        sys.exit('Cipher is weak if key B is 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 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)))
Esempio n. 4
0
# Chapter 13 Practice Questions

# 1. What do the following expressions evaluate to?
print(17 % 1000)
print(5 % 5)

# 2. What is the GCD of 10 and 15?
# Don't do this - imports should be at the top of the file
from books.CrackingCodesWithPython.Chapter13.cryptomath import gcd
print(gcd(10, 15))

# 3. What does spam contain after executing spam, eggs = 'hello', 'world'?
spam, eggs = 'hello', 'world'
print(spam)

# 4. The GCD of 17 and 31 is 1. Are 17 and 31 relatively prime?
if not gcd(17, 31) == 1:
    print("No")
else:
    print("Yes")

# 5. Why aren't 6 and 8 relatively prime?
print(gcd(6, 8))

# 6. What is the formula for the modular inverse of A mod C?
# Hint: check page 183
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
print(
    "The modular inverse of %s mod %s is number %s such that (%s * %s) mod %s == %s"
    % (SYMBOLS[0], SYMBOLS[2], SYMBOLS[34], SYMBOLS[0], SYMBOLS[34],
       SYMBOLS[2], SYMBOLS[-14]))
def getRandomKey():
    while True:
        keyA = random.randint(2, len(SYMBOLS))
        keyB = random.randint(2, len(SYMBOLS))
        if gcd(keyA, len(SYMBOLS)) == 1:
            return keyA * len(SYMBOLS) + keyB
# This program proves that the keyspace of the affine cipher is limited
# to less than len(SYMBOLS) ^ 2.

from books.CrackingCodesWithPython.Chapter14.affineCipher import encryptMessage, SYMBOLS
from books.CrackingCodesWithPython.Chapter13.cryptomath import gcd

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

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