Ejemplo n.º 1
0
    def test_compare(self, User):
        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        other = User()
        other.password = Password(md5_crypt.hash('b'))

        # Not sure what to assert here; the test raised an error before.
        assert obj.password != other.password
Ejemplo n.º 2
0
def write_vmx_config(d1, i):
    print("creating vmx config ", i)
    line1 = []
    line1.append("system {")
    line1.append("   host-name " + i + ";")
    line1.append("   root-authentication {")
    line1.append("      encrypted-password \"" +
                 md5_crypt.hash(d1['vmm_pod']['junos_login']['password']) +
                 "\";")
    line1.append("   }")
    line1.append("   login {")
    line1.append("      user " + d1['vmm_pod']['junos_login']['login'] + " {")
    line1.append("         class super-user;")
    line1.append("         authentication {")
    line1.append("            encrypted-password \"" +
                 md5_crypt.hash(d1['vmm_pod']['junos_login']['password']) +
                 "\";")
    line1.append("         }")
    line1.append("      }")
    line1.append("   }")
    line1.append("""   services {
        ssh;
        netconf {
            ssh;
        }
    }
    syslog {
        user * {
            any emergency;
        }
        file messages {
            any notice;
            authorization info;
        }
        file interactive-commands {
            interactive-commands any;
        }
    }
}
chassis {
   network-services enhanced-ip;
}""")
    line1.append("""interfaces {
   fxp0 {
      unit 0 {
         family inet {
             address %s;
         }
      }
    }
}""" % (d1['vm'][i]['interfaces']['fxp0'][1]))
    f1 = param1.tmp_dir + i + ".conf"
    write_to_file(f1, line1)
Ejemplo n.º 3
0
    def __call__(self):
        '''
        Actually reset the password, if correct key (from sent link) 
        is used to come here and member is identifiable from request.
        '''
        self.login_necessary = False
        session = DBSession()
        md = self.request.matchdict

        def info(msg):
            return dict(form="", m=None, key=None, msg=msg)

        if not 'key' in md or md['key'] == "":
            return info(u'Sorry, no key given to grant reset request.')
        member = get_member(session, self.request)
        if not member:
            return info(u'Sorry, cannot identify member.')
        if member.mem_pwd_url != md['key']:
            return info(u'Sorry, the reset request cannot be authorised.')
        if 'pwd1' not in self.request.params:
            # show password reset form
            return dict(m=member, form='reset', key=md['key'])
        # set new password
        member.validate_pwd(self.request)
        pwd = str(self.request.params['pwd1'])
        member.mem_enc_pwd = md5_crypt.hash(pwd)
        member.mem_pwd_url = ''
        return info(u'Password has been set.'\
               ' Please use the new password the next time you log in.')
Ejemplo n.º 4
0
def resetpassword(user, password):
    db = sqlite3.connect(DB_FILE)
    c = db.cursor()
    params = (md5_crypt.hash(password), user)
    c.execute("UPDATE users SET password = ? WHERE email = ?", params)
    db.commit()
    db.close()
Ejemplo n.º 5
0
def enter_reset_password():
    form = passwordReset()
    if request.method == "POST" and form.validate_on_submit():
        token_value = request.args.get("token")
        verify_token = Reset_password.query.filter_by(token=token_value).first()
        if verify_token:
            current_time = time.time()
            if current_time >= verify_token.dateTime:
                db.session.delete(verify_token)
                db.session.commit()
                # error message
                flash("token has expired, try again")
                return redirect(f"/enter-reset-password?token={token_value}")
            else:
                # success msg
                password = request.form.get("password")
                password = md5_crypt.hash(password)
                user_id = request.args.get("i")
                user = User.query.filter_by(id=user_id).first()
                user.password = password
                delete_confirm = Reset_password.query.filter_by(mail=user.email).all()
                for each_delete_confirm in delete_confirm:
                    db.session.delete(each_delete_confirm)
                db.session.commit()
                
                flash("You have successfully changed your password")
                return redirect(url_for("login"))
        else:
            flash("token does not exist")
            return redirect(url_for("enter_reset_password"))
    else:
        return render_template('enter_reset_password.html', form=form)
