예제 #1
0
def send_response(rid, api, status=True, data=""):
    print "> Response:",data
    tmp = {"status" : status, "data" : data}

    body = encode(json.dumps(tmp))

    enc = hashlib.sha3_512()
    enc.update(body)

    msg_sig = hashlib.sha3_512()
    msg_sig.update("%s%s%s" % (api, enc.hexdigest(), body))

    return "%s:%s:%s:%s" % (rid, api, msg_sig.hexdigest(), body)
예제 #2
0
def sign_up():
    if request.method == 'GET':
        return render_template('sign_up.html')
    elif request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        fb_email = request.form['fb_email']
        email = request.form['email']

        if not first_name or not last_name or not fb_email or not email:
            flash(u'Please fill out all required fields', 'error')
            return render_template('sign_up.html')

        u = User(first_name=first_name, last_name=last_name, fb_email=fb_email,email=email)

        if not mongo.check_user(u.fb_email):  
            s = hashlib.sha3_512()
            s.update((secret+u.email).encode('utf-8'))
            token = s.hexdigest()
            mongo.signed_up(u)
            mailgun.send_verification(u, token)
            return render_template('verify.html')

        else:
            flash('%s, we see you have already signed up! Please log in.' % (first_name), "success")
            return redirect('/')

    else:
        return render_template('404.html'), 404
예제 #3
0
파일: files.py 프로젝트: downpoured/pyxels
def hasherFromString(s):
    import hashlib
    if s == 'sha1':
        return hashlib.sha1()
    elif s == 'sha224':
        return hashlib.sha224()
    elif s == 'sha256':
        return hashlib.sha256()
    elif s == 'sha384':
        return hashlib.sha384()
    elif s == 'sha512':
        return hashlib.sha512()
    elif s == 'blake2b':
        return hashlib.blake2b()
    elif s == 'blake2s':
        return hashlib.blake2s()
    elif s == 'md5':
        return hashlib.md5()
    elif s == 'sha3_224':
        return hashlib.sha3_224()
    elif s == 'sha3_256':
        return hashlib.sha3_256()
    elif s == 'sha3_384':
        return hashlib.sha3_384()
    elif s == 'sha3_512':
        return hashlib.sha3_512()
    elif s == 'shake_128':
        return hashlib.shake_128()
    elif s == 'shake_256':
        return hashlib.shake_256()
    else:
        return None
예제 #4
0
def check_pwd(request, fid, target):
    """
        Check if the file is protected by a key.
        If yes, check the password and redirect 
        to the password template if wrong.

    """
    # Get the file description
    f = get_object_or_404(File, id=fid)
    # If it is protected by a password
    if f.key is not None:
        # Try to get the password from GET
        if "key" in request.GET.keys():
            pwd = request.GET["key"]
        # Try to get the password from POST
        elif "key" in request.POST.keys():
            pwd = request.POST["key"]
        # If no password provided, return password view
        else:
            ctxt = dict()
            ctxt["target"] = target
            return (False, render(request, "website/enter_pwd.html", ctxt))
        # If the password is not correct, return an error
        if hashlib.sha3_512(pwd.encode("utf-8")).hexdigest() != f.key:
            ctxt = dict()
            ctxt["target"] = reverse('download', kwargs={ 'fid': fid})
            ctxt["wrong_pwd"] = True
            return (False, render(request, "website/enter_pwd.html", ctxt))
        return (True, pwd)
    return (True, "")
예제 #5
0
 def go():
     run = 'y'
     while run != 'n':
         mystring = input('''
 PLEASE ENTER A STRING TO HASH:  ''')
         md5_hash_object = hashlib.md5(mystring.encode())
         print('''   
 MD5 HASH:
 -----------------------------------
 ''',md5_hash_object.hexdigest())
         sha1_hash_object = hashlib.sha1(mystring.encode())
         print('''
 SHA-1 HASH:
 -----------------------------------
 ''',sha1_hash_object.hexdigest())
         sha256_hash_object = hashlib.sha256(mystring.encode())
         print('''
 SHA-256 HASH:
 -----------------------------------
 ''',sha256_hash_object.hexdigest())
         sha512_hash_object = hashlib.sha512(mystring.encode())
         print('''
 SHA-512 HASH:
 -----------------------------------
 ''',sha512_hash_object.hexdigest())
         sha3_hash_object = hashlib.sha3_512(mystring.encode())
         print('''
 SHA-3 HASH:
 -----------------------------------
 ''',sha3_hash_object.hexdigest())                           
         run = input('''
 ------------------
 RUN ANOTHER? (y/n) ''')
     return
예제 #6
0
 def sha3_512Encode(self, text):
     if not os.path.isfile(str(text)):
         if not text:
             return "No String passed to method"
         else:
             m = hashlib.sha3_512()
             m.update(text.encode('utf-8'))
             return (m.hexdigest())
     else:
         BLOCKSIZE = 65536
         hasher = hashlib.sha3_512()
         with open(text, 'rb') as afile:
             buf = afile.read(BLOCKSIZE)
             while len(buf) > 0:
                 hasher.update(buf)
                 buf = afile.read(BLOCKSIZE)
         return (hasher.hexdigest())
예제 #7
0
 def test_sha3512(self):
     """
     Test SHA3-512 hash.
     """
     if "sha3_512" not in hashlib.algorithms_available:
         pass
     else:
         assert bh.hashlib_hash("tempfile.txt", hashlib.sha3_512()) == "2ca12b585486d0f775f9fd438a73525b37b1214bc36a8b0ae611d0f1261e8d32b47b923b406c46cc80cc178598d41d42abee3eae5b1c23164b817342e22580e2"
예제 #8
0
파일: stupor.py 프로젝트: junkert/stupor
def hash(file_path):
    global chunk_size
    if os.path.exists(file_path):
        f = open(file_path, 'rb+')
        file_hash = sha3_512(f.read(chunk_size)).hexdigest()
        f.close()
    else:
        file_hash = None
    return (file_hash, file_path)
예제 #9
0
def keystream(seedHandle,size):
    s = hashlib.sha3_512()
    seed = 0
    previousHash = ''
    try:
        byte = seedHandle.read(65536)
        while byte != "":
            s.update(byte)
            byte = seedHandle.read(65536)
    finally:
        previousHash = hash = s.hexdigest()
        seed = bitstring.BitArray(hex=hash).bin

    while len(seed) < size:
        s = hashlib.sha3_512()
        s.update(previousHash)
        previousHash = hash = s.hexdigest()
        seed = str(seed) + str(bitstring.BitArray(hex=hash).bin)
    return bitstring.BitArray(bin=seed).bin[0:size]
예제 #10
0
def sha3_512(fname, blocksize=4096):
    '''Вычисление хэш суммы файла, считывая порциями по blocksize байт'''
    hash_sha3_512 = hashlib.sha3_512()
    try:
        with open(fname, "rb") as f:
            for chunk in iter(lambda: f.read(blocksize), b""):
                hash_sha3_512.update(chunk)
        return hash_sha3_512.hexdigest()
    except IOError as e:
        print(e)
        return None
