def reset_ldap_password(service_id): confirm_service_admin(service_id) service = Service.query.get(service_id) password = "".join(random.sample(string.ascii_lowercase + string.digits + "_,./~=+@*-", k=32)) hashed = sha512_crypt.using(rounds=100_000).hash(password) service.ldap_password = hashed db.session.merge(service) return {"ldap_password": password}, 200
def _anonymize_value(raw_val, lookup, reserved_words): """Generate an anonymized replacement for the input value. This function tries to determine what type of value was passed in and returns an anonymized value of the same format. If the source value has already been anonymized in the provided lookup, then the previous anon value will be used. """ # Separate enclosing text (e.g. quotes) from the underlying value sens_head, val, sens_tail = _extract_enclosing_text(raw_val) if val in reserved_words: logging.debug('Skipping anonymization of reserved word: "%s"', val) return raw_val if not val: logging.debug('Nothing to anonymize after removing special characters') return raw_val if val in lookup: anon_val = lookup[val] logging.debug('Anonymized input "%s" to "%s" (via lookup)', val, anon_val) return sens_head + anon_val + sens_tail anon_val = 'netconanRemoved{}'.format(len(lookup)) item_format = _check_sensitive_item_format(val) if item_format == _sensitive_item_formats.cisco_type7: # Not salting sensitive data, using static salt here to more easily # identify anonymized lines anon_val = cisco_type7.using(salt=9).hash(anon_val) if item_format == _sensitive_item_formats.numeric: # These are the ASCII character values for anon_val converted to decimal anon_val = str(int(b2a_hex(b(anon_val)), 16)) if item_format == _sensitive_item_formats.hexadecimal: # These are the ASCII character values for anon_val in hexadecimal anon_val = b2a_hex(b(anon_val)).decode() if item_format == _sensitive_item_formats.md5: old_salt_size = len(val.split('$')[2]) # Not salting sensitive data, using static salt here to more easily # identify anonymized lines anon_val = md5_crypt.using(salt='0' * old_salt_size).hash(anon_val) if item_format == _sensitive_item_formats.sha512: # Hash anon_val w/standard rounds=5000 to omit rounds parameter from hash output anon_val = sha512_crypt.using(rounds=5000).hash(anon_val) if item_format == _sensitive_item_formats.juniper_type9: # TODO(https://github.com/intentionet/netconan/issues/16) # Encode base anon_val instead of just returning a constant here # This value corresponds to encoding: Conan812183 anon_val = '$9$0000IRc-dsJGirewg4JDj9At0RhSreK8Xhc' lookup[val] = anon_val logging.debug('Anonymized input "%s" to "%s"', val, anon_val) return sens_head + anon_val + sens_tail
def _hash_password(self, password): """ Return SHA512-CRYPT password hash of a given password. Requires the passlib module to work """ if PASSLIB_ENABLED: return '{SHA512-CRYPT}' + sha512_crypt.using(rounds=5000).hash(password) else: return False
def testPass(cryptPass): salt = cryptPass[3:11] print("[+] Salt: ", salt) dictFile = open('rockyou.txt', encoding='ISO-8859-1') for word in dictFile: word = word.strip('\n') cryptword = sha512_crypt.using(salt=salt, rounds=5000).hash(word) if (cryptword == cryptPass): print("[+] Found password: "******"\n") return print("[-] Password not found.\n") return
def main(): """Print the hash of an input password""" verified = False while not verified: # Ask for password from stdin and generate hash password_hash = sha512_crypt.using(rounds=5000).hash(getpass()) # Ask again and confirm if the hashes match verified = sha512_crypt.verify(getpass("Verify password: "******"\nPassword verified") print(f"Hash: {password_hash}")
def crack_password(username, password, dictionary_file): salt = password.split('$') if len(salt) > SALT_INDEX: salt = salt[SALT_INDEX] with open(dictionary_file) as dictionary_file: for candidate in dictionary_file: candidate = candidate.rstrip('\n') candidate_hash = sha512_crypt.using(rounds=5000).using(salt=salt).hash(candidate.encode('utf-8')) if candidate_hash == password: print('[+] Found password: [' + candidate + '] for: ' + username) found = True return print('[-] No password found for: ' + username)
def crack(max_depth = 3, target_depth = 3, current_depth=1, word=""): result = "" if current_depth > max_depth: return "" for c in chars: if(target_depth == current_depth): test = sha512_crypt.using(salt=salt, rounds=5000).hash(word+c) if test == password: return word+c else: result = crack(max_depth, target_depth, current_depth+1, word + c) if(result != ""): break return result
def test_password_match(host): with host.sudo(): f = host.file('/home/admin/.root_password') user_root_password = host.user('root').password user_root_password_parts = user_root_password.split('$') password_hash = sha512_crypt.using( rounds=5000, salt=user_root_password_parts[2]).hash(f.content_string) assert f.exists assert user_root_password == password_hash
def main(): # begin: argument parsing parser = argparse.ArgumentParser() parser.add_argument('-p', '--password', required=True, help='password to encrypt') args = parser.parse_args() # end: argument parsing hashed = sha512_crypt.using(rounds=5000).hash(args.password) print(hashed)
def generate_passwd(user_list, force=False): passwd_dict = {} for user in user_list: passwd_dict[user] = randomString(20) pass_file = f"{user}.password" if force or (not os.path.isfile(passwd_folder / pass_file)): with open(passwd_folder / pass_file, 'w') as f: f.write(passwd_dict[user]) print( f"password for {user} was created in the {passwd_folder/pass_file}" ) with open(passwd_folder / f"{pass_file}_hashed", 'w') as f: f.write( sha512_crypt.using(rounds=5000).hash(passwd_dict[user])) else: print(f"Pass for {user} exists in the {passwd_folder / pass_file}")
def decode(ciphertext, mode): file0 = None if mode == 1: file0 = open("mode1.txt", "r+") elif mode == 2: file0 = open("mode2.txt", "r+") else: file0 = open("mode3.txt", "r+") cipher_list = ciphertext.split(":")[1].split("$") if cipher_list[1] != "6": print( "It is not hashed by SHA-512! Only when the number after the first $ sign is 6, it is SHA-512 hashing." ) exit() else: salt0 = cipher_list[2] if len(salt0) != 16: print("length of salt is not equal to 16!") ct = cipher_list[3] fw = file0.readlines() compare = '$6$' + salt0 + '$' + ct bar = Bar('Processing', max=len(fw), fill='♡') for i in range(len(fw)): bar.next() test = fw[i].strip() h_test = sha512_crypt.using(salt=salt0, rounds=5000).hash(test) if h_test == compare: print("\n") print("solved!!!") print("The password is: {}".format(test)) bar.finish() exit() bar.finish() if mode in [1, 2]: print("Cannot find password. You can try the higher mode.") exit() elif mode == 3: print( "Looks like it is a very complex password. Sorry I cannot decode it." ) exit()
def test_update_passwd(self): new_passwd = sha512_crypt.using(rounds=5000).hash('milan') print(new_passwd) post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'user', 'name': 'test2', 'state': 'update', 'password': new_passwd, 'update_password': '******' } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def create_user(self): """ 创建用户 :return: """ ip, root_user, new_user, new_pass, group = self.ensure_data() path = self.save_hosts() hash_pass = sha512_crypt.using(rounds=5000).hash(new_pass) print hash_pass s = subprocess.Popen( 'ansible -i {0} {1} -m user -a "name={2} shell=/bin/bash group={3} password={4}" -u {5} -become' .format(path, ip, new_user, group, hash_pass, root_user), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) sc = s.communicate() if '{0} | SUCCESS '.format(ip) in sc[0]: return {'code': 200, 'message': 'Success'} return {'code': 4040, 'message': 'Create User Failure'}
def crackPass(fullHash, algo, salt, wordList): dictFile = open(wordList, 'r') for word in dictFile.readlines(): word = word.strip('\n') if algo == hashTypes['MD5']: if md5_crypt.using(salt=salt, rounds=5000).verify(word, fullHash): print("[+] Found Password: "******"\n") return if algo == hashTypes['SHA-256']: if sha256_crypt.using(salt=salt, rounds=5000).verify(word, fullHash): print("[+] Found Password: "******"\n") return if algo == hashTypes['SHA-512']: if sha512_crypt.using(salt=salt, rounds=5000).verify(word, fullHash): print("[+] Found Password: "******"\n") return print("[-] Password Not Found.\n") return
def main(): # begin: argument parsing parser = argparse.ArgumentParser() parser.add_argument('-p', '--password', required=True, help='password to encrypt') parser.add_argument('-e', '--environment', required=True, help='environment in which the password is to be used e.g. dev | stage | prod') args = parser.parse_args() # end: argument parsing hashed = sha512_crypt.using(rounds=5000).hash(args.password) print( ''' Password encrypted. Add the following entry to your ini file: [{}] login_password={} '''.format(args.environment, hashed) )
def encrypt(passwd: str) -> str: """Encrypts the password using 5000 rounds of sha512.""" return sha512_crypt.using(rounds=5000).hash(passwd)
#different methods (you only have to give the #first six hex characters for the hash):MD5, SHA-1, SHA-256, SHA-512, DES #MD5 SHA1 SHA256 SHA512 DES #Also note the number hex characters that the hashed value uses:MD5, Sun MD5, SHA-1, SHA-256, SHA-512 ############# from passlib.hash import md5_crypt, sun_md5_crypt, sha1_crypt, sha256_crypt, sha512_crypt, des_crypt words = ["hello"] salt = "ZDzPE45C" for x in words: print("Hashes for \"" + x + "\":") md5 = md5_crypt.using(salt=salt).hash(x) print("MD5: " + md5) sha1 = sha1_crypt.using(salt=salt).hash( x) # .encrypt deprecatyed, using hash instead print("SHA1: " + sha1) sha256 = sha256_crypt.using(salt=salt).hash(x) print("SHA256: " + sha256) sha512 = sha512_crypt.using(salt=salt).hash(x) print("SHA512: " + sha512_crypt.using(salt=salt).hash(x)) des = des_crypt.using(salt=salt[:2]).hash(x) # first 2 chars of salt print("DES: " + des) print("") print("Hex length for \"" + x + "\":") print("MD5: " + str(len(md5))) print("Sun MD5: " + str(len(sun_md5_crypt.using(salt=salt).hash(x)))) print("SHA-1: " + str(len(sha1))) print("SHA-256: " + str(len(sha256))) print("SHA=512: " + str(len(sha512)))
def init_crypt(secret): try: crypt = sha512_crypt.using(salt=secret) return True except RuntimeError: return False
sys.exit('You can not continue process!!!!!') ssh_port = input("Please type port for ssh port(default: 22): ") hacluster_pass = getpass.getpass("Please type password of user hacluster: ") disk_name = input("Please type name of disk: ") name_of_vg = input("Please type name of volume group: ") name_of_lv = input("Please type name of logical volume: ") folder_name = input("Please type name of folder: ") cluster_name = input("Please type name of cluster name: ") hacluster_user = "******" hacluster_user_password = hacluster_pass worker_ip_list = input("Please type list of workers ip: ") vcenter_ip = ip_address_vcenter vcenter_user = input("Please type name of vcenter user for fencing: ") vcenter_password = getpass.getpass("Please type password of vcenter user: "******"" or ssh_port == "22": ssh_port = "22" elif ssh_port != "": ssh_port = ssh_port if not os.path.exists('/tmp/test'): os.mknod('/tmp/test') with open('inventory', 'a') as the_host_file: the_host_file.write('[VMs]\n') for hostname in data_worker_list: the_host_file.write(hostname + "\n") the_host_file.write('\n') the_host_file.write('[all_workers]\n')
import crypt from passlib.hash import sha512_crypt def randomString(stringLength=6): """Generate a random string of letters and digits """ lettersAndDigits = string.ascii_lowercase + string.digits return ''.join( random.choice(lettersAndDigits) for i in range(stringLength)) if len(sys.argv) != 2: print("Wrong input") sys.exit(-1) account_list = [] with open('main.yml', 'w') as the_file: the_file.write("Accounts:\n") for i in range(1, int(sys.argv[1])): pw = randomString() pw_hash = sha512_crypt.using(rounds=5000).hash(pw) the_file.write(" - name: " + 'user' + str(i) + "\n") the_file.write(" password: "******"\n") the_file.write(" pw_clr: " + pw + "\n") account_list.append(('user' + str(i), pw)) for account in account_list: print(account[0]) print(account[1]) print("")
from flask import Blueprint, make_response, jsonify from flask_httpauth import HTTPBasicAuth, HTTPDigestAuth from passlib.hash import sha512_crypt from models.User import User as User from utils.Logger import Logger as Logger import os api = Blueprint('api', __name__, static_folder='static', template_folder='templates') auth = HTTPBasicAuth() logger = Logger() crypt = sha512_crypt.using( salt=os.getenv('SECRET_KEY')[:15] or 'NOT_A_SAFE_SECRET') # @auth.get_password # def get_password(user): # user = User.query.filter_by(username=user).first() # if user is None: # return None # return user.password # @auth.get_password # def get_password(user): # user = User.query.filter_by(username=user).first() # if user is None: # return None # hashed_pass = pwd_context.hash(HTTPDigestAuth.get_password()) # if hashed_pass == user.password:
def _encrypt(self, clearvalue, salt=None): rounds = param_tools.get_global_parameter("rounds_number") sha512_crypt.using(rounds=rounds) return sha512_crypt.hash(clearvalue)
from passlib.hash import sha512_crypt p = raw_input("Password:"******"Salt:") print sha512_crypt.using(salt=s, rounds=5000).hash(p)
#! /usr/bin/python # This script hashes a password, read from the terminal, using the SHA512 # algorithm, which allows it to be used as an Ansible compatible password # hash (in the "inventory" file or other variable for example) # from passlib.hash import sha512_crypt import getpass p = getpass.getpass() print "Password: "******"Hash: " + sha512_crypt.using(rounds=5000).hash(p)
# Copyright 2019, Kay Hayen, mailto:[email protected] # # Python test originally created or extracted from other peoples work. The # parts from me are licensed as below. It is at least Free Software where # it's copied from other people. In these cases, that will normally be # indicated. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from passlib.hash import sha512_crypt as sha512 # nuitka-skip-unless-imports: passlib print("hello") print(len(sha512.using(rounds=1000).hash("password"))) print("bye")
#Written for python 2 #For import run `pip install passlib` from passlib.hash import sha512_crypt chars = "0123456789" salts = {"msH6N3AG", "HFp/Mlc0", "g8FtcZYm", "mMHjRszK", "Q3MJoO84"} file = open("Assets/passwords2.txt", "w") for i in range(len(chars)): for j in range(len(chars)): for k in salts: p = "secure" + chars[i] + chars[j] hash = sha512_crypt.using(salt=k, rounds=5000).hash(p) file.write(p + " " + hash + "\n") print p, hash
def _encrypt_password(password): salt = environ['SALT'] hash_result = sha512_crypt.using(salt=salt, rounds=5000).hash(password) hashed_password_index = hash_result.rindex('$') + 1 return hash_result[hashed_password_index:]
# COMP3550-1 Lab1 # MacchiaroliM 5-17-2020 # Question C1 ############# #Create a Python script to create the SHA #hash for the following: "changeme","123456","password" #Prove them against on-line SHA generator #(or from the page given above). ############# from passlib.hash import sha1_crypt, sha256_crypt, sha512_crypt words = ["changeme", "123456", "password"] salt = "8sFt66rZ" for x in words: print("Hashes for \"" + x + "\":") print("SHA1 Hash: " + sha1_crypt.using( salt=salt).hash(x)) # .encrypt deprecatyed, using hash instead print("SHA256 Hash: " + sha256_crypt.using( salt=salt).hash(x)) # .encrypt deprecatyed, using hash instead print("SHA512 Hash: " + sha512_crypt.using( salt=salt).hash(x)) # .encrypt deprecatyed, using hash instead
#!/usr/bin/python3 import passlib from passlib.hash import sha512_crypt import itertools # having_shadow = "$6$O/yIOqMzCqpyFbng$FPPwWLu/uDXtb5nVYFJrQfga2lh5rpunYTRNCwxDV6YTFq7x1OISxyTYlRzpcu5VyF1gF9tSx2fCLa.nwkNLx." # generated_shadow = sha512_crypt.using(salt="O/yIOqMzCqpyFbng", rounds=5000).hash("passw0rd") # if having_shadow == generated_shadow: # print(generated_shadow + " is equal to " + having_shadow) #else: # print(generated_shadow + " is wrong") # chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ÆæØøÅå" # the above chars can be used for a larger search chars = "1234567890" salt = "penguins" password = "******" for arr in itertools.permutations(list(chars), r=3): perm = ''.join(arr) test = sha512_crypt.using(salt=salt, rounds=5000).hash(perm) if test == password: print("******************************") print("The password is %s" % perm) print("******************************") break # The password is 479
from __future__ import print_function from tornado.testing import AsyncTestCase, AsyncHTTPClient, gen_test from tornado.escape import json_encode TEST_URL = "http://127.0.0.1:8083/ansible/task" user_info = {'remote_user': '******', 'conn_pass': '******'} host = ['172.16.251.101'] from passlib.hash import sha512_crypt password = sha512_crypt.using(rounds=5000).hash('123123') class UserTest(AsyncTestCase): @gen_test(timeout=60) def test_add_user(self): post_data = { 'user_info': json_encode(user_info), 'host': host, 'module': 'user', 'state': 'absent', 'name': 'test1', 'password': password } client = AsyncHTTPClient(self.io_loop) response = yield client.fetch(TEST_URL, method='POST', body=json_encode(post_data)) print(response.body)
def encrypt_password(password, salt=None): from passlib.hash import sha512_crypt if password: return sha512_crypt.using(rounds=5000).hash(password, salt=salt) return None
#!/usr/bin/env python from passlib.hash import sha512_crypt import getpass print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))