Ejemplo n.º 6
0
 def fill_data(self):
     '''
     Fills in dummy content that we will use for testing
     2 members, Peter and Hans.
     2 workgroups, Systems and Besteling.
     Peter is the only member in Systems.
     Both are members in Bestel, with Hans leading that one.
     Bestel has a shift ('do stuff') for Peter.
     '''
     m1 = Member(fname=u'Peter', prefix=u'de', lname='Pan')
     m1.mem_email = '*****@*****.**'
     m1.mem_enc_pwd = md5_crypt.hash('notsecret')
     self.DBSession.add(m1)
     m2 = Member(fname=u'Hans', prefix=u'de', lname='Wit')
     m1.mem_email = '*****@*****.**'
     self.DBSession.add(m2)
     wg1 = Workgroup(name=u'Systems', desc=u'IT stuff')
     self.DBSession.add(wg1)
     wg2 = Workgroup(name=u'Besteling', desc=u'Besteling at wholesale')
     self.DBSession.add(wg2)
     self.DBSession.flush()  # flush now to get member and workgroup IDs
     wg1.members.append(m1)
     wg1.leaders.append(m1)
     wg2.members.append(m1)
     wg2.members.append(m2)
     wg2.leaders.append(m2)
     self.DBSession.flush()
     s = Shift(wg2.id, 'do stuff', 2012, 6, member=m1)
     self.DBSession.add(s)
     self.DBSession.flush()
     # reserved transaction types
     for rt in reserved_ttype_names:
         self.DBSession.add(TransactionType(name=rt))
     self.DBSession.flush()
Ejemplo n.º 7
0
def password_set(request, template_name='password_set_form.html'):
    if request.method == "POST":
        data = request.POST
        customer_id = data.get('customer_id', '')
        new_password2 = data.get('new_password2', '')
        from passlib.hash import md5_crypt

        password = md5_crypt.hash(new_password2)
        obj = Customer.objects.get(id=customer_id)
        obj.password = password
        obj.save()

        CorePasswordAlter.objects.filter(customer_id=customer_id).update(
            isvalid=False)

        messages.add_message(request, messages.SUCCESS, _lazy(u'密码修改成功'))
        return HttpResponseRedirect('/login')

    uuids = request.GET.get('uuid', '')
    token = request.GET.get('token', '')
    try:
        p_obj = CorePasswordAlter.objects.get(uuid=uuids, token=token)
        customer_id = p_obj.customer_id
        expire_time = p_obj.expire_time
        isvalid = p_obj.isvalid
        if (time.time() > expire_time) or (not isvalid):
            return TemplateResponse(request, 'http404.html', {})
        else:
            return TemplateResponse(request, template_name, {
                'uuid': uuids,
                'token': token,
                'customer_id': customer_id,
            })
    except:
        return TemplateResponse(request, 'http404.html', {})
Ejemplo n.º 8
0
def Validate_Md5(**kwargs):
    '''
    **kwargs=(
    password= Clean text password, 
    hashed= Hashed Md5 password)
    
    Return string containing status
    '''
    if not kwargs.get("hashed"):
        return ("Error,hash not provided")
    if "$1$" not in kwargs.get('hashed'):
        return ("Error, hash not well defined")
    try:
        from passlib.hash import md5_crypt
    except:
        return ("This module requires passlib module")
    try:
        salt = re.search('\$\d\$(.*)\$', kwargs.get("hashed")).group(1)
        try:
            h = md5_crypt.hash(kwargs.get("password"), salt=salt)
        except:
            return ("Error, password not defined")
    except:
        return ("Error, hash not defined")
    if h == kwargs.get("hashed"):
        return ("Match")
    else:
        return ("Not Match")