예제 #11
0
파일: views.py 프로젝트: Frky/freespeech
def create_comptoir(request):
    global comptoir_created

    context = RequestContext(request)
    context['registerForm'] = RegisterForm()
    context['version'] = VERSION
    form = ComptoirForm(request.POST or None)

    if form.is_valid():
        data = form.cleaned_data

        if request.user.is_authenticated and str(request.user) != "AnonymousUser":
            user = request.user
        else:
            user = None

        if not data['public'] and (data['key_hash'] is None or data['key_hash'] == ""):
            form._errors['key_hash'] = ErrorList("This field is requested to create a private comptoir.")
            messages.warning(request, "Comptoir not created: no hash given.")
            return index(request)
        if data['public']:
            key = "ff" * 32
            sha = hashlib.sha3_512()
            sha.update(key)
            data['key_hash'] = sha.hexdigest()
        new_comptoir = Comptoir(owner=user,
                                title=data['title'],
                                description=data['description'],
                                public=not data['public'],
                                key_hash=data['key_hash'],
                                title_is_ciphered=True)

        new_comptoir.save()

        lv = LastVisit(comptoir=new_comptoir)
        lv.save()
        request.user.chatuser.last_visits.add(lv)
        request.user.comptoirs.append((new_comptoir, 0))

        messages.success(request,
                         "The comptoir has been created successfully. You can access your comptoirs by clicking on your nickname.")

        # Global variable set to True to distinguish between form with error
        # (that will be filled by index) and form treated that as to be cleaned up
        comptoir_created = True

        return HttpResponse("cid_" + str(new_comptoir.id))
        # return redirect("join_comptoir", new_comptoir.id)

    else:
        messages.warning(request, "Comptoir not created: some errors in the form.")

        return index(request)
예제 #12
0
파일: code.py 프로젝트: 21donut/img.bi-api
 def POST(self):
   web.header('Access-Control-Allow-Origin', '*')
   try:
     data = web.input()
   except ValueError:
     web.header("Content-Type", "application/json")
     return json.dumps({"status": "File is too large"})
   if not 'encrypted' in data:
     web.header("Content-Type", "application/json")
     return json.dumps({"status": "Wrong parameters"})
   try:
     json.loads(data.encrypted)
     if 'thumb' in data:
       json.loads(data.thumb)
   except ValueError:
     web.header("Content-Type", "application/json")
     return json.dumps({"status": "This is not JSON"})
   salt = r_server.get('salt')
   if salt is None:
     salt = zbase62.b2a(M2Crypto.m2.rand_bytes(25))
     r_server.set('salt', salt)
     r_server.expire('salt',86400)
   hashedip = hashlib.sha3_512(web.ctx.ip.encode('utf-8') + salt).hexdigest()
   redisip = r_server.get('ip:' + hashedip)
   if redisip is not None and int(redisip) > 100:
     web.header("Content-Type", "application/json")
     return json.dumps({"status": "Too much uploads from your IP"})
   fileid = ''.join(random.choice(string.letters + string.digits) for x in range(7))
   while r_server.get('file:' + fileid):
     fileid = ''.join(random.choice(string.letters + string.digits) for x in range(7))
   password = zbase62.b2a(M2Crypto.m2.rand_bytes(20))
   hashed = bcrypt.hashpw(password, bcrypt.gensalt())
   f = open(upload_dir + '/' + fileid,'w')
   f.write(data.encrypted)
   f.close()
   if 'thumb' in data:
     f = open(upload_dir + '/thumb/' + fileid,'w')
     f.write(data.thumb)
     f.close()
   if 'expire' in data and int(data.expire) != 0:
     try:
       delta = timedelta(days=int(data.expire))
     except:
       return json.dumps({"status": "Wrong expire date"})
     r_server.set('file:expire:' + fileid, (datetime.now() + delta).strftime('%Y-%m-%d %H:%M:%S'))
   r_server.set('file:' + fileid, hashed)
   r_server.incr('ip:' + hashedip)
   r_server.expire('ip:' + hashedip,86400)
   web.header("Content-Type", "application/json")
   return json.dumps({"id": fileid, "pass": password, "status": "OK"})
