コード例 #1
0
 def predict(self, guess):
     p = Password(guess)
     p.analyze_frequencies()
     if self.clf.decision_function([p.letter_frequencies.values()]) + 400 > 0:
         return True
     else:
         return False
コード例 #2
0
def entertainChoice(choice):
    if choice == "1":
        date = raw_input("Enter date (dd-mm-yy H:M): ")

        try:
            date = datetime.strptime(date, dateFormat)
        except ValueError:
            print "Date not correct. Try again."
            sys.exit(0)
        password = raw_input("Enter password: "******"2":
        data = Password.getAllPasswords()
        todayDate = datetime.now()
        if len(data) == 0:
            print "File seems to be empty"
        else:
            for counter, p in enumerate(data):
                if todayDate >= p.dateObj:
                    print "{0}. date: {1} \t password: {2}".format(
                        counter, p.getDate(), p.getPassword())
                else:
                    print "Password will be available on/from: {0}".format(
                        p.getDate())

    elif choice == "3":
        confirm = raw_input("Are you sure? y/n")
        if (confirm == 'y'):
            Password.clearAllPasswords()
        else:
            return
コード例 #3
0
ファイル: main.py プロジェクト: JasonPap/hawaian-hacker
def append_numbers():
    wordfile = "input_dictionaries/linkedin.txt"
    outputFile = "output_dictionaries/mutations.txt"

    if len(sys.argv) != 3:
        print "Number of arguments dif than 2, default filenames will be used"
    else:
        wordfile = sys.argv[1]
        outputFile = sys.argv[2]

    # delete the content of the output file if there are any
    with open(outputFile, 'w'):
        pass
    with open(outputFile, 'a') as output:
        with open(wordfile, 'r') as words:
            print "Mutating passwords"
            for simpleWord in words:
                # below should be the logic for the creation of the new dictionary
                password = Password(simpleWord)

                # mutations = password.mutate(change_factor=chng, max_results=mx_res)
                mutations = password.append_numbers()

                # write results to output file
                output.write('\n'.join(mutations) + "\n")
                # print simpleWord + " + " + str(len(mutations))
    return
コード例 #4
0
ファイル: main.py プロジェクト: Viktoriya973/Hack
def main():
    password = input("Password: ")
    hash_object = hashlib.sha1(password.encode('utf-8'))
    pb_hash = hash_object.hexdigest()
    print(pb_hash)
    a1 = Password()
    print(a1.asd(pb_hash))
コード例 #5
0
ファイル: Course.py プロジェクト: myasiny/seas
 def register_student_csv(self, csv_data_file, lecturer):
     csv_reader = csv.reader(csv_data_file)
     data = list(csv_reader)
     auth = []
     reg = []
     pas = Password()
     first = True
     for i in data:
         if first:
             first = False
             continue
         name = handle_tr(i[0]).title()
         surname = handle_tr(i[1]).title()
         student_number = str(int(float(i[2])))
         mail = i[3]
         role = 4
         username = name.split()[0].lower() + surname.lower()
         password = passwordGenerator(8)
         try:
             self.execute(
                 "INSERT INTO members(PersonID, Role, Name, Surname, Username, Password, Email) "
                 "values(%s, '%s', '%s', '%s', '%s', '%s', '%s');" %
                 (student_number, role, name, surname, username,
                  pas.hash_password(password), mail))
             auth.append((name + " " + surname, mail, password, username))
         except IntegrityError:
             pass
         reg.append(student_number)
     threading.Thread(target=send_mail_first_login,
                      args=(auth, lecturer)).start()
     self.register_student(reg)
     return "Done"
コード例 #6
0
ファイル: main.py プロジェクト: JasonPap/hawaian-hacker
def append_numbers():
    wordfile = "input_dictionaries/linkedin.txt"
    outputFile = "output_dictionaries/mutations.txt"

    if len(sys.argv) != 3:
        print "Number of arguments dif than 2, default filenames will be used"
    else:
        wordfile = sys.argv[1]
        outputFile = sys.argv[2]

    # delete the content of the output file if there are any
    with open(outputFile, 'w'):
        pass
    with open(outputFile, 'a') as output:
        with open(wordfile, 'r') as words:
            print "Mutating passwords"
            for simpleWord in words:
                # below should be the logic for the creation of the new dictionary
                password = Password(simpleWord)

                # mutations = password.mutate(change_factor=chng, max_results=mx_res)
                mutations = password.append_numbers()

                # write results to output file
                output.write('\n'.join(mutations) + "\n")
                # print simpleWord + " + " + str(len(mutations))
    return
コード例 #7
0
 def __init__(self, inifile, passfile=None):
     PyWordSeg.__init__(self, inifile)
     XMLParser.__init__(self)
     if passfile:
         self.password = Password(passfile)
         self.auth = True
     else:
         self.auth = False
コード例 #8
0
 def predict(self, guess):
     p = Password(guess)
     p.analyze_frequencies()
     if self.clf.decision_function([p.letter_frequencies.values()
                                    ]) + 400 > 0:
         return True
     else:
         return False
コード例 #9
0
ファイル: main.py プロジェクト: JasonPap/hawaian-hacker
def classify_and_generate():
    wordfile = "input_dictionaries/linkedin.txt"
    outputFile = "output_dictionaries/mutations.txt"
    if len(sys.argv) != 3:
        print "Number of arguments dif than 2, default filenames will be used"
    else:
        wordfile = sys.argv[1]
        outputFile = sys.argv[2]

    # delete the content of the output file if there are any
    with open(outputFile, 'w'):
        pass

    print "Creating classifier"
    classifier = PasswordClassifier()
    classifier.train(wordfile)
    print "Classifier built"

    count = 10000000  # """ <<==== minimum number of passwords to be generated"""
    letter_frequencies = dict()
    with open(outputFile, 'a') as output:
        with open(wordfile, 'r') as words:
            print "Calculating letter frequencies"
            for simpleWord in words:
                # below should be the logic for the creation of the new dictionary
                password = Password(simpleWord)
                password.analyze_frequencies()
                for c in password.letter_frequencies:
                    if c in letter_frequencies:
                        letter_frequencies[c] += password.letter_frequencies[c]
                    else:
                        letter_frequencies[c] = password.letter_frequencies[c]
                # password.print_frequencies()
                # mutations = password.mutate()
                # mutations = password.append_numbers()

                # write results to output file
                # output.write('\n'.join(mutations) + "\n")
            # for c in letter_frequencies:
            #    output.write(c + "," + str(letter_frequencies[c]) + "\n")
            print "Generating new passwords"
            n_created = 0
            while n_created <= count:
                tentative_passwords = PasswordGen.generate_passwords(letter_frequencies, 1000, random.randint(7, 14))
                output_buffer = []
                for p in tentative_passwords:
                    if classifier.predict(p):
                        output_buffer.append(p)
                        P = Password(p)
                        mutations = P.mutate(change_factor=3)
                        output_buffer.extend(mutations)
                        n_created += len(mutations) + 1
                output.write('\n'.join(output_buffer) + "\n")
                print "Created: " + str(n_created)

    print "done"
コード例 #10
0
    def train(self, TrainingFile):
        training_data = []
        with open(TrainingFile) as inputFile:
            for word in inputFile:
                p = Password(word)
                p.analyze_frequencies()
                training_data.append(p.letter_frequencies.values())

        # print training_data
        self.clf.fit(training_data)
コード例 #11
0
    def train(self, TrainingFile):
        training_data = []
        with open(TrainingFile) as inputFile:
            for word in inputFile:
                p = Password(word)
                p.analyze_frequencies()
                training_data.append(p.letter_frequencies.values())

        # print training_data
        self.clf.fit(training_data)
コード例 #12
0
    def getPasswordAcount(self):

        password = Password()

        print("¿Cómo será su contraseña?")
        inPassword = input()
        print(f"Contraseña:, {inPassword}")
        password.Password = inPassword

        return password
コード例 #13
0
    def login():

        # if pathToFile.is_file(): os.remove(pathToFile)

        # if the login file doesn't exist, have the user create an account
        if not pathToLoginFile.is_file():
            firstName = input("What is your first name? ")
            lastName = input("What is your last name? ")
            loginUser = input('What do you want your username to be? ')
            loginPass = Password(
                getpass('What do you want as your password? '))
            # os.removedirs(Path( pathToDir ))

            # loops until the user puts in a max strength password, a strength of 5
            while True:
                if loginPass.check(5):
                    namePass = f"{rBrkt}'First name' : '{firstName}', 'Last name' : '{lastName}', 'UserName' : '{loginUser}', 'Password' : '{loginPass.txt}'{lBrkt}"

                    # generate a key based on the namePass string, then encrypt namePass with that key, that key is also the global encryption key
                    CryptoGraphy.genKey(namePass, pathToDir)
                    CryptoGraphy.encrypt(namePass, f"{pathToDir}",
                                         f"{pathToLoginFile}")
                    break
                # set the txt value of loginPass to the ui
                loginPass.set(
                    getpass(
                        'That password is not very secure, try a different one: '
                    ))

        # if the login file exists
        if pathToLoginFile.is_file():
            namePass = CryptoGraphy.decrypt(pathToLoginFile, pathToDir)
            # namePass is decrypted into a string, so eval it to turn it into the dictionary it is
            namePass = eval(namePass)
            username = namePass["UserName"]
            password = namePass["Password"]

            fails = 0
            while True:
                useful.Terminal.clear()
                print(f"Attempts: {fails}")
                if fails == 3:
                    useful.Terminal.clear()
                    print("You have reached the maximum number of attempts.")
                    quit()

                fails += 1
                if useful.Terminal.inputChecker(
                        input("What's your username? "),
                        username) and useful.Terminal.inputChecker(
                            getpass("What's your password? "), password):
                    break

            PasswordManager.openApp()
コード例 #14
0
def CreateNewUser():
    name = input("Ingrese su nombre: ")
    last_name = input("Ingrese su apellido: ")
    dni = input("Ingrese su número de DNI: ")

    user = User(dni, name, last_name)
    addUser(user)
    password = input("Ingrese una clave: ")
    password = Password(user.dni, password)
    Password.save(password)
    print("Usuario Creado")
    return
コード例 #15
0
ファイル: UI.py プロジェクト: ericpotvin/PyPass
    def _decrypt_data(self):
        """ Decrypt the encrypted data
        """
        if not self._check_for_errors(self.CHECK_DECRYPT):
            return

        encrypted_text = self.txt_encrypted_text.toPlainText()
        cipher = self.cmb_algorithm.currentText()
        digest = self.cmb_digest.currentText()

        my_pass = Password(self.txt_master_password.text(), cipher, digest)
        raw_text = my_pass.decrypt_text(encrypted_text)

        self.txt_raw_text.setPlainText(QtCore.QString(raw_text))
コード例 #16
0
ファイル: prog.py プロジェクト: stirredo/password_encryptor
def entertainChoice(choice):
    if choice == "1":
        date = raw_input("Enter date (dd-mm-yy H:M): ")

        try:
            date = datetime.strptime(date, dateFormat)
        except ValueError:
            print "Date not correct. Try again."
            sys.exit(0)
        password = raw_input("Enter password: "******"2":
        data = Password.getAllPasswords()
        todayDate = datetime.now()
        if len(data) == 0:
            print "File seems to be empty"
        else:
            for counter, p in enumerate(data):
                if todayDate >= p.dateObj:
                    print "{0}. date: {1} \t password: {2}".format(counter, p.getDate(), p.getPassword())
                else:
                    print "Password will be available on/from: {0}".format(p.getDate())

    elif choice == "3":
        confirm = raw_input("Are you sure? y/n")
        if( confirm == 'y'):
            Password.clearAllPasswords()
        else:
            return
コード例 #17
0
class WordSegXML(PyWordSeg, XMLParser):
    def __init__(self, inifile, passfile=None):
        PyWordSeg.__init__(self, inifile)
        XMLParser.__init__(self)
        if passfile:
            self.password = Password(passfile)
            self.auth = True
        else:
            self.auth = False

    def authenticate(self):
        if self.auth == False:
            return True
        info = self.getUserInfo()
        ret = self.password.check(info['username'], info['password'])
        return ret

    def ProcessXML(self, inbuf_xml):
        parse_ok = self.parseString(inbuf_xml)

        if not parse_ok:
            return (2, 'xml format error.')

        if self.authenticate() == False:
            return (3, 'user or password error.')

        textL = self.getText().strip("\r\n").split("\n")
        outL = self.ApplyList(textL)
        outXML = self.XMLStringListWrap(outL, "UTF-8")
        return (1, outXML)
コード例 #18
0
class WordSegXML(PyWordSeg, XMLParser):
    def __init__(self, inifile, passfile=None):
        PyWordSeg.__init__(self, inifile)
	XMLParser.__init__(self)
	if passfile:
	    self.password=Password(passfile)
	    self.auth=True
	else:
	    self.auth=False

    def authenticate(self):
        if self.auth==False:
	    return True
        info=self.getUserInfo()
	ret=self.password.check(info['username'], info['password'])
	return ret

    def ProcessXML(self, inbuf_xml):
        parse_ok=self.parseString(inbuf_xml)

	if not parse_ok:
	    return (2,'xml format error.')

	if self.authenticate()==False:
	    return (3,'user or password error.')

	textL=self.getText().strip("\r\n").split("\n")
	outL=self.ApplyList(textL)
	outXML=self.XMLStringListWrap(outL,"UTF-8")
	return (1, outXML)
コード例 #19
0
    def __init__(self, inifile, passfile=None):
        PyWordSeg.__init__(self, inifile)
	XMLParser.__init__(self)
	if passfile:
	    self.password=Password(passfile)
	    self.auth=True
	else:
	    self.auth=False
コード例 #20
0
    def __init__(self, list_of_json):
        # list_of_json = [{"password": "******", "encryption": null}, {"password": "******", "encryption": "REVERSE"}]
        # An array of {"password": "******", "encryption": ____}

        self.passwords = []

        for p in list_of_json:
            self.passwords.append(Password(p))
コード例 #21
0
    def addPass():
        # ask the user what catagory the password is in, and where the password is used
        if PasswordManager.mstrPWStor.keys().__str__() == "dict_keys([])":
            catagory = input("What do you want to call your first catagory? ")
            passFor = input("Where is this password going to be used? ")
        else:
            while True:
                catagory = input(f"What category is this password; {useful.Strings.lstToStr(PasswordManager.mstrPWStor, ', ', False)}, or enter a new name to create a new catagory? ")
                passFor = input("Where is this password going to be used? ")
                break

        # ask the user what the password is, or generate one for them
        ui = getpass("Type a password, or put a number 1 to 3 for a password with that strength to be generated, 1 being super weak, 3 being super strong: ")
        while True:
            useful.Terminal.clear()
            if ui.isdigit():
                if 3 <= int(ui) + 2 <= 5:
                    if not catagory in PasswordManager.mstrPWStor:
                        PasswordManager.mstrPWStor[catagory] = {}
                    randPass = Password( Generator.genPass(int(ui) + 2) )
                    PasswordManager.mstrPWStor[catagory][passFor] = randPass.getPass()
                    break
            else:
                passTemp = Password(ui)
                if passTemp.check():
                    if not catagory in PasswordManager.mstrPWStor:
                        PasswordManager.mstrPWStor[catagory] = {}
                    PasswordManager.mstrPWStor[catagory][passFor] = passTemp.getPass()
                    break
            ui = getpass("That password was insecure, type a password, or put a number 1 to 3 for a password with that strength to be generated, 1 being super weak, 3 being super strong: ")
コード例 #22
0
ファイル: User.py プロジェクト: myasiny/seas
 def __init__(self, db, organization, username):
     self.db = db
     self.execute = db.execute
     self.execute("USE %s" % organization)
     self.username = username
     self.organization = organization
     self.allowed_extensions = {'png', 'jpg', 'jpeg'}
     self.pass_word = Password()
     self.get = self.get_user_info()
コード例 #23
0
ファイル: User.py プロジェクト: Bellara/Eventmanager_Server
 def __init__(self, id=None, mail=None, name=None, vorname=None, pw=None):
     self.id = id
     self.mail = EventMail(mail)
     self.name = name
     self.vorname = vorname
     if pw != None:
         self.pw = Password(pw)
     else:
         self.pw = None
コード例 #24
0
ファイル: main.py プロジェクト: JasonPap/hawaian-hacker
def classify_and_generate():
    wordfile = "input_dictionaries/linkedin.txt"
    outputFile = "output_dictionaries/mutations.txt"
    if len(sys.argv) != 3:
        print "Number of arguments dif than 2, default filenames will be used"
    else:
        wordfile = sys.argv[1]
        outputFile = sys.argv[2]

    # delete the content of the output file if there are any
    with open(outputFile, 'w'):
        pass

    print "Creating classifier"
    classifier = PasswordClassifier()
    classifier.train(wordfile)
    print "Classifier built"

    count = 10000000  # """ <<==== minimum number of passwords to be generated"""
    letter_frequencies = dict()
    with open(outputFile, 'a') as output:
        with open(wordfile, 'r') as words:
            print "Calculating letter frequencies"
            for simpleWord in words:
                # below should be the logic for the creation of the new dictionary
                password = Password(simpleWord)
                password.analyze_frequencies()
                for c in password.letter_frequencies:
                    if c in letter_frequencies:
                        letter_frequencies[c] += password.letter_frequencies[c]
                    else:
                        letter_frequencies[c] = password.letter_frequencies[c]
                # password.print_frequencies()
                # mutations = password.mutate()
                # mutations = password.append_numbers()

                # write results to output file
                # output.write('\n'.join(mutations) + "\n")
            # for c in letter_frequencies:
            #    output.write(c + "," + str(letter_frequencies[c]) + "\n")
            print "Generating new passwords"
            n_created = 0
            while n_created <= count:
                tentative_passwords = PasswordGen.generate_passwords(
                    letter_frequencies, 1000, random.randint(7, 14))
                output_buffer = []
                for p in tentative_passwords:
                    if classifier.predict(p):
                        output_buffer.append(p)
                        P = Password(p)
                        mutations = P.mutate(change_factor=3)
                        output_buffer.extend(mutations)
                        n_created += len(mutations) + 1
                output.write('\n'.join(output_buffer) + "\n")
                print "Created: " + str(n_created)

    print "done"
コード例 #25
0
ファイル: User.py プロジェクト: myasiny/seas
    def __init__(self, db, organization, username):
        self.db = db
        self.execute = db.execute
        self.execute("USE %s" % organization)
        self.username = username
        self.organization = organization
        self.allowed_extensions = {'png', 'jpg', 'jpeg'}
        self.pass_word = Password()

        self.user_id = None
        self.role = None
        self.name = None
        self.surname = None
        self.hashed_pass = None
        self.email = None
        self.department = None
        self.profile_pic_path = None
        self.role_name = None

        self.get = self.get_user_info()
コード例 #26
0
ファイル: Generator.py プロジェクト: GaegeSmith/2020Finals
    def genPass(strength):

        while True:
            numCap = random.randint(0, 4)
            numLet = random.randint(0, 4)
            numSpecChar = random.randint(0, 4)
            numNums = random.randint(0, 4)

            password = ""
            specChars = "!@#$%^&()"
            pwNoRand = ""

            # assign random capitol letters based on how many are requested
            for i in range(numCap):
                pwNoRand += (chr(random.randint(65, 90)))

            # assign random lowercase letters based on how many are requested
            for i in range(numLet):
                pwNoRand += (str(chr(random.randint(65, 90))).lower())

            # assign random digits based on how many are requested
            for i in range(numNums):
                pwNoRand += (str(random.randint(0, 9)))

            # assign random special characters based on how many are requested
            for i in range(numSpecChar):
                pwNoRand += (str(specChars[random.randint(
                    0,
                    len(specChars) - 1)]))

            # randomize the order of string created above
            for i in range(len(pwNoRand)):
                num = random.randint(0, len(pwNoRand) - 1)
                password += pwNoRand[num]
                # https://stackoverflow.com/questions/14198497/remove-char-at-specific-index-python
                pwNoRand = pwNoRand[:num] + pwNoRand[num + 1:]

            passAttempt = Password(password)
            if passAttempt.check(strength):
                return passAttempt.getPass()
コード例 #27
0
ファイル: PwdConsumer.py プロジェクト: gradoc15/BruteForce_CI
    def run(self):
        while (True):
            password = None
            self.condition.acquire()
            try:
                pw = self.queue.get(block=False)
                password = Password(pw)
                self.condition.notify()
            except queue.Empty:
                self.condition.wait()
                print("no pwd")

                self.condition.release()

            #todo brute force algurithm implementation
            if not password is None:
                myLetters = string.ascii_letters + string.digits + string.punctuation
                for i in range(3, 5):
                    for j in map(''.join, itertools.product(myLetters,
                                                            repeat=i)):
                        if password.check(test=str(j)):
                            print("password found: " + j)
コード例 #28
0
    def validate(self):
        connection = sqlite3.connect("prueba.db")
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM passwords WHERE userDni = '{}'".format(self.userDni))
        registeredPassword = cursor.fetchone()

        if registeredPassword == None:
            return "user not exist"
        password = Password(registeredPassword[0],registeredPassword[1])
        if password.password == self.passwordEntered:
            return "access"
        else:
            return "denied"
コード例 #29
0
ファイル: UI.py プロジェクト: ericpotvin/PyPass
    def _set_combo(self):
        """ Set all the combo for the UI
        """

        # algorithm combo
        combo_object = QtCore.QRect(
            self.POSITION_RIGHT_X, 130, 160, self.TEXT_HEIGHT)
        self.cmb_algorithm.setGeometry(combo_object)
        self.cmb_algorithm.setEditable(False)
        self.cmb_algorithm.setObjectName(_fromUtf8("algorithm"))

        # populate with data
        cipher_list = Password.get_cipher_list()

        for cipher in cipher_list:
            self.cmb_algorithm.addItem(_fromUtf8(cipher))

        # select first one
        self.cmb_algorithm.setCurrentIndex(0)

        # digest combo

        combo_object = QtCore.QRect(
            self.POSITION_RIGHT_X, 200, 160, self.TEXT_HEIGHT)
        self.cmb_digest.setGeometry(combo_object)
        self.cmb_digest.setEditable(False)
        self.cmb_digest.setObjectName(_fromUtf8("digest"))

        # populate with data
        digest_list = Password.get_digest_list()

        for digest in digest_list:
            self.cmb_digest.addItem(_fromUtf8(digest))

        # select first one
        self.cmb_digest.setCurrentIndex(0)
コード例 #30
0
 def sign_up_user(self, organization, request):
     passwd = Password().hash_password(request.form["Password"])
     username = request.form["Username"]
     role = request.form["Role"].lower()
     command = "Insert into %s.members(PersonID, Role, Name, Surname, Username, Password, Email, Department) " \
               "values(%s, '%d', '%s', '%s', '%s', '%s', '%s', '%s')" \
               % (organization,
                  request.form["ID"],
                  int(self.execute("SELECT RoleID FROM %s.roles WHERE Role = '%s'" % (
                      organization, role))[0][0]),
                  request.form["Name"],
                  request.form["Surname"],
                  username,
                  passwd,
                  request.form["Email"],
                  request.form["Department"]
                  )
     return self.execute(command)
コード例 #31
0
    def edit():
        # ask the user what catagory the password is in
        PasswordManager.listPass()
        cat = input(f"What category is the password in ")
        while not cat in PasswordManager.mstrPWStor:
            useful.Terminal.clear()
            PasswordManager.listPass()
            cat = input("That's not a category, try again ")

        # ask the user where the password gets used
        useful.Terminal.clear()
        PasswordManager.listPass()
        place = input("What is the password to ")
        while not place in PasswordManager.mstrPWStor[cat]:
            useful.Terminal.clear()
            PasswordManager.listPass()
            place = input("That place isn't in the records, try again ")

        # ask the user what they want the new password to be, or generate one for them
        ui = getpass(
            "Type a password, or put a number 1 to 3 for a password with that strength to be generated, 1 being super weak, 3 being super strong: "
        )
        while True:
            useful.Terminal.clear()
            if ui.isdigit():
                if 3 <= int(ui) + 2 <= 5:
                    if not cat in PasswordManager.mstrPWStor:
                        PasswordManager.mstrPWStor[cat] = {}
                    randPass = Password(Generator.genPass(int(ui) + 2))
                    PasswordManager.mstrPWStor[cat][place] = randPass.getPass()
                    break
            else:
                passTemp = Password(ui)
                if passTemp.check():
                    if not cat in PasswordManager.mstrPWStor:
                        PasswordManager.mstrPWStor[cat] = {}
                    PasswordManager.mstrPWStor[cat][place] = passTemp.getPass()
                    break
            ui = getpass(
                "That password was insecure, type a password, or put a number 1 to 3 for a password with that strength to be generated, 1 being super weak, 3 being super strong: "
            )
コード例 #32
0
    def test_init(self):
        username = "******"
        password = "******"
        pswd = Password(username, password)

        self.assertIsInstance(pswd, Password)
コード例 #33
0
    def test_hashPassword(self):
        username = "******"
        password = "******"
        pswd = Password(username, password)

        assert pswd.password != "Dumbass"
コード例 #34
0
 def test_check1(self):
     pwd = Password("asd")
     self.assertEqual(True, pwd.check("asd"))
コード例 #35
0
ファイル: User.py プロジェクト: Bellara/Eventmanager_Server
class User:

    def __init__(self, id=None, mail=None, name=None, vorname=None, pw=None):
        self.id = id
        self.mail = EventMail(mail)
        self.name = name
        self.vorname = vorname
        if pw != None:
            self.pw = Password(pw)
        else:
            self.pw = None

    @staticmethod
    def getAll():
        #Alle User Objekte von der Datenbank holen
        db = SQLConnection.getInstance()
        db_content = db.select("SELECT * FROM user", ())

        ret = []

        for e in db_content:
            user = User()
            user.id = EventId()
            user.id.setUnhashed(int(e[0]))
            user.mail = EventMail(str(e[1]))
            pw = Password(h=str(e[2]))
            user.pw = pw
            user.setName(str(e[3]))
            user.setVorname(str(e[4]))

            ret.append(user)

        return ret

    def login(self, pw):
        return self.pw.getHash() == Password(pw).getHash()


    @staticmethod
    def getByMail(m):
        db = SQLConnection.getInstance()
        db_content = db.select("SELECT * FROM user WHERE mail=%s", (m,))

        if len(db_content) is 0:
            raise EventError(EventError.NO_USER_FOUND)

        elif len(db_content) > 1:
            raise Exception()

        else:
            db_content = db_content[0]
            user = User()
            user.id = EventId()
            user.id.setUnhashed(int(db_content[0]))
            user.setMail(str(db_content[1]))
            pw = Password(h=str(db_content[2]))
            user.pw = pw
            user.setName(str(db_content[3]))
            user.setVorname(str(db_content[4]))

            return user

    def register(self):
        #Alle params uebergeben?
        if (self.mail is not None) and \
            (self.pw is not None) and \
            (self.name is not None) and \
            (self.vorname is not None):
        #pruefen ob schon ein element mit mail = sdfsf exisitiert
            db = SQLConnection.getInstance()
            if db.count("SELECT COUNT(*) FROM user WHERE mail=%s", (self.mail,)) > 0:
                raise EventError(EventError.USER_ALREADY_EXISTING)

        #benutzer anlegen
            id = db.insert("INSERT INTO user (mail, pw, name, vorname) VALUES (%s,%s,%s,%s)", (self.mail,
                                                                                          self.pw.getHash(),
                                                                                          self.name,
                                                                                          self.vorname))
            self.id = EventId()
            self.id.setUnhashed(id)
        return

    def getAsDict(self, attr=[]):
        ret = {}

        if len(attr) == 0:
            attr = ["mail", "vorname", "name", "id"]

        if "mail" in attr:
            ret["mail"] = str(self.mail)

        if "name" in attr:
            ret["name"] = self.name

        if "vorname" in attr:
            ret["vorname"] = self.vorname

        if "id" in attr:
            ret["id"] = str(self.id.getHashed())

        return ret

    @staticmethod
    def getById(uid):
        #User Objekt anhand der ID bekommen
        db = SQLConnection.getInstance()
        db_content = db.select("SELECT * FROM user WHERE id=%s", (uid.getUnhashed(),))

        if len(db_content) is 0:
            raise EventError(EventError.NO_USER_FOUND)

        elif len(db_content) > 1:
            raise Exception()

        else:
            db_content = db_content[0]
            user = User()
            user.id = EventId()
            user.id.setUnhashed(int(db_content[0]))

            user.setMail(str(db_content[1]))
            pw = Password(h=str(db_content[2]))
            user.pw = pw
            user.setName(str(db_content[3]))
            user.setVorname(str(db_content[4]))
            return user

    def setMail(self, mail):
        """
        Einfache Ueberpruefung ob Mail eine 'vernuenftige' Mail Adresse ist.

        :param mail: Mail Adresse
        :return: <void>
        """
        email = EventMail(mail)

        if email.check() is False:
            raise EventError.INVALID_MAIL

        self.mail = email

        return

    def setPassword(self, pw):
        if len(pw) < 5:
            raise EventError(EventError.INVALID_PASSWORD)
        pw = Password(s=pw)
        self.pw = pw

        return

    def setName(self, n):
        #TODO ggf. Pruefungen machen
        self.name = n

        return

    def setVorname(self, v):
        #TODO ggf Pruefungen machen
        self.vorname = v
        return
コード例 #36
0
import os
import sys
sys.path.append(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), '..\src'))
import Logger
from Password import Password