Ejemplo n.º 9
0
def push_file(name, password, file, filename, socketio):
    r = redis.Redis()
    mimetype = mimetypes.MimeTypes().guess_type(filename)[0]
    if mimetype is None:
        mimetype = 'application/octet-stream'
    base = file_to_base64(file)
    plaintext = filename.encode() + b'mimetype:' + mimetype.encode(
    ) + b'filedata:' + base
    data = encrypt(password, plaintext)
    blocks = textwrap.wrap(data.decode(), BLOCK_SIZE)

    i = 0
    for block in blocks:
        block_id = uuid.uuid1().hex
        # Set block to file name hashtable
        block_hash = md5_crypt.hash(block)
        r.hset('file-' + name, 'block' + str(i), block_id)
        # Set connection between block id and hash
        r.hset(block_id, 'hash', block_hash)
        nodes = pickle.dumps(set())
        r.hset(block_id, 'nodes', nodes)
        i += 1
        t = threading.Thread(target=push_block,
                             args=(block, block_id, get_available_nodes(20),
                                   socketio))
        t.start()
Ejemplo n.º 10
0
        def signup():
            signup_data = sign_up_data()
            user_name = signup_data['username']
            password = signup_data['password']
            phone = signup_data['phone']
            email = signup_data['email']
            check_if_user_exist = self.user.query.filter_by(email=email).all()
            if len(check_if_user_exist) > 0:
                signup_message = {
                    "failure": "The email you are trying use already exist"
                }
            else:
                password = md5_crypt.hash(password)
                check_for_first_user = len(self.user.query.all())
                if not check_for_first_user:
                    user = self.user(username=user_name,
                                     is_admin=True,
                                     phone=phone,
                                     email=email,
                                     password=password)
                else:
                    user = self.user(username=user_name,
                                     is_admin=False,
                                     phone=phone,
                                     email=email,
                                     password=password)

                self.db.session.add(user)
                self.db.session.commit()

                signup_message = {"success": "you have sign up successfully"}
            return jsonify(signup_message)
Ejemplo n.º 11
0
def create_user(username, password, is_admin=False):
    user = get_user(username)
    if not user:
        password = md5_crypt.hash(password)
        user = User(username=username, password=password, is_admin=is_admin)
        db.session.add(user)
        db.session.commit()
    return user
Ejemplo n.º 12
0
def md5_hash(txt):
    '''
    Returns the MD5 Hashed secret for use as a password hash in the PanOS configuration
    :param txt: text to be hashed
    :return: password hash of the string with salt and configuration information. Suitable to place in the phash field
    in the configurations
    '''
    return md5_crypt.hash(txt)
Ejemplo n.º 13
0
def add_user(name, email, password, security_question, security_answer):
    db = sqlite3.connect(DB_FILE)
    c = db.cursor()
    password = md5_crypt.hash(password)
    params = (name, email, password, security_question, security_answer)
    c.execute("INSERT INTO users VALUES(?, ?, ?, ?, ?)", params)
    db.commit()
    db.close()
Ejemplo n.º 14
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))

    form = MyForm()
    if request.method == "POST" and form.validate_on_submit():
        # referral = request.form.get('ref')
        email = form.email.data
        password = form.password.data
        username = form.username.data
        bank_name = form.bank_name.data
        account_name = form.account_name.data
        account_number = form.account_number.data
        bitcoin_wallet = form.bitcoin_wallet.data
        mobile_number = form.mobile_number.data
        country = request.form.get("country")
        referral = form.referral.data

        password = md5_crypt.hash(password)
        check_for_first_user = len(User.query.all())
        if not check_for_first_user:
            user = User(username=username,
                        referral=referral,
                        is_admin=True,
                        password=password,
                        country=country,
                        account_number=account_number,
                        account_name=account_name,
                        bitcoin_addr=bitcoin_wallet,
                        bank_name=bank_name,
                        mobile_number=mobile_number,
                        email=email)
        else:
            user = User(username=username,
                        referral=referral,
                        is_admin=False,
                        password=password,
                        country=country,
                        account_number=account_number,
                        account_name=account_name,
                        bitcoin_addr=bitcoin_wallet,
                        bank_name=bank_name,
                        mobile_number=mobile_number,
                        email=email)

        db.session.add(user)
        db.session.commit()

        flash("You have signed up successfully")
        return redirect('/login')
    else:
        ref = request.args.get("ref")
        context = {"ref": ref}
        all_tasks = Admin_tasks.query.all()
        for task in all_tasks:
            context[f"{task.key}"] = task.value
        return render_template("sign_up.html", form=form, context=context)