예제 #13
0
    def save(self, user):
        if user.is_anonymous():
            folder = settings.UPLOAD_DIRECTORY_ANONYMOUS
            max_dl = settings.FILE_MAX_DL_ANONYMOUS
        else:
            folder = os.path.join(user.fshare_user.permission.base_path, user.username)
            max_dl = self.cleaned_data.get('max_dl') or 1
        if not os.path.exists(folder):
            os.makedirs(folder)

        key = self.cleaned_data.get('key') or None

        uploaded_file = self.cleaned_data.get('file')
        filename_safe = smart_str(uploaded_file.name, "utf-8")

        if key is not None:
            iv, md5, filepath = encrypt_file(filename_safe, uploaded_file, folder, key)
            filename = encrypt_filename(filename_safe, key, iv)
        else:
            filepath = generate_random_path(folder)
            filename = filename_safe
            iv = None
            m = hashlib.md5()
            with open(filepath, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    m.update(chunk)
                    destination.write(chunk)
            md5 = m.hexdigest()

        new_file = File(
            owner=user if not user.is_anonymous() else None,
            title=filename,
            private_label=self.cleaned_data.get('private_label', self.cleaned_data.get('title')),
            description=self.cleaned_data.get('description'),
            path=filepath,
            checksum=md5,
            size=uploaded_file.size,
            expiration_date=compute_expiration_date(uploaded_file.size),
            key = hashlib.sha3_512(key.encode("utf-8")).hexdigest() if key is not None else None,
            iv = iv.decode("utf-8") if iv is not None else None,
            max_dl = max_dl,
        )

        pwd = self.cleaned_data.get('pwd') or None
        if new_file.is_private:
            new_file.pwd = pwd

        new_file.save()
        return new_file
예제 #14
0
    def create_public_key(self, bits=2048):
        charlist = digits+ascii_uppercase+ascii_lowercase
        pairs = []

        char = ""

        for a in charlist:
            for b in charlist:
                char = ""
                char = a+b

                if char.lower() != a+b:
                    pairs.extend([char])

        return b64encode(hashlib.sha3_512(str(random.getrandbits(bits))).digest(), random.choice(pairs)).rstrip('==').replace("/","")
예제 #15
0
    def make_request(self, id, req, pub, priv):
        tmp = req.split(" ")
        cmd = tmp[0]
        args = []

        enc = hashlib.sha3_512()
        enc.update(priv.encode('utf-8'))

        try:
            args = tmp[1:]
        except:
            pass

        body = encode("%s" % (json.dumps({"cmd" : cmd, "args" : args})))
        
        msg_sig = hmac.new(str(priv), body, hashlib.sha512)
        self.redis.set("%s" % id, msg_sig.hexdigest())

        return "%s:%s:%s:%s" % (id, pub, msg_sig.hexdigest(), body)
예제 #16
0
def get_engine(hashtype):
    """
    Get hashlib engine from hash type.

    :param hashtype: Hash type.
    :type hashtype: str
    """
    hashengines = {"md5": hashlib.md5(),
                   "sha1": hashlib.sha1(),
                   "sha224": hashlib.sha224(),
                   "sha256": hashlib.sha256(),
                   "sha384": hashlib.sha384(),
                   "sha512": hashlib.sha512()}
    if utilities.new_enough(6):
        hashengines.update({"sha3224": hashlib.sha3_224(),
                            "sha3256": hashlib.sha3_256(),
                            "sha3384": hashlib.sha3_384(),
                            "sha3512": hashlib.sha3_512()})
    return hashengines[hashtype]
예제 #17
0
파일: coupon.py 프로젝트: zhchen6688/test02
def hash_demo():
    m = hashlib.md5()
    # m.update(b"hello")
    # m.update(b"world!")  # = hello + world!
    m.update(b'python isinteresting')
    hash_hex = hashlib.sha3_512(b"python isinteresting").hexdigest()
    print(m.digest_size)
    print(m.digest())     # 二进制hash
    print(m.hexdigest())  # 十六进制hash
    print(hash_hex)       # SHA 512哈希加密算法

    '''
    密码加盐。
    盐是一个添加到用户的密码哈希过程中的一段随机序列。这个机制能够防止通过预先计算结果的彩虹表破解。
    每个用户都有自己的盐,这样的结果就是即使用户的密码相同,通过加盐后哈希值也将不同。
    为了校验密码是否正确,我们需要储存盐值。通常和密码哈希值一起存放在账户数据库中,或者直接存为哈希字符串的一部分。
    '''
    # 加盐加密
    hash_bytes = hashlib.pbkdf2_hmac('sha256', b'python isinteresting', b'80', 100000)
    print(hash_bytes)
예제 #18
0
def verify_token():
    email = request.args.get('email', '')
    token = request.args.get('token', '') 

    user = mongo.verified(email)

    if user:
        u = User.from_json(user)

        s = hashlib.sha3_512()
        s.update((secret+u.email).encode('utf-8'))

        if s.hexdigest() == token:
            mongo.add_user(u)
            mailgun.add_list_member(u)
            session['email'] = u.email
            flash('Welcome %s, thanks for signing up!' % (u.first_name), "success")
            mongo.delete_verified(u.email)
            return redirect('/find_symptoms')
    flash('We could not verify this email', 'error')
    return render_template('404.html')
예제 #19
0
def calculate_model_key(model_config: dict,
                        data_config: dict,
                        metadata: Optional[dict] = None) -> str:
    """
    Calculates a hash-key from a model and data-config.

    Notes
    -----
    Ignores the data_provider key since this is an complicated object.

    Parameters
    ----------
    model_config: dict
        Config for the model. See
        :func:`gordo_components.builder.build_model.build_model`.
    data_config: dict
        Config for the data-configuration. See
        :func:`gordo_components.builder.build_model.build_model`.
    metadata: Optional[dict] = None
        Metadata for the models. See
        :func:`gordo_components.builder.build_model.build_model`.

    Returns
    -------
    str:
        A 512 byte hex value as a string based on the content of the parameters.

    Examples
    -------
    >>> len(calculate_model_key(model_config={"model": "something"},
    ... data_config={"tag_list": ["tag1", "tag 2"]} ))
    128
    """
    if metadata is None:
        metadata = {}
    # TODO Fix this when we get a good way of passing data_provider in the yaml/json
    if "data_provider" in data_config:
        logger.warning(
            "data_provider key found in data_config, ignoring it when creating hash"
        )
        data_config = dict(data_config)
        del data_config["data_provider"]

    # Sets a lot of the parameters to json.dumps explicitly to ensure that we get
    # consistent hash-values even if json.dumps changes their default values (and as such might
    # generate different json which again gives different hash)
    json_rep = json.dumps(
        {
            "model_config": model_config,
            "data_config": data_config,
            "user-defined": metadata,
        },
        sort_keys=True,
        default=str,
        skipkeys=False,
        ensure_ascii=True,
        check_circular=True,
        allow_nan=True,
        cls=None,
        indent=None,
        separators=None,
    )
    return hashlib.sha3_512(json_rep.encode("ascii")).hexdigest()
예제 #20
0
 def __init__(self, **kwargs):
     super().__init__('sha3-512', hashlib.sha3_512(), **kwargs)
 def _hash_crawl_arg(self, crawl_arg):
     return 'sha3-512:' + hashlib.sha3_512(crawl_arg.encode('utf-8')).hexdigest()
예제 #22
0
 def api_key(self, plaintext_api_key: str) -> str:
     self.api_key_hash = hashlib.sha3_512(
         plaintext_api_key.encode(),
         usedforsecurity=True
     ).hexdigest()
예제 #23
0
     print("\n")

     pass_hash = input(Fore.CYAN+"ENTER sha3_512 HASH: ")
     wordlist = input("ENTER NAME OF THE FILE: ")

     try:
        pass_file = open (wordlist, "r")
     
     except:
         cprint("CANNOT FIND THE FILE!! YOUR FILE SHOULD BE IN THE SAME DIRECTORY THAT YOU ARE RUNNING THIS PYTHON SCRIPT",'red')
         quit()
    
     for word in pass_file:

         enc_wrd = word.encode('utf-8')
         digest = hashlib.sha3_512(enc_wrd.strip()).hexdigest()

         if digest == pass_hash:
             print("Your Password is",)
             cprint(word)
             flag = 1
             break

     if  flag ==0:
         cprint("password not found );")

 if selection == 15:
     cprint("scrypt is now selected")

     print("\n")
 def get_hash(self):
     return hashlib.sha3_512(self.encode_content_as_bytes()).hexdigest()
예제 #25
0
 def sha3_512(self, text, salt=''):
     return hashlib.sha3_512((text + salt).encode('UTF-8')).hexdigest()
예제 #26
0
파일: license.py 프로젝트: nakamura9/latrom
    def __call__(self, request):
        """
        Checks that each request is within the limits of the purchased license.
            1. Checks that the users are not using the same account on multiple 
                machines.
            2. Verifies that the license file has not been tampered with.
        """

        #condition is evaluated to ensure an infinite loop is avoided
        if request.path.startswith('/base/license-error') or \
                'api' in request.path or \
                request.path.startswith('/admin') or \
                request.path.startswith('/base/reset-license-check'):
            return self.get_response(request)

        try:
            TRACKER.track_user(request)
        except UserTrackerException:
            return HttpResponseRedirect('/base/license-error/users')

        license = None
        try:
            #installer requires license in top level directory
            with open('../license.json', 'r') as f:
                license = json.load(f)

        except FileNotFoundError:
            logger.critical('The license file is not found')
            return HttpResponseRedirect('/base/license-error-page')

        data_string = json.dumps(license['license'])
        byte_data = bytes(data_string, 'ascii')
        hash = hashlib.sha3_512(byte_data).hexdigest()

        if not hmac.compare_digest(hash, license['signature']):
            logger.critical('the license hash check has failed')
            return HttpResponseRedirect('/base/license-error-page')

        #check with remote server every three days
        config = GlobalConfig.objects.get(pk=1)
        #not settings.DEBUG and
        if (config.last_license_check == None or \
                (datetime.date.today() - \
                config.last_license_check).days > 2):

            if config.verification_task_id == '':
                # if not generate that task and store the task id
                task = remote_license_verification(license)
                config.verification_task_id = task.task_hash
                config.save()
                return self.get_response(request)

            else:
                if CompletedTask.objects.filter(
                        task_hash=config.verification_task_id).exists():
                    task = CompletedTask.objects.filter(
                        task_hash=config.verification_task_id).latest('pk')
                    if task.attempts > 0:
                        return HttpResponseRedirect('/base/license-error-page')
                    else:
                        return self.get_response(request)
                else:
                    return self.get_response(request)
        else:
            return self.get_response(request)
예제 #27
0
파일: crypto.py 프로젝트: aldur/Arcula
def sha3_512_half(m: bytes) -> bytes:
    """Return the SHA3_512_half digest of the provided message."""
    h = hashlib.sha3_512()
    h.update(m)
    d = h.digest()
    return d[:len(d) // 2]
예제 #28
0
파일: crypto.py 프로젝트: aldur/Arcula
def sha3_512(m: bytes) -> bytes:
    """Return the SHA3_512 digest of the provided message."""
    h = hashlib.sha3_512()
    h.update(m)
    return h.digest()
예제 #29
0
import hashlib

# encode it to bytes using UTF-8 encoding

message = "My name is Erick".encode()

# hash with SHA-3
print("SHA-3-256:", hashlib.sha3_256(message).hexdigest())

print("SHA-3-512:", hashlib.sha3_512(message).hexdigest())
예제 #30
0
 def hash(self, block):
     encoded_block = json.dumps(block, sort_keys=True).encode()
     return hashlib.sha3_512(encoded_block).hexdigest()
예제 #31
0
파일: PySha.py 프로젝트: mrtnRitter/PySha
allfiles = str(f"{(sum(len(files) for _, _, files in os.walk(startpath))):,}")

print(allfiles + " files found!\n")

for root, dirs, files in os.walk(startpath):

    for filename in files:

        filepath = Path(root).joinpath(filename)

        #filesize = str("{:.2f}".format(os.path.getsize(filepath)/(1024**3)))

        filesize = str("{:.2f}".format((filepath.stat().st_size) / (1024**3)))

        file_hash = hashlib.sha3_512()

        filesdone += 1

        print("Processing file " + str(f"{filesdone:,}") + " of " + allfiles)

        with open(filepath, "rb") as file:

            for i in itertools.count():
                data = file.read(Buf_size)

                currentsize = str("{:.2f}".format(i * (Buf_size / (1024**3)),
                                                  2))

                print("Reading " + currentsize + "GB of " + filesize +
                      "GB from " + filename,
예제 #32
0
# res=input('signup or login :-')
answer = inquirer.prompt([
    inquirer.List('ans',
                  message="Do you want to ",
                  choices=['Login', 'Signup'])
])  #Asking through Inquirer
res = answer['ans']
if res == 'Signup':
    passwd = getpass.getpass('Enter Password: '******'utf-8')
    hashin_method(passwd)

elif res == 'Login':
    decrypt_file()
    hash_n = hashlib.sha3_512(
        getpass.getpass('Enter Password: '******'utf-8'))  #pass password from tkinter here
    f = open('hakuna.txt', 'r')
    if f.readline().strip() == hash_n.hexdigest():
        f.close()
        print('\n ~~~~~~~~~~~~Welcome To Your Vault~~~~~~~~~~~ \n'
              )  #tkinter loginpage
        ans = inquirer.prompt([
            inquirer.List('ans',
                          message="You want to ",
                          choices=['Enter a new entry', 'View your Passwords'])
        ])
        resp = ans['ans']
        if resp == 'Enter a new entry':  #tkinter enter new item page
            enter_new()
        if resp == 'View your Passwords':  #tkinter show list page
예제 #33
0
 def test_hashlib_sha3(self):
     import hashlib
     import sha3
     self.assertIsNotNone(hashlib.sha3_512())
     self.assertIsNotNone(sha3.keccak_512())
예제 #34
0
    DEFAULT_CAT_CONFIG = {}
    INCLUDE_TEXT = "include"
    EXCLUDE_TEXT = "exclude"
    DEFAULT_CAT_REGISTER = {
        INCLUDE_TEXT: [],
        EXCLUDE_TEXT: {t: list()
                       for t in EXCLUDES_TYPES}
    }
    DEFAULT_SUBCMD = "backup"
    MEMORY_PWD = os.path.join(os.path.expanduser("~"), ".memory_pwd")


if not os.path.isfile(GlobalConstants.MEMORY_PWD):
    import hashlib
    with open(GlobalConstants.MEMORY_PWD, "w") as f:
        f.write(hashlib.sha3_512(os.urandom(2048)).hexdigest())


def cmd_get_output(cmd, **kwargs):
    p = subprocess.Popen(__prep_popen_cmd(cmd),
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.DEVNULL,
                         **kwargs)
    return p.communicate()[0]


def call_cmdline(cmd,
                 stdout=subprocess.DEVNULL,
                 stderr=subprocess.DEVNULL,
                 **kwargs):
예제 #35
0
def main():
    virtualbox_xidl = 'VirtualBox.xidl'
    config_kmk = 'Config.kmk'

    print("Create new virtualbox/library.py")
    xidl = open(virtualbox_xidl, 'rb').read()
    xidl = preprocess(xidl, target=b'xpidl')

    xml = minidom.parseString(xidl)

    # Get the idl description
    idl = xml.getElementsByTagName('idl')
    assert len(idl) == 1
    idl = idl[0]
    lib_doc = '''__doc__ = """\\\n  %s\n"""\n\n''' % get_doc(idl, 0)

    # Process the library

    library = xml.getElementsByTagName('library')
    assert len(library) == 1
    library = library[0]

    # 5.2 introduced <library><application> ... </application></library>
    applications = xml.getElementsByTagName('application')
    if applications:
        for application in applications:
            name = application.attributes.get('name', None)
            if name is not None:
                if "VirtualBox" == name.value:
                    break
        else:
            raise ValueError("Failed to find VirtualBox application")
        app_uuid = application.getAttribute('uuid')
        virtualbox_application = application
    else:
        app_uuid = library.getAttribute('appUuid')
        virtualbox_application = library

    # Iterate each element under the virtualbox application node
    source = dict(result=[], enum=[], interface=[])
    for node in virtualbox_application.childNodes:
        name = getattr(node, 'tagName', None)
        if name is None:
            continue
        if name == 'result':
            source['result'].append(process_result_node(node))
        elif name == 'enum':
            source['enum'].append(process_enum_node(node))
        elif name == 'interface':
            source['interface'].append(process_interface_node(node))

    # Add OLE errors to 'result'
    for args in OLE_ERRORS:
        source['result'].append(build_error_result(*args))

    #get lib meta
    vbox_version = get_vbox_version(config_kmk)
    uuid = library.getAttribute('uuid')
    version = library.getAttribute('version')
    xidl_hash = hashlib.sha3_512(xidl).hexdigest()
    lib_meta = LIB_META % dict(vbox_version=to_string(vbox_version),
                               uuid=to_string(uuid),
                               version=to_string(version),
                               app_uuid=to_string(app_uuid),
                               xidl_hash=to_string(xidl_hash))

    code = []
    code.append(LIB_IMPORTS)
    code.append(lib_doc)
    code.append(lib_meta)
    code.append(LIB_DEFINES)
    code.extend(source['result'])
    code.extend(source['enum'])
    code.extend(source['interface'])
    code = b"\n".join(
        [c.encode('utf-8') if not isinstance(c, bytes) else c for c in code])
    print("   vbox version : %s" % to_string(vbox_version))
    print("   xidl hash    : %s" % xidl_hash)
    print("   version      : %s" % version)
    print("   line count   : %s" % code.count(b"\n"))
    library_path = os.path.join('.', 'virtualbox', 'library.py')
    if os.path.exists(library_path):
        os.unlink(library_path)
    with open(library_path, 'wb') as f:
        f.write(code)
예제 #36
0
    xorIPad = b''
    for i in range(len(paddedName2Key)):
        xorIPad += bytes([paddedName2Key[i] ^ iPad[0]])

    # k ⊕ opad
    xorOPad = b''
    for i in range(len(paddedName2Key)):
        xorOPad += bytes([paddedName2Key[i] ^ oPad[0]])

    # generate the pdf file bytes
    pdfBytes = b''
    f = open("netsec2016_exercise_sheet_05.pdf", "rb")
    try:
        while True:
            b = f.read(1)
            if not b:
                break
            pdfBytes += b
    finally:
        f.close()

    # (k ⊕ ipad) || m
    xorIPadM = b''
    xorIPadM = xorIPad + pdfBytes

    # h( (k ⊕ ipad) || m ) with sha3_512
    hashXorIPadM = hashlib.sha3_512(xorIPadM).digest()

    # h(k ⊕ opad || h(k ⊕ ipad || m))
    hmac = hashlib.sha3_512(xorOPad + hashXorIPadM).digest()
    print ("hmac:{0}".format(hmac))
예제 #37
0
    elif alg == 'sha256':
        hs = hashlib.sha256(block_str.encode()).hexdigest()
    elif alg == 'sha384':
        hs = hashlib.sha384(block_str.encode()).hexdigest()
    elif alg == 'sha512':
        hs = hashlib.sha512(block_str.encode()).hexdigest()
    elif alg == 'MD5':
        hs = hashlib.md5(block_str.encode()).hexdigest()
    elif alg == 'SHA3-224':
        hs = hashlib.sha3_224(block_str.encode()).hexdigest()
    elif alg == 'SHA3-256':
        hs = hashlib.sha3_256(block_str.encode()).hexdigest()
    elif alg == 'sha3-384':
        hs = hashlib.sha3_384(block_str.encode()).hexdigest()
    elif alg == 'SHA3-512':
        hs = hashlib.sha3_512(block_str.encode()).hexdigest()
    
    if hs[:cz] == '0'*cz:
        block['hash'] = hs
        break

    nonce += 1
answer = f'\nAnswer: {json.dumps(block, separators=(",", ":"), indent=4)}'

with open(f'{os.path.dirname(__file__)}/Tasks.txt', 'a', encoding='UTF') as f:
    f.write('Задание 2\n')
    f.write(text_of_task)
    f.write('\n\n\n')

with open(f'{os.path.dirname(__file__)}/Answers.txt', 'a', encoding='UTF') as f:
    f.write('Задание 2\n')
예제 #38
0
    def seal_send(msg, receiver_pub_key, symm_key_K, sym_system_type,
                  sym_system_mode, self_private_key, sha_format):
        print("  ////////Proces slanja pečata.////////")

        # Odabran je proizvoljni simetrični ključ K u pripadnoj metodi gdje je ključ generiran.
        # Ključ može biti generiran u AESImplementation.generate_key_k() ili DESImplementation.generate_key_k().
        print("     Odabran je ključ 'K': {}".format(symm_key_K))

        # C1 = DES (ili AES) (P, K).
        print(
            "     Kriptiraj tekst P simetričnom funkcijom {}. Rezultat je poruka C1."
            .format(sym_system_type))
        print("         ==== >  C1 = {}(P, K)".format(sym_system_mode))
        print("         Tekst P: {}.".format(msg))
        print("             {} - {} enkripcija....".format(
            sym_system_type, sym_system_mode))
        if sym_system_type == "DES3":
            encrypted_message_C1 = DES3Implementation.des3_encrypt(
                msg, symm_key_K, sym_system_mode)
        else:  # else AES
            encrypted_message_C1 = AESImplementation.aes_encrypt(
                msg, symm_key_K, sym_system_mode)
        print("         Dobivena enkriptirana poruka C1:{}".format(
            encrypted_message_C1))

        print(
            "     Javnim ključem primatelja KE kriptiraj tajni ključ K. Rezultat je poruka C2."
        )
        print("         ==== >  C2 = RSA(K, KE)")
        print("         Javni ključ primatelja KE: {}.".format(
            receiver_pub_key.export_key()))
        print("         Tajni ključ  K: {}.".format(symm_key_K))
        print("             RSA enkripcija....")
        encryptor_RSA = PKCS1_OAEP.new(receiver_pub_key)  # RSA.
        encrypted_message_C2 = encryptor_RSA.encrypt(symm_key_K)
        print("         Dobivena enkriptirana poruka C2:{}".format(
            encrypted_message_C2))

        print(
            "     Izračunaj sažetak poruka C1 i C2 H(C1, C2) pomoću svojeg privatnog ključa KD."
        )
        print("         ==== >  S = H(C1, C2).")
        print("             Računanje sažetka H(C1, C2)....")
        # Spoji poruke C1 i C2.
        if len(encrypted_message_C1) == 2:
            shc1c2 = \
                str(encrypted_message_C1[0])[2:-1] + \
                str(encrypted_message_C1[1])[2:-1] + str(encrypted_message_C2)[2:-1]
        else:
            shc1c2 = \
                str(encrypted_message_C1)[2:-1] + str(encrypted_message_C2)[2:-1]
        shc1c2 = bytes(shc1c2, 'utf-8')  # Ponovo pretvori u bajtove
        if sha_format == "3_256":  # Provedi sažimanje ovisno o odabranoj inačici.
            print("             Računanje sažetka pomoću SHA3-256...")
            h = int.from_bytes(sha3_256(shc1c2).digest(), byteorder='big')
        else:  # else sha3_512
            print("             Računanje sažetka pomoću SHA3-512...")
            h = int.from_bytes(sha3_512(shc1c2).digest(), byteorder='big')
        print("         Dobiveni sažetak H(C1,C2): {}".format(str(hex(h))))

        print(
            "     Generiraj potpis tako da kriptiraš sažetak poruke S = H(C1, C2) svojim privatnim ključem KD..."
        )
        print("         ==== >  sig = RSA(S, KD)")
        print("         Privatni ključ KD: {}".format(
            self_private_key.export_key()))
        print("             Generiranje potpisa...")
        # Generiraj potpis (Digni hash na potenciju d modulo n).
        signature_C3 = pow(h, self_private_key.d, self_private_key.n)
        print("         Potpis P: {}".format(str(hex(signature_C3))))

        print("         Omotnicom se šalje poruka M(C1, C2, C3).")
        print("  ////////Kraj slanja pečata.////////")
        return encrypted_message_C1, encrypted_message_C2, signature_C3
예제 #39
0
def sha3hashWord512():
    m = hashlib.sha3_512()
    m.update(toHash)
    return m.hexdigest()
예제 #40
0
def makeHash(data):
    s = hashlib.sha3_512()
    s.update(data)
    return s.hexdigest()
예제 #41
0
파일: Lab2.py 프로젝트: D13128914/Labs
# User is offered choice of input (file/string)
print("Welcome to hash checker. This program can calculate the hash of a string or file.")
question = input("Do you wish to check the hash of a string (S) or file (F)? Enter S or F: ")

# If user choses file, accept filename as input, open, read file, compute hashes
if question == "F" or question == "f":
	filename = input("Enter a file name: ")
	contents = open(filename, 'rb').read()
	yoursha1 = hashlib.sha1(contents)
	yoursha256 = hashlib.sha256(contents)
	yoursha512 = hashlib.sha512(contents)
	yoursha3224 = hashlib.sha3_224(contents)
	yoursha3256 = hashlib.sha3_256(contents)
	yoursha3384 = hashlib.sha3_384(contents)
	yoursha3512 = hashlib.sha3_512(contents)
else:
	# Prompt user to enter string and compute hashes
	guess = input("\nPlease enter a string: ")
	yoursha1 = hashlib.sha1(guess.encode())
	yoursha256 = hashlib.sha256(guess.encode())
	yoursha512 = hashlib.sha512(guess.encode())
	yoursha3224 = hashlib.sha3_224(guess.encode())
	yoursha3256 = hashlib.sha3_256(guess.encode())
	yoursha3384 = hashlib.sha3_384(guess.encode())
	yoursha3512 = hashlib.sha3_512(guess.encode())

# Convert hashes to readable form and print
print("\nYour hashes are computed as follows: ")
print("\nSHA-1:    ", yoursha1.hexdigest())
print("\nSHA-256:  ", yoursha256.hexdigest())
예제 #42
0
import file_info

public_file_block = ""

md5_hash = hashlib.md5()
sha1_hash = hashlib.sha1()
sha224_hash = hashlib.sha224()
sha256_hash = hashlib.sha256()
sha384_hash = hashlib.sha384()
sha512_hash = hashlib.sha512()
blake2b_hash = hashlib.blake2b()
blake2s_hash = hashlib.blake2s()
sha3_224_hash = hashlib.sha3_224()
sha3_256_hash = hashlib.sha3_256()
sha3_384_hash = hashlib.sha3_384()
sha3_512_hash = hashlib.sha3_512()


def reset():
    global public_file_block
    public_file_block = ""

    global md5_hash
    md5_hash = None
    md5_hash = hashlib.md5()

    global sha1_hash
    sha1_hash = None
    sha1_hash = hashlib.sha1()

    global sha224_hash
                buf = afile.read(BLOCKSIZE)
        print("SHA3-256 of",get_filename,":\n",hasher3_256.hexdigest(),"\n")

        #Calculate SHA3-384:
        BLOCKSIZE = 65536
        hasher3_384 = hashlib.sha3_384()
        with open(get_filename, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher3_384.update(buf)
                buf = afile.read(BLOCKSIZE)
        print("SHA3-384 of",get_filename,":\n",hasher3_384.hexdigest(),"\n")

        #Calculate SHA3-512:
        BLOCKSIZE = 65536
        hasher3_512 = hashlib.sha3_512()
        with open(get_filename, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher3_512.update(buf)
                buf = afile.read(BLOCKSIZE)
        print("SHA3-512 of",get_filename,":\n",hasher3_512.hexdigest(),"\n")

    if choice == "s": #calculate hashes for string
        loop += 1
        string = input("Enter string to be checked:\n")
        print("\n")

        #calculate SHA-1:
        sha1_string = hashlib.sha1(string.encode())
        print("SHA-1 of string:\n", sha1_string.hexdigest(),"\n")
예제 #44
0
def hash_sender_value(sender, value):
    s = hashlib.sha3_512()
    s.update(str(sender))
    s.update(str(value))
    return s.hexdigest()
예제 #45
0
 def _hash(self, value: str) -> str:
     return hashlib.sha3_512(value.encode(), usedforsecurity=True).hexdigest()
예제 #46
0
def __get_raw_blake2b_sha3_512_merged_hash_func(input_data):
    hash_of_input_data = hashlib.sha3_512(
        input_data).digest() + hashlib.blake2b(input_data).digest()
    return hash_of_input_data
예제 #47
0
 def create_private_key(self, salt):
     from uuid import uuid4 as uid
     return b64encode(hashlib.sha3_512("%s%s" % (salt, uid())).digest()).rstrip('==').replace("/","")
예제 #48
0
def calculateHash(password):
    crypt = hashlib.sha3_512()
    crypt.update(password.encode('utf-8'))
    return crypt.hexdigest()
예제 #49
0
 def text2hash(self, text2hash):
     enc = hashlib.sha3_512()
     enc.update(str(text2hash).encode("utf-8"))
     return enc.hexdigest()
예제 #50
0
    print("SHA512 : " + result.hexdigest())

if parsed_args.sha3_224:
    result = hashlib.sha3_224(parsed_args.word.encode())
    print("SHA3_224 : " + result.hexdigest())

if parsed_args.sha3_256:
    result = hashlib.sha3_256(parsed_args.word.encode())
    print("SHA3_256 : " + result.hexdigest())

if parsed_args.sha3_384:
    result = hashlib.sha3_384(parsed_args.word.encode())
    print("SHA3_384 : " + result.hexdigest())

if parsed_args.sha3_512:
    result = hashlib.sha3_512(parsed_args.word.encode())
    print("SHA3_512 : " + result.hexdigest())

if parsed_args.blake2s:
    result = hashlib.blake2s(parsed_args.word.encode())
    print("BLAKE2S : " + result.hexdigest())

if parsed_args.blake2b:
    result = hashlib.blake2b(parsed_args.word.encode())
    print("BLAKE2B : " + result.hexdigest())

if parsed_args.all:
    hashes = [
        hashlib.md5, hashlib.sha1, hashlib.sha224, hashlib.sha256,
        hashlib.sha384, hashlib.sha512, hashlib.sha3_224, hashlib.sha3_256,
        hashlib.sha3_384, hashlib.sha3_512, hashlib.blake2s, hashlib.blake2b
예제 #51
0
import sys
import hashlib
from sha3 import sha3_256, sha3_512
import string

inputFile = raw_input("Enter the name of the file:")
openedFile = open(inputFile)
readFile = openedFile.read()

hash_object1 = hashlib.sha1(readFile)
hash_object1_final = hash_object1.hexdigest()

hash_object2 = hashlib.sha256(readFile)
hash_object2_final = hash_object2.hexdigest()

hash_object3 = hashlib.sha512(readFile)
hash_object3_final = hash_object3.hexdigest()

hash_object4 = hashlib.sha3_256(readFile)
hash_object4_final = hash_object4.hexdigest()

hash_object5 = hashlib.sha3_512(readFile)
hash_object5_final = hash_object5.hexdigest()

print ("File Name: %s" % inputFile)
print ("SHA-1: " + hash_object1_final)
print ("SHA-256: " + hash_object2_final)
print ("SHA-512: " + hash_object3_final)
print ("SHA-3(256): " + hash_object4_final)
print ("SHA-3(512): " + hash_object5_final)
예제 #52
0
# importing libraries
import requests
from flask import Flask, render_template, redirect, url_for, request, flash
from flask_login import login_user, login_required, logout_user, UserMixin, LoginManager, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import hashlib

# Configuring the application
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = hashlib.sha3_512(
    'smoothbronx69'.encode()).hexdigest()
db = SQLAlchemy(app)
manager = LoginManager(app)


# Models and connecting to the database
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(128), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    ip = db.Column(db.String(50), nullable=False)
    creation_datetime = db.Column(db.String(50), nullable=False)


class City(db.Model):
    id = db.Column(db.Integer, primary_key=True)
예제 #53
0
        buf = afile.read(BLOCKSIZE)
		# print to screen result:
print("SHA256 hash checksum is:", hasher.hexdigest())

hasher = hashlib.sha512()
with open(str1, 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) > 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
		# print to screen result:
print("SHA512 hash checksum is:", hasher.hexdigest())

hasher = hashlib.sha3_256()
with open(str1, 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) > 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
		# print to screen result:
print("SHA3_256 hash checksum is:", hasher.hexdigest())

hasher = hashlib.sha3_512()
with open(str1, 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) > 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
		# print to screen result:
print("SHA3_512 hash checksum is:", hasher.hexdigest())
예제 #54
0
def sha3(data: typing.Union[str, bytes]) -> bytes:
    return hashlib.sha3_512(_binary(data)).digest()
예제 #55
0
def _threaded_hash(filepath):
    hasher = sha3_512()
    hasher.update(open(filepath, "rb").read())
    return base64.b85encode(hasher.digest()).decode()
예제 #56
0
wordlist = input('Enter the path of wordlist:~# ')
c = 0
try:
    wordlist = open(wordlist, 'r')
    quit()
except:
    print('File not found')
for paswd in wordlist:
    hash_obj_1 = hb.shake_128(paswd.strip().encode('utf-8')).hexdigest(1)
    hash_obj_2 = hb.sha384(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_3 = hb.sha256(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_4 = hb.sha3_384(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_5 = hb.blake2b(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_6 = hb.sha224(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_7 = hb.sha3_224(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_8 = hb.blake2s(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_9 = hb.sha3_256(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_10 = hb.sha3_512(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_11 = hb.sha1(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_12 = hb.sha512(paswd.strip().encode('utf-8')).hexdigest()
    hash_obj_13 = hb.shake_256(paswd.strip().encode('utf-8')).hexdigest(1)
    hash_obj_14 = hb.md5(paswd.strip().encode('utf-8')).hexdigest()
    if hash == hash_obj_1 or hash == hash_obj_2 or hash == hash_obj_3 or hash == hash_obj_4 or hash == hash_obj_5 or hash == hash_obj_6 or hash == hash_obj_7 or hash == hash_obj_8 or hash == hash_obj_9 or hash == hash_obj_10 or hash == hash_obj_11 or hash == hash_obj_12 or hash == hash_obj_13 or hash == hash_obj_14:
        system('clear')
        print('Password found --------> ' + paswd)
        c = c + 1
    else:
        print('Trying password --------> ' + paswd)
if c > 1:
    print('Password not match')
예제 #57
0
    def seal_receive(self_priv_key, msg_c1, msg_c2, sym_type, sym_mode,
                     sender_pub_key, sha_format, msg_c3):
        print("  ////////Proces čitanja pečata.////////")

        print(
            "     Dekriptiraj poruku C2 svojim privatnim ključem KD i saznaj  ključ K.."
        )
        print("         ==== >  K = RSA^-1 (RSA(K,KE), KD)")
        print("         Poruka C2: {}".format(msg_c2))
        print("         Privatni ključ KD: {}".format(
            self_priv_key.export_key()))
        print("             RSA dekripcija....")
        decryptor = PKCS1_OAEP.new(self_priv_key)
        secret_key_K = decryptor.decrypt(msg_c2)
        print("         Dobiveni tajni ključ K:{}".format(secret_key_K))

        # Razdvoji poruku C1 na podatak i inicijalizacijski vektor(ako je potrebno).
        c1_data = msg_c1[0]
        if sym_mode != "ECB":  # Ako je CBC, ima inicijalizacijski vektor.
            c1_vector = msg_c1[1]
        else:  # Ako je ECB, nema inicijalizacijski vektor.
            c1_vector = None

        print(
            "     Dobivenim ključem K dekriptiraj poruku C1 da dobiješ izvorni tekst P."
        )
        print("         ==== >  P = {} ^-1 {}(P, K)).".format(
            sym_type, sym_type))
        print("         Poruka C1: {}".format(msg_c1))
        print("             {} - {} dekripcija....".format(sym_type, sym_mode))
        if sym_type == "DES3":
            original_message = DES3Implementation.des3_decrypt(
                secret_key_K, c1_data, c1_vector, sym_mode)
        else:  # else AES
            original_message = AESImplementation.aes_decrypt(
                secret_key_K, c1_data, c1_vector, sym_mode)
        print("         Dobiveni izvorni tekst P:{}".format(
            str(original_message)[2:-1]))

        print("     Na temelju dolazne poruke P izračunaj sažetak H1(P)")
        print("         Dolazna poruka P: {}".format(msg_c1))
        if len(msg_c1) == 2:
            shc1c2 = \
                str(msg_c1[0])[2:-1] + \
                str(msg_c1[1])[2:-1] + str(msg_c2)[2:-1]
        else:
            shc1c2 = \
                str(msg_c1)[2:-1] + str(msg_c1)[2:-1]
        shc1c2 = bytes(shc1c2, 'utf-8')  # Ponovo pretvori u bajtove
        if sha_format == "3_256":
            h = int.from_bytes(sha3_256(shc1c2).digest(), byteorder='big')
            print("             Računanje sažetka pomoću SHA3-256...")
        else:  # else sha3_512
            h = int.from_bytes(sha3_512(shc1c2).digest(), byteorder='big')
            print("             Računanje sažetka pomoću SHA3-512...")
        print("         Dobiveni sažetak H1(P): {}".format(str(hex(h))))

        print(
            "     Dekriptiraj poslani sažetak H2(P) javnim ključem pošiljatelja KE."
        )
        print("         ==== >  H2(P) = RSA^-1(RSA(H(P), KD)), KE)")
        print("         Poslani kriptirani sažetak H2(P): {}".format(
            str(hex(msg_c3))))
        print("         Javni ključ pošiljatelja: {}".format(
            sender_pub_key.export_key()))
        print("             Dekriptiraj sažetak...")
        hash_from_signature = pow(msg_c3, sender_pub_key.e, sender_pub_key.n)
        print("         Dekriptirani sažetak H2(P): {}".format(
            str(hex(hash_from_signature))))

        print("     Usporedi ta dva sažetka.")
        print("         ==== >  (H1(P) == H2(P)) = ?")
        print("         Dobiveni sažetak H1(P): {}".format(str(hex(h))))
        print("         Dekriptirani sažetak H2(P): {}".format(
            str(hex(hash_from_signature))))
        print("         Sažetci su jednaki? ", h == hash_from_signature)

        print("         Dobiveni izvorni tekst P:{}".format(
            str(original_message)[2:-1]))
        print("  ////////Kraj procesa čitanja pečata.////////")
예제 #58
0
def readNormal():
	with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
		for line in FileObj:
			passwd1 = line.replace("\n", "")
			if hash_type == 0: #MD5
				passwd_hash = hashlib.md5(passwd1.encode()).hexdigest()
			elif hash_type == 1: #MD4
				passwd_hash = MD4.new(passwd1.encode()).hexdigest()
			elif hash_type == 2: #MD2
				passwd_hash = MD2.new(passwd1.encode()).hexdigest()
			elif hash_type == 3: #SHA1
				passwd_hash = hashlib.sha1(passwd1.encode()).hexdigest()
			elif hash_type == 4: #SHA-224
				passwd_hash = hashlib.sha224(passwd1.encode()).hexdigest()
			elif hash_type == 5: #SHA-256
				passwd_hash = hashlib.sha256(passwd1.encode()).hexdigest()
			elif hash_type == 6: #SHA-384
				passwd_hash = hashlib.sha384(passwd1.encode()).hexdigest()
			elif hash_type == 7: #SHA-512
				passwd_hash = hashlib.sha512(passwd1.encode()).hexdigest()
			elif hash_type == 8: #SHA3-224
				passwd_hash = hashlib.sha3_224(passwd1.encode()).hexdigest()
			elif hash_type == 9: #SHA3-256
				passwd_hash = hashlib.sha3_256(passwd1.encode()).hexdigest()
			elif hash_type == 10: #SHA3-384
				passwd_hash = hashlib.sha3_384(passwd1.encode()).hexdigest()
			elif hash_type == 11: #SHA3-512
				passwd_hash = hashlib.sha3_512(passwd1.encode()).hexdigest()
			elif hash_type == 12: #BLAKE2s256
				passwd_hash = hashlib.new('blake2s256', passwd1.encode()).hexdigest()
			elif hash_type == 13: #BLAKE2b512
				passwd_hash = hashlib.new('blake2b512', passwd1.encode()).hexdigest()
			elif hash_type == 14: #NTLM
				passwd_hash = hashlib.new('md4', passwd1.encode('utf-16le')).hexdigest()
			elif hash_type == 15: #Whirlpool
				passwd_hash = hashlib.new('whirlpool', passwd1.encode()).hexdigest()
			elif hash_type == 16: #SM3
				passwd_hash = hashlib.new('sm3', passwd1.encode()).hexdigest()
			elif hash_type == 17: #RIPEMD-160
				passwd_hash = hashlib.new('ripemd160', passwd1.encode()).hexdigest()
			else:
				print(color.RED + "[-] Invalid hash type...Exiting!" + color.END)
				sys.exit()
			if verbose == True:
				print(color.BLACK + "Trying {}" .format(str(repr(passwd1))) + color.END)
			if user_hash == passwd_hash:
				print(color.GREEN + "[+] Hash cracked! Results: " + color.RED + str(line) + color.END)
				endTime = time.time()
				deltaTime = endTime - startTime
				sys.stdout.write("\033[F")
				print(color.GREEN + "[+] Cracking finished in " + color.RED + str(format(deltaTime, ".3f")) + color.END + color.GREEN + "s" + color.END)
				if output == True:
					output_text = "\nDate: {0}\nHash: {1}\nCracked hash: {2}\nCracking time: {3}\nWordlist: {4}" .format(str(today.strftime("%d/%m/%Y")), str(user_hash), str(line).replace("\n", ""), format(deltaTime, ".3f"), str(wordlist))
					print(output_text, file=open("results.txt", "a"))
					print(color.ORANGE + "Results saved successfully in ./results.txt!" + color.END)
				if output_json == True:
					results = {
						"Date": str(today.strftime("%d/%m/%Y")),
						"hash": str(user_hash),
						"crackedHash": str(line).replace("\n", ""),
						"crackingTime": format(deltaTime, ".3f"),
						"wordlist": str(wordlist)
					}
					results_json = json.dumps(results, indent=2)
					print(results_json, file=open("results.json", "a"))
					print(color.ORANGE + "Results saved successfully in ./results.json!" + color.END)
				sys.exit()
		print(color.RED + "[-] Hash not found! Maybe another wordlist would help." + color.END)
		sys.exit()
예제 #59
0
import sys
import hashlib
from sha3 import sha3_256, sha3_512
import string

mystring = raw_input ('Enter String to hash: ')
hash_object1 = hashlib.sha1(mystring.encode())
hash_object2 = hashlib.sha256(mystring.encode())
hash_object3 = hashlib.sha512(mystring.encode())
hash_object4 = hashlib.sha3_256(mystring.encode())
hash_object5 = hashlib.sha3_512(mystring.encode())

print ("String entered: %s" % mystring)
print ("SHA-1: " + hash_object1.hexdigest())
print ("SHA-256: " + hash_object2.hexdigest())
print ("SHA-512: " + hash_object3.hexdigest())
print ("SHA-3(256): " + hash_object4.hexdigest())
print ("SHA-3(512): " + hash_object5.hexdigest())
예제 #60
0
             time.sleep(3)
             break
         else:
             linum += 1
     except IndexError:
         print('\nHash uncrackable with SHA512')
         sha512 = 0
         time.sleep(3)
         break
 print('Trying SHA3-512')
 time.sleep(0.5)
 print('Begin cracking')
 linum = 0
 while True:
     try:
         com_hash3 = hashlib.sha3_512(wl[linum][:len(wl[linum]) -
                                                1]).hexdigest()
         word3 = wl[linum][:len(wl[linum]) - 1]
         print('Comparing: ' + str(input_hash) + ' - ' + str(com_hash3) +
               ' ( ' + str(word3)[1:] + ' )')
         if com_hash3 == input_hash:
             print('\nHash successfully cracked')
             sha3_512 = 1
             time.sleep(3)
             break
         else:
             linum += 1
     except IndexError:
         print('\nHash uncrackable with SHA3-512')
         sha3_512 = 0
         time.sleep(3)
         break