try:
    p = Password()
    print(p.get_password(True))
except Exception as e:
    tb = sys.exc_info()[2]
    Logger.Logging("message:{0}".format(e.with_traceback(tb)))
コード例 #37
0
 def test_password(self):
     user_hash_pwd = Password.hash_password(self.password)
     self.assertTrue(Password.hash_check(self.password, user_hash_pwd),
                     (True))
コード例 #38
0
ファイル: start.py プロジェクト: Vishpratap41/PythonPassword
from User import User
from Password import Password
import hashlib
import sys

password = b"bobob001A$"
checkPass = password.decode('utf-8')

user1 = User()
user1.set_name("Bert")

p = Password()

if p.check_complexity(checkPass) == False:
    print("Password not complex enough!")
    exit()
hashed_password = p.hash_password(password)

user1.set_password(hashed_password)
hashed_password = user1.get_password()
p.hash_check(password, hashed_password)
コード例 #39
0
 def test_Pass_if_number_is_in_increasing_order(self):
     number = 123445
     password = Password()
     self.assertTrue(password.validate(number))
コード例 #40
0
ファイル: HandleEmail.py プロジェクト: knail1/stocrates
import imaplib      # IMAP tools
import email        # Email object
import re           # Regular expressions
import InsertParser # Parse insert statements
import StocratesDb  # Connect to database
import inspect      # Frame inspector