Ejemplo n.º 15
0
def enter_token():
    if request.method == "POST":
        token_value = request.form.get("token")
        print(token_value)
        verify_token = Confirm_mail.query.filter_by(token=token_value).first()
        if verify_token:
            current_time = time.time()
            print(current_time, verify_token.dateTime)
            if current_time >= float(verify_token.dateTime):
                db.session.delete(verify_token)
                db.session.commit()
                flash("token has expired, try again")
                return redirect(url_for("sign_up"))

            else:
                # success msg
                user_data = json.loads(verify_token.user_details)
                user_name = user_data.get("username")
                password = user_data.get("password")
                email = user_data.get("email")
                mobile_number = user_data.get("mobile_number")
                bitcoin_wallet = user_data.get("bitcoin_wallet")
                account_name = user_data.get("account_name")
                bank_name = user_data.get("bank_name")
                account_number = user_data.get("account_number")
                country = user_data.get("country")
                referral = user_data.get("referral")

                password = md5_crypt.hash(password)

                check_for_first_user = len(User.query.all())
                if not check_for_first_user:
                    user = User(username=user_name, referral=referral, is_admin=True, password=password, country=country, account_number=account_number, account_name=account_name, bitcoin_addr=bitcoin_wallet, bank_name=bank_name, mobile_number=mobile_number, email=email)
                else:
                    user = User(username=user_name, referral=referral, is_admin=False, password=password, country=country, account_number=account_number, account_name=account_name, bitcoin_addr=bitcoin_wallet, bank_name=bank_name, mobile_number=mobile_number, email=email)

                db.session.add(user)

                delete_confirm = Confirm_mail.query.filter_by(mail=email).all()
                for each_delete_confirm in delete_confirm:
                    db.session.delete(each_delete_confirm)
                db.session.commit()


                flash("your account has been verified successfully, you can now login")
                return redirect(url_for("login"))
            print(verify_token.token)
        else:
            flash("token does not exist")
            return redirect(url_for("enter_token"))
    else:
        context = {}
        all_tasks = Admin_tasks.query.all()
        for task in all_tasks:
            context[f"{task.key}"] = task.value
        return render_template("enter_token.html", context=context)
Ejemplo n.º 16
0
    def __md5_hash(txt: str) -> str:
        """
        Returns the MD5 Hashed secret for use as a password hash in the PAN-OS configuration

        :param txt: text to be hashed
        :return: password hash of the string with salt and configuration information. Suitable to place in the phash field
        in the configurations
        """

        return md5_crypt.hash(txt)
Ejemplo n.º 17
0
def decrypt_md5(enc_pwd, pwdlist):
	##fill this

	split_enc = enc_pwd.split('$')
	#print(enc_pwd)
	for word in pwdlist:
		#print(md5_crypt.hash(word, salt=split_enc[2]))
		if md5_crypt.hash(word.rstrip(), salt=split_enc[2]).strip() == enc_pwd.strip():
			return word
	return ""
Ejemplo n.º 18
0
def bf(h, dictionary):

    f = open(dictionary, 'r')
    lines = f.readlines()
    print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h)
    for i in lines:

        h2 = md5_crypt.hash(i[:-1])

        if h == h2:

            print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i)
