""" Class defintion for elliptic curve factorization """

sage_present = True
try:
    from sage.all_cmdline import *
except ImportError:
    sage_present = False

from RSAExploits.util import compute_priv_rsa_exp
from RSAExploits.exploits.exploit import Exploit

class Ecm(Exploit):
    """ Class providing a run interface to sage's ecm.factor function"""
    
    def run(self, rsadata_list, info_dict):
        """ Factors moduli using elliptic curve factorization 

            This is currently the third fastest known general purpose
            factoring algorithm. However, its runtime is dominated by
            the size of the smallest factor. Therefore it is particularly
            well suited to finding the factors of moduli that contain a small
            prime factor 

            Args:
                rsadata_list: A list of RSA_Data objects with moduli to factor
                info_dict: Not currently used in this exploit

            Side Effects: 
                If a modulus is factored, the corresponding RSA_Data object's
                private key will be computed and initialized

            Return: 
                True if at least one modulus was factored
        """
    
        global sage_present
    
        if not sage_present:
            print "ECM Factoring: Sage required, skipping exploit"
            return 
        
        print ("ECM Factoring: Running Attack...")
        success = False

        for rsadata in rsadata_list:
            roots = ecm.factor(rsadata.get_n())
            if roots != None:
                rsadata.set_d(compute_priv_rsa_exp(rsadata.get_e(), roots))
                success = True
    
        if success:     
            print("ECM Factoring: Success, roots found, assigned in rsadata.")
        else:           
            print("ECM Factoring: Failure, roots not found.")
        return success
