Example #1
0
 def test_encrypt_decrypt_01(self):
     p, q, e = 11, 29, 3
     epn = euler_phi(p * q)
     assert epn == (11 - 1) * (29 - 1)
     assert xgcd(epn, 3)[0] == 1
     pk, sk = rsa.generate_keys_from_pqe(p, q, e)
     M = 100
     assert rsa.decrypt(rsa.encrypt(M, pk), sk) == M
     assert rsa.encrypt(rsa.decrypt(M, sk), pk) == M
Example #2
0
 def test_encrypt_decrypt_02(self):
     nums = [
         2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
         67, 71, 73, 79, 83, 89, 97
     ]
     for p in nums:
         for q in nums:
             if p != q:
                 eu_phi_n = (p - 1) * (q - 1)
                 if eu_phi_n > 20:
                     e = rsa.choose_e(eu_phi_n)
                     n = p * q
                     M = random.randint(0, n - 1)
                     pk, sk = rsa.generate_keys_from_pqe(p, q, e)
                     assert rsa.decrypt(rsa.encrypt(M, pk), sk) == M
                     assert rsa.encrypt(rsa.decrypt(M, sk), pk) == M
Example #3
0
def render_encrypt_text(text, params):
    params = tuple(int(param) for param in params)

    p, q, e = params
    n, phi = rsa._get_n(p, q), rsa._get_phi(p, q)
    encrypted = rsa.encrypt(text, (n, phi, e))
    decrypted = rsa.decrypt(encrypted, n, rsa._get_private_key(phi, e))

    write_to_file(decrypted, 'output.txt')

    template_params = get_template_params(text, encrypted, decrypted, p, q, e)
    return render_template('rsa.html', **template_params)
Example #4
0
def main():

    with open("files/initial.txt", "r") as file:

        data = file.read()

        n, e, d = rsa.make_key_pair(2048)

        print(n, ' ', e, ' ', d)

        encrypted_data = rsa.encrypt(data, e, n)
        write_to_file("files/encrypted.txt", encrypted_data)
        print("\nencrypted data:\n{}".format(encrypted_data))

        decrypted_data = rsa.decrypt(encrypted_data, d, n)
        write_to_file("files/decrypted.txt", decrypted_data)
        print("\ndecrypted data:\n{}".format(decrypted_data))
Example #5
0
def api_auth(api_base_url, api_id, api_user_key):
    # This should return an authorized token so we can do other, more exciting things
    # Lets show what we're doing.
    print('geting URL: {}auth/{}'.format(api_base_url, api_id))

    # Actual request goes here.
    r = requests.get('{}auth/{}'.format(api_base_url, api_id))
    data = r.json()
    api_error_handling(r.status_code)

    api_token_encrypted = data['data']['token']
    api_token_encrypted_expires = data['data']['expires']
    print('The API Token expires: {}'.format(api_token_encrypted_expires))
    #print(api_token_encrypted)

    api_bearer_token = rsa.decrypt(base64.b64decode(api_token_encrypted),
                                   api_user_key)
    api_bearer_token = api_bearer_token.decode("utf-8")
    return (api_bearer_token)
Example #6
0
def main():
    """Funcion principal del programa."""
    while True:
        print_menu()
        op = int(input("\nSeleccione una opcion: "))

        # Cifrado.
        if op == 1:
            # Permitimos al usuario seleccionar el archivo.
            src = select_file()

            # Leemos el archivo.
            with open(src) as f:
                msg = f.read()

            # Generamos dos primos aleatorios distintos de entre 50 y 60 dígitos.
            p = rsa.generate_prime_number(50, 60)
            q = p
            while q == p:
                q = rsa.generate_prime_number(50, 60)

            # Obtenemos las claves pública y privada.
            public_key, private_key = rsa.generate_keys(p, q)

            # Cadena con el texto cifrado.
            ciphertext = ' '.join(
                [str(c) for c in rsa.encrypt(public_key, msg)])

            print(
                f"Su llave pública es: {public_key}\nSu llave privada es: {private_key}"
            )

            # Escribimos el texto cifrado en un archivo salida.txt
            # Se crea en el directorio actual.
            with open("salida.txt", "w+") as out:
                out.write(ciphertext)
                print(f"\nEl archivo salida.txt se ha creado en {os.getcwd()}")

            input("\nPresione <ENTER> para continuar... ")
            clean_console()

        # Descifrado.
        elif op == 2:
            # Permitimos al usuario seleccionar el archivo.
            src = select_file()

            # Leemos el archivo con el texto encriptado.
            with open(src) as f:
                text = f.read()

            # Obtenemos la llave pública.
            print(">> Ingrese la llave pública [n, e] (ejemplo: 567 785): ")
            n, e = map(int, input().split())
            public_key = (n, e)

            # Obtenemos la llave privada.
            print("\n>> Ingrese la llave privada: ")
            private_key = int(input())

            keys = (public_key, private_key)

            # Lista de enteros asociados al texto cifrado.
            ciphertext = [int(c) for c in text.split()]

            # Obtenemos el mensaje descifrado como una cadena.
            msg = rsa.decrypt(ciphertext, keys)

            print(f"\nSu texto descifrado es:\n{msg}")

            input("\nPresione <ENTER> para continuar... ")
            clean_console()

        # Salir del programa.
        elif op == 3:
            clean_console()
            print("Hasta luego! Gracias por utilizar el programa :D")
            break

        # Opción inválida.
        else:
            print("Opción no válida.")
            input("\nPresione <ENTER> para continuar... ")
            clean_console()