Ejemplo n.º 19
0
 def encrypt(self, password, type):
     pwd_hash = ""
     if (type == "md5"):
         pwd_hash = md5_crypt.hash(password.strip())
     elif (type == "bcrypt"):
         pwd_hash = bcrypt.hash(password.strip())
     elif (type == "sha256"):
         pwd_hash = sha256_crypt.hash(password.strip())
     elif (type == "sha512"):
         pwd_hash = sha512_crypt.hash(password.strip())
     print("Type: {}. Your hash: {}".format(type, pwd_hash))
     return pwd_hash
Ejemplo n.º 20
0
async def createsuperuser(args):
    await Tortoise.init(config=settings.TORTOISE_ORM)
    from apps.auth.models import User
    from passlib.hash import md5_crypt
    username = input("enter username:"******"username is wrong")
    password = input("enter password:"******"password is wrong")
    password = md5_crypt.hash(password)
    u = await User.create(username=username, password=password, is_superuser=True, is_staff=True, is_active=True)
    print(Fore.GREEN + "create username:" + u.username)
Ejemplo n.º 21
0
    def test_check_and_update(self, User):
        """
        Should be able to compare the plaintext against a deprecated
        encrypted form and have it auto-update to the preferred version.
        """

        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'
        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')
Ejemplo n.º 22
0
def sub_account_reset(request, user_id):
    obj = get_customer_child_obj(request, user_id)
    if request.method == "POST":
        new_password2 = request.POST.get('new_password2', None)
        password = md5_crypt.hash(new_password2)
        obj.password = password
        obj.save()
        messages.add_message(request, messages.SUCCESS, _(u'密码修改成功'))
        return HttpResponseRedirect(reverse('sub_account'))

    return render(request,
                  template_name='setting/sub_account_reset.html',
                  context={
                      'user_obj': obj,
                      'user_id': user_id,
                  })
Ejemplo n.º 23
0
        def confirm_signup_token():
            token = token_data()
            print(token)
            token_value = token['token']
            print(token['token'])

            verify_token = self.confirmMail.query.filter_by(
                token=token_value).first()
            if verify_token:
                current_time = time.time()
                if current_time >= verify_token.dateTime:
                    self.db.session.delete(verify_token)
                    self.db.session.commit()
                    # error message
                    confirm_message = {
                        "failure": "token has expired, try again"
                    }
                    return confirm_message

                else:
                    # success msg
                    print(verify_token.user_details)
                    print(type(verify_token.user_details))
                    user_data = json.loads(verify_token.user_details)
                    credentials = []

                    for value in user_data.values():
                        credentials.append(value)

                    user_name, password, *misc = credentials
                    password = md5_crypt.hash(password)

                    user = self.user(username=user_name, password=password)
                    self.db.session.add(user)
                    self.db.session.commit()
                    confirm_message = {
                        "success":
                        "your account has been verified successfully, you can now change password"
                    }
                    # confirm_message = { "success": "your account has been verified successfully" }
                    return confirm_message
                print(verify_token.token)
            else:
                confirm_message = {"failure": "token does not exist"}
                # print("token does not exist")
            return confirm_message
Ejemplo n.º 24
0
def enter_token():
    if request.method == "POST":
        token_value = request.form.get("token")
        verify_token = Confirm_mail.query.filter_by(token=token_value).first()
        if verify_token:
            current_time = time.time()
            if current_time >= verify_token.dateTime:
                db.session.delete(verify_token)
                db.session.commit()
                # error message
                flash("token has expired, try again")
                return redirect(url_for("confirm_mail"))
                
            else:
                # success msg
                user_data = json.loads(verify_token.user_details)
                user_name = user_data.get("name")
                password = user_data.get("password")
                email = user_data.get("email")
                phone = user_data.get("phone")
    
                password = md5_crypt.hash(password)
                
                user = User(username=user_name, password=password, phone=phone, email=email)
                db.session.add(user)

                delete_confirm = Confirm_mail.query.filter_by(mail=email).all()
                for each_delete_confirm in delete_confirm:
                    db.session.delete(each_delete_confirm)
                db.session.commit()
                

                flash("your account has been verified successfully, you can now login")
                return redirect(url_for("login"))
            print(verify_token.token)
        else:
            flash("token does not exist")
            return redirect(url_for("confirm_mail"))
    else:
        return render_template("enter_token.html")