from errorLog import errorLog
errorLog = errorLog(__file__)
from Password import Password
password = Password('*****@*****.**', '../../../config.txt')

import pprint       # Pretty printer (development tool)
pp = pprint.PrettyPrinter(indent=4)

# http://stackoverflow.com/questions/2792623/reading-and-parsing-email-from-gmail-using-c-c-or-python

inbox = imaplib.IMAP4_SSL('imap.gmail.com',993) # Specify mail server
inbox.login('stocr4tes', password.getPassword()) # Login to inbox
inbox.select() # Select inbox for read/write
typ, data = inbox.search(None,'UNSEEN') # Get all unread messages. UNSEEN = unread, seen = read, all = all
for num in data[0].split():
    typ, msgData = inbox.fetch(num, '(BODY.PEEK[])') # Do not mark as read for testing purposes
    #typ, msgData = inbox.fetch(num, '(RFC822)') # Mark as read after reading
    for responsePart in msgData:
        if(isinstance(responsePart, tuple)):
            msg = email.message_from_string(responsePart[1]) # Decode message object
            print(msg['subject'])
            if(re.match('^PREDICTION$', msg['subject'], re.IGNORECASE)):
                if msg.is_multipart() == True:
                    for part in msg.get_payload():
コード例 #41
0
ファイル: start.py プロジェクト: harigajmer21/PythonPassword
from User import User
from Password import Password
import hashlib
import os
import bcrypt
#Example to trigger a sonar vulnerability
#import socket
#ip = '127.0.0.1'
#sock = socket.socket()
#sock.bind((ip, 9090))
#Hari gajmer developer
#typical bandit findings
#>>> bandit -r <folder>
#deprecated md5 will not be found by sonar...
password = os.getenv("123_x&5s")
hash_object = bcrypt.hashpw((b'123_x32&'), bcrypt.gensalt())

password = "******".encode()

user1 = User()
user1.set_name("Bert")

p = Password()
hashed_password = p.hash_password(password)

user1.set_password(hashed_password)
hashed_password = user1.get_password()

p.hash_check(password, hashed_password)
コード例 #42
0
 def test_Pass_for_third_advent_code_parameter_123444(self):
     number = 123444
     password = Password()
     self.assertFalse(password.validate(number))