Ejemplo n.º 25
0
def main(argv):
    username = ""
    password = ""
    try:
        opts, args = getopt.getopt(argv, "hu:p:", ["iuser="******"ipass"])
    except getopt.GetoptError:
        #print 'validate_credentials.py -u <user> -p <pass>'
        print "error~:~x1008~:~Parameter not Passed Correctly"
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-H':
            #print 'validate_credentials.py -u <user> -p <pass>'
            print "error~:~x1009~:~Parameter not Passed Correctly"
            sys.exit()
        elif opt in ("-u", "--iuser"):
            username = arg.strip()
        elif opt in ("-p", "--ipass"):
            password = arg.strip()
    #print username+"   "+password
    #print 'Input file is :', filename
    #print bcrypt.hashpw(str(random.random()), bcrypt.gensalt())
    #print "<br>"
    #print bcrypt.hashpw(str(password+universal_slt_key), bcrypt.gensalt())
    if username == "":
        print "error~:~x1006~:~Username Can't Be Empty"
        sys.exit()
    if password == "":
        print "error~:~x1007~:~Password Cant Be Empty"
        sys.exit()
    check_credentials = verify_credentials()
    token = check_credentials.authenticate_credentials(username, password)
    if (token == -111):
        print "Token~:~" + md5_crypt.hash(str(
            random.random())) + '~:~' + User_f_l_name + '~:~' + str(User_ID)
    else:
        if (token == -112):
            print "error~:~#1005~:~Usename Not Found"
        else:
            print "error~:~#1001~:~Password Does Not Match"
Ejemplo n.º 26
0
    def _set_expert_password(self, cli_service, logger):
        """Set expert password.

        :param cloudshell.cli.cli_service.CliService cli_service:
        :param logging.Logger logger:
        :rtype: bool
        """
        # gen enable password hash
        enable_password_hash = md5_crypt.hash(
            self.resource_config.enable_password,
            salt_size=random.choice(range(5, 8)))

        error_map = OrderedDict([
            ("Configuration lock present", "Configuration lock present."),
            ("Failed to maintain the lock", "Failed to maintain the lock."),
            ("Wrong password", "Wrong password."),
        ])
        cli_service.send_command(
            command="set expert-password-hash {}".format(enable_password_hash),
            logger=logger,
            error_map=error_map,
        )
Ejemplo n.º 27
0
def addAdmin():
    '''
    after old names are added, he has ID 3
    '''
    admin = Member(fname=u'Adalbert', lname='Adminovic')
    admin.mem_email = '*****@*****.**'
    admin.mem_mobile = "06" + str(random.randint(10000000, 100000000))
    admin.household_size = 1
    admin.mem_enc_pwd = md5_crypt.hash('notsecret')
    admin.mem_admin = True
    admin.mem_active = True
    DBSession.add(admin)
    DBSession.flush()
    wgs = DBSession.query(Workgroup).filter(
        Workgroup.name == u'Systems').first()
    wgs.members.append(admin)
    wgm = DBSession.query(Workgroup).filter(
        Workgroup.name == u'Membership').first()
    wgm.members.append(admin)
    wgf = DBSession.query(Workgroup).filter(
        Workgroup.name == u'Finance').first()
    wgf.members.append(admin)
    return admin
Ejemplo n.º 28
0
def addOldMembers():
    m1 = Member(fname=u'Peter', prefix=u'de', lname='Pan')
    m1.mem_email = '*****@*****.**'
    m1.mem_enc_pwd = md5_crypt.hash('notsecret')
    DBSession.add(m1)
    m2 = Member(fname=u'Hans', prefix=u'de', lname='Wit')
    m1.mem_email = '*****@*****.**'
    DBSession.add(m2)
    wg1 = Workgroup(name=u'Systems', desc=u'IT stuff')
    DBSession.add(wg1)
    wg2 = Workgroup(name=u'Besteling', desc=u'Besteling at wholesale')
    DBSession.add(wg2)
    DBSession.flush()  # flush now to get member and workgroup IDs
    wg1.members.append(m1)
    wg1.leaders.append(m1)
    wg2.members.append(m1)
    wg2.members.append(m2)
    wg2.leaders.append(m2)
    DBSession.flush()
    s = Shift(wg2.id, 'do stuff', 2012, 6, member=m1)
    DBSession.add(s)
    DBSession.flush()
    return m1, m2
Ejemplo n.º 29
0
    def test_check_and_update_persist(self, session, User):
        """
        When a password is compared, the hash should update if needed to
        change the algorithm; and, commit to the database.
        """

        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        session.add(obj)
        session.commit()

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'

        session.commit()

        obj = session.query(User).get(obj.id)

        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')
        assert obj.password == 'b'
Ejemplo n.º 30
0
def type5_decrypt(enc_pwd, dict):

    print("[*] Bruteforcing 'type 5' hash...\n")

    # Count passwords in the wordlist
    passnum = linecounter(dict)
    print("\tFound %d passwords to test." % passnum)

    try:
        passf = open(dict, 'rb')
    except IOError:
        print('[ERR] Cannot open:', dict)
        exit(-1)

    # Splitting hash
    split_pwd = enc_pwd.split('$')

    print("\tTesting: %s" % enc_pwd)
    if split_pwd[1] == '1':
        print("\tHash Type = MD5")
    else:
        print("\t[ERR] Your 'type 5' hash is not valid.")
        exit(-1)

    print("\tSalt = %s" % split_pwd[2])
    print("\tHash = %s\n" % split_pwd[3])

    count = 0
    for line in passf.readlines():
        # random status
        if random.randint(1, 100) == 42:
            print("\t[Status] %d/%d password tested..." % (count, passnum))
        if md5_crypt.hash(line.rstrip(), salt=split_pwd[2]) == enc_pwd:
            print("\n[*] Password Found = %s" % line.decode("utf-8"))
            exit(0)
        count += 1
    print("\t[-] Password Not Found. You should try another dictionary.")
Ejemplo n.º 31
0
def type5_decrypt(enc_pwd, dict):

    print("[*] Bruteforcing 'type 5' hash...\n")

    # Count passwords in the wordlist
    passnum = linecounter(dict)
    print("\tFound %d passwords to test." % passnum)

    try:
        passf = open(dict, 'rb')
    except IOError:
        print('[ERR] Cannot open:', dict)
        exit(-1)

    # Splitting hash
    split_pwd = enc_pwd.split('$')

    print("\tTesting: %s" % enc_pwd)
    if split_pwd[1] == '1':
        print("\tHash Type = MD5")
    else:
        print("\t[ERR] Your 'type 5' hash is not valid.")
        exit(-1)

    print("\tSalt = %s" % split_pwd[2])
    print("\tHash = %s\n" % split_pwd[3])

    count = 0
    for line in passf.readlines():
        # random status
        if random.randint(1, 100) == 42:
            print("\t[Status] %d/%d password tested..." % (count, passnum))
        if md5_crypt.hash(line.rstrip(), salt=split_pwd[2]) == enc_pwd:
            print("\n[*] Password Found = %s" % line.decode("utf-8") )
            exit(0)
        count += 1
    print("\t[-] Password Not Found. You should try another dictionary.")
Ejemplo n.º 32
0
 def _encrypt(self, clearvalue, salt=None):
     return md5_crypt.hash(clearvalue)