예제 #1
0
def warehouse(brutefile, passwordtype, ifsplitTEXT="Cache"):
    catch = []
    if brutefile != "Default":
        if passwordtype == "md5":
            catch = [(md5(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        elif passwordtype == "sha1":
            catch = [(sha1(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        elif passwordtype == "sha224":
            catch = [(sha224(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        elif passwordtype == "sha256":
            catch = [(sha256(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        elif passwordtype == "sha384":
            catch = [(sha384(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        elif passwordtype == "sha512":
            catch = [(sha512(x.strip()).hexdigest() + ":" + x.strip()) for x in open(brutefile, "r").readlines()]
        return catch

    else:
        if passwordtype == "md5":
            catch = [(md5(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        elif passwordtype == "sha1":
            catch = [(sha1(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        elif passwordtype == "sha224":
            catch = [(sha224(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        elif passwordtype == "sha256":
            catch = [(sha256(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        elif passwordtype == "sha384":
            catch = [(sha384(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        elif passwordtype == "sha512":
            catch = [(sha512(x.strip()).hexdigest() + ":" + x.strip()) for x in ifsplitTEXT]
        return catch
예제 #2
0
 def close(self):
     log.info("%s: Closing" % (self.__class__.__name__))
     if self._oram is not None:
         try:
             stashdigest = \
                 PathORAM.stash_digest(
                     self._oram.stash,
                     digestmod=hmac.HMAC(key=self._oram.storage_heap.key,
                                         digestmod=hashlib.sha384))
             positiondigest = \
                 PathORAM.position_map_digest(
                     self._oram.position_map,
                     digestmod=hmac.HMAC(key=self._oram.storage_heap.key,
                                         digestmod=hashlib.sha384))
             new_header_data = \
                 bytearray(self._oram.storage_heap.\
                           header_data[:self._header_offset])
             new_header_data[:hashlib.sha384().digest_size] = \
                 stashdigest
             new_header_data[hashlib.sha384().digest_size:\
                             (2*hashlib.sha384().digest_size)] = \
                 positiondigest
             self._oram.storage_heap.update_header_data(
                 bytes(new_header_data) + self.header_data)
         except:                                                # pragma: no cover
             log.error(                                         # pragma: no cover
                 "%s: Failed to update header data with "       # pragma: no cover
                 "current stash and position map state"         # pragma: no cover
                 % (self.__class__.__name__))                   # pragma: no cover
             raise
         finally:
             self._oram.storage_heap.close()
예제 #3
0
 def id(self):
     """Returns the SHA384-based ID of the message"""
     if isinstance(self.msg, str):
         msg_hash = hashlib.sha384((self.msg + to_base_58(self.time)).encode())
     else:
         msg_hash = hashlib.sha384(self.msg + to_base_58(self.time).encode())            
     return to_base_58(int(msg_hash.hexdigest(), 16))
예제 #4
0
    def warehouse(self, brutefile, ifsplitTEXT="Cache"):
        if brutefile != "Default":
            with open(brutefile, "r") as brute:
                for i in brute.readlines():
                    if self.type == "md5":
                        storekey = "%s:%s" % (md5(i.strip()).hexdigest(), i.strip())
                    elif self.type == "sha1":
                        storekey = "%s:%s" % (sha1(i.strip()).hexdigest(), i.strip())
                    elif self.type == "sha224":
                        storekey = "%s:%s" % (sha224(i.strip()).hexdigest(), i.strip())
                    elif self.type == "sha256":
                        storekey = "%s:%s" % (sha256(i.strip()).hexdigest(), i.strip())
                    elif self.type == "sha384":
                        storekey = "%s:%s" % (sha384(i.strip()).hexdigest(), i.strip())
                    elif self.type == "sha512":
                        storekey = "%s:%s" % (sha512(i.strip()).hexdigest(), i.strip())
                    self.catch.append(storekey)
                self.bruteforce()

        else:
            for i in set(ifsplitTEXT):
                if self.type == "md5":
                    storekey = "%s:%s" % (md5(i.strip()).hexdigest(), i.strip())
                elif self.type == "sha1":
                    storekey = "%s:%s" % (sha1(i.strip()).hexdigest(), i.strip())
                elif self.type == "sha224":
                    storekey = "%s:%s" % (sha224(i.strip()).hexdigest(), i.strip())
                elif self.type == "sha256":
                    storekey = "%s:%s" % (sha256(i.strip()).hexdigest(), i.strip())
                elif self.type == "sha384":
                    storekey = "%s:%s" % (sha384(i.strip()).hexdigest(), i.strip())
                elif self.type == "sha512":
                    storekey = "%s:%s" % (sha512(i.strip()).hexdigest(), i.strip())
                self.catch.append(storekey)
            self.bruteforce()
예제 #5
0
파일: jsoncert.py 프로젝트: pstjuste/litter
  def __init__(self, content, pubkey=None, privkey=None):
    """If key=None, the key should be in content dict already, else overwrite"""
    self.as_dict = content
    self.privkey = privkey
    if pubkey:
      self.pubkey = pubkey
      self.as_dict['key'] = JsonCert.key_to_str(self.pubkey)
    elif 'key' in self.as_dict:
      self.pubkey = JsonCert.str_to_key(self.as_dict['key'])
    else:
      raise Exception("No public key in certificate")

    if 'sig' in self.as_dict:
      sig = self.as_dict['sig']
      del self.as_dict['sig']
      #verify:
      self.keyid = hashlib.sha384(JsonCert.serialize(self.as_dict)).digest() 
      compkid = rsa_cbc_d(self.pubkey, base64.urlsafe_b64decode(sig)) 
      if compkid != self.keyid:
        raise Exception('Invalid self-signature in keyid %s' % \
                        base64.urlsafe_b64encode(self.keyid))
      #things look good, put the signature back:
      self.as_dict['sig'] = sig
    else:
      if not privkey:
        raise Exception("Unsigned certificate without private key")
      else:
        self.keyid = hashlib.sha384(JsonCert.serialize(self.as_dict)).digest() 
        sigdata = rsa_cbc_e(self.privkey, self.keyid)
        self.as_dict['sig'] = base64.urlsafe_b64encode(sigdata)
    self.keyid64 = base64.urlsafe_b64encode(self.keyid)
예제 #6
0
def generate_hash():
    import hashlib as h
    entry = [[e['entry']['id'], str(e['entry']['datetime']), 
              e['entry']['title'],
              '|'.join([h.sha1(e['entry']['description']).hexdigest(),
                        h.md5(e['entry']['description']).hexdigest(),
                        h.sha224(e['entry']['description']).hexdigest(),
                        h.sha256(e['entry']['description']).hexdigest(),
                        h.sha384(e['entry']['description']).hexdigest(),
                        h.sha512(e['entry']['description']).hexdigest()])]
              for e in cynotedb(cynotedb.entry.id>0).select(cynotedb.entry.id, 
                  cynotedb.entry.title, cynotedb.entry.datetime, 
                  cynotedb.entry.description).records]
    comment = [[e['comment']['id'], str(e['comment']['datetime']), 
                e['comment']['entry_id'],
                '|'.join([h.sha1(e['comment']['body']).hexdigest(),
                          h.md5(e['comment']['body']).hexdigest(),
                          h.sha224(e['comment']['body']).hexdigest(),
                          h.sha256(e['comment']['body']).hexdigest(),
                          h.sha384(e['comment']['body']).hexdigest(),
                          h.sha512(e['comment']['body']).hexdigest()])]
                for e in cynotedb(cynotedb.comment.id>0).select(cynotedb.comment.id, 
                    cynotedb.comment.entry_id, cynotedb.comment.datetime, 
                    cynotedb.comment.body).records]
    for e in entry:
        db.entry_hash.insert(eid=e[0], edatetime=e[1], etitle=e[2], ehash=e[3])
    for c in comment:
        db.comment_hash.insert(cid=c[0], cdatetime=c[1], eid=c[2], chash=c[3])
    db.log.insert(event='Entry hash generation. n=' + str(len(entry)), 
                  user=session.username)
    db.log.insert(event='Comment hash generation. n=' + str(len(comment)), 
                  user=session.username)
    return dict(entry=entry, comment=comment)
예제 #7
0
def forgeSignature(message, sig1, sig2):
	
	# definitions
	r = sig1['r']
	s1 = sig1['s']
	s2 = sig2['s']
	m1 = sig1['m']
	m2 = sig2['m']
	h1 = int(hashlib.sha384(m1.encode('ASCII')).hexdigest(), 16)
	h2 = int(hashlib.sha384(m2.encode('ASCII')).hexdigest(), 16)
	hNew = int(hashlib.sha384(message.encode('ASCII')).hexdigest(), 16)
	
	# sanity checks
	assert(sig1['r'] == sig2['r'])
	assert(elgamal_verify(r, s1, m1))
	assert(elgamal_verify(r, s2, m2))
	
	# get k^(-1)
	kInvCandidates = moddiv((s1 - s2) % (SAFEPRIME - 1), (h1 - h2) % (SAFEPRIME - 1), SAFEPRIME - 1)
	kInvCandidates = filter(lambda c: pow(r, c, SAFEPRIME) == GENERATOR, kInvCandidates)
	kInv = next(kInvCandidates)

	# compute the new s value
	s = (s1 + (hNew - h1) * kInv) % (SAFEPRIME - 1)
	
	return {'r': r, 's' : s}
예제 #8
0
    def hack(self):
        print "[*] Initialized Elgamal ..."
        t = 0
        t_ = 0
        flag = 0
        # First select two sigs which are valid and have the same r
        for i in range(len(self.sigs)):
            t = self.sigs[i]
            for j in range(i + 1, len(self.sigs)):
                t_ = self.sigs[j]
                if t["r"] != t_["r"]:
                    continue
                if not self.verify(j) or not self.verify(i):
                    continue
                flag = 1
                break
            if flag == 1:
                break

        if flag == 0:
            print "[X] Signatures are secure"
            sys.exit(2)
        
        print "[*] Found sigs with common r! Trying to break."

        s1 = t["s"]
        s2 = t_["s"]
        m1 = int(hashlib.sha384(t["m"]).hexdigest(), 16)
        m2 = int(hashlib.sha384(t_["m"]).hexdigest(), 16)
        m1_m2 = m1 - m2

        n = daedmath.euclid(s1 - s2, self.safeprime -1)
        k_ = gmpy.divm(m1_m2 / n, (s1 - s2) / n, (self.safeprime-1)/n)
        k = None
        for i in range(0, n):
            k = k_ + (i * (self.safeprime - 1) / n)
            if pow(self.generator, k, self.safeprime) == t["r"]:
                break
        if not k:
            print "[X] Failed to get a valid k!"
            sys.exit(2)
        
        print "[*] Found k: %d" % k
        n = daedmath.euclid(t["r"], self.safeprime - 1)
        side2 = m1 - k * t["s"]
        x_ = gmpy.divm(side2/n, t["r"]/n, (self.safeprime - 1) / n)
        x = None
        for i in range(0, n):
            x = x_ + (i * (self.safeprime - 1) / n)
            if pow(self.generator, x, self.safeprime) == self.pubkey:
                break
        if x:
            print "[*] Retrieved Private Key x: %d" % x
        else:
            print "[X] Unable to calculate x!"
예제 #9
0
 def test_LargeStream(self):
   with tempfile.TemporaryFile() as tmp:
     tmp_hash = hashlib.sha384()
     null_chunk = bytearray(2**20) # 1 MiB
     for i in range(10): # 10 MiB
       tmp.write(null_chunk)
       tmp_hash.update(null_chunk)
     tmp.seek(0)
     self.TempFileNX.PutStream(tmp)
   with open(self.TempFileNX.Path, 'rb') as tmp2:
     tmp2_hash = hashlib.sha384()
     for chunk in iter(lambda: tmp2.read(2**20), b''):
       tmp2_hash.update(chunk)
   self.assertEqual(tmp_hash.digest(), tmp2_hash.digest())
예제 #10
0
파일: webserver.py 프로젝트: xmcp/kylinOJ
    def login(self,username=None,password=None):
        ha=lambda u,p: hashlib.sha384(('U "%s" --> P "%s"'%(u,p)).encode()).hexdigest()

        if 'username' in cherrypy.session:
            raise cherrypy.HTTPRedirect('/')
        if not username:
            return lookup('login.html').render()
        elif not password:
            db=sqlite3.connect(const.DBFILE)
            cur=db.cursor()
            cur.execute('select exists(select * from users where username=?)',[username])
            return 'login' if cur.fetchone()[0] else 'register'
        else:
            db=sqlite3.connect(const.DBFILE)
            cur=db.cursor()
            cur.execute('select password from users where username=?',[username])
            result=cur.fetchone()
            if result: #login
                if ha(username,password)==result[0]:
                    cherrypy.session['username']=username
                    raise cherrypy.HTTPRedirect('/')
                else:
                    return err('密码不正确')
            else: #signup
                cur.execute('insert into users (id,username,password,nick) values '\
                    '(null,?,?,?)',[username,ha(username,password),username])
                db.commit()
                cherrypy.session['username']=username
                raise cherrypy.HTTPRedirect('/')
예제 #11
0
def verify_certificate(c, pc):
    # TODO: need a new way
    c_signature_algorithm = c['signature_algorithm']['algorithm'].dotted
    c_tbs_encoded = c['tbs_certificate'].dump()
    if c_signature_algorithm == '1.2.840.113549.1.1.4':  # RSA
        tbs_hash_hex = hashlib.md5(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.113549.1.1.5':
        tbs_hash_hex = hashlib.sha1(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.113549.1.1.11':
        tbs_hash_hex = hashlib.sha256(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.113549.1.1.12':
        tbs_hash_hex = hashlib.sha384(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.113549.1.1.13':
        tbs_hash_hex = hashlib.sha512(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.10040.4.3':  # DSA
        tbs_hash_hex = hashlib.sha1(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '2.16.840.1.101.3.4.3.2':
        tbs_hash_hex = hashlib.sha256(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.10045.4.1':  # ecdsa
        tbs_hash_hex = hashlib.sha1(c_tbs_encoded).hexdigest()
    elif c_signature_algorithm == '1.2.840.10045.4.3.2':
        tbs_hash_hex = hashlib.sha256(c_tbs_encoded).hexdigest()
    else:
        tbs_hash_hex = ''
    pub_key = pc.public_key
    return sig_verify(c.signature, pub_key, tbs_hash_hex)
예제 #12
0
def __hashsha384__():
  chaine = raw_input('\nEntrez le texte a hasher: ')
  if(chaine == ""):
    print vide
    __hashsha384__()

  else:
    encode = sha384(chaine).hexdigest()
    print '\nVotre texte hashé est:\n'
    print encode
    print ""
    ysha384()
#############################

#### Fonction * to ASCII ####
#def __cracksha384__():
  #chaine = raw_input('\nEntrez la chaine a decrypter: ')
  #if (chaine == ""):
    #print vide
    #__decodezb64__()

  #else:
    #decode = base64.decodestring(chaine)
    #print '\nVotre chaine déhashée est:\n'
    #print decode
    #print ""
    #base64()
#############################
예제 #13
0
 def isValid(self):
     superValid, superReason = ProofOfWorkRequest.isValid(self)
     if not superValid:
         return (superValid, superReason)
     if hashlib.sha384("%s%s" % (self.prefix, self.suffix)).hexdigest()[:4] != "0000":
         return (False, "Invalid hash.")
     return (True, None)
예제 #14
0
파일: ked.py 프로젝트: askin/misc
    def encrypt(self, widget, data=None):
        # get choose
        choose = self.combobox.get_active_text()

        # do it
        if choose == "md5":
            m = hashlib.md5(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "sha1":
            m = hashlib.sha1(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "sha224":
            m = hashlib.sha224(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "sha256":
            m = hashlib.sha256(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "sha384":
            m = hashlib.sha384(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "sha512":
            m = hashlib.sha512(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m.hexdigest())
        elif choose == "Base16":
            m = base64.b16encode(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m)
        elif choose == "Base32":
            m = base64.b32encode(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m)
        elif choose == "Base64":
            m = base64.b64encode(self.get_text(self.textbox1))
            self.set_text(self.textbox2, m)
        else:
            print "Yok Böyle Birşey"
예제 #15
0
 def hash(self, line):
   gotHash = ''
   try:
     if (line[4] in HASHES):
       if (len(line) >= 6):
         target = ''
         for i in line[5:]:
           target += str(i) + " "
         target = target[:-1]
         if (line[4] == 'md5'):
           return hashlib.md5(target).hexdigest()
         if (line[4] == 'sha1'):
           return hashlib.sha1(target).hexdigest()
         if (line[4] == 'sha224'):
           return hashlib.sha224(target).hexdigest()
         if (line[4] == 'sha256'):
           return hashlib.sha256(target).hexdigest()
         if (line[4] == 'sha384'):
           return hashlib.sha384(target).hexdigest()
         else:
           return "Fail."
       else:
         return "Nothing to hash."
     else:
       return "Invalid hash type."
   except(IndexError):
     return "No hash type."
예제 #16
0
파일: app.py 프로젝트: Morillo9/QHashGUI
    def Browse(self):

        self.listWidget_2.clear()

        fname = QFileDialog.getOpenFileName()
        self.hash_md5 = hashlib.md5()
        self.hash_sha256 = hashlib.sha256()
        self.hash_sha1 = hashlib.sha1()
        self.hash_sha224 = hashlib.sha224()
        self.hash_sha384 = hashlib.sha384()
        self.hash_crc32 = None

        with open(fname, "rb") as f:
            buf = f.read()
            self.hash_crc32 = (binascii.crc32(buf) & 0xFFFFFFFF)
            for chunk in iter(lambda: f.read(4096), b""):
                self.hash_md5.update(chunk)
                self.hash_sha256.update(chunk)
                self.hash_sha1.update(chunk)
                self.hash_sha224.update(chunk)
                self.hash_sha384.update(chunk)


        self.listWidget_2.addItem(self.hash_md5.hexdigest())
        self.listWidget_2.addItem(self.hash_sha1.hexdigest())
        self.listWidget_2.addItem(self.hash_sha256.hexdigest())
        self.listWidget_2.addItem(self.hash_sha224.hexdigest())
        self.listWidget_2.addItem(self.hash_sha384.hexdigest())
        self.listWidget_2.addItem(str(self.hash_crc32))
예제 #17
0
파일: flaskr.py 프로젝트: hxkoh2/project
def add_user():
	type = request.form['type'].lower().strip()
	if type == 'student': type = 0
	else: type = 1

	username = request.form['username'].strip()
	password = request.form['password']
	email = request.form['email'].strip()
	if len(email.split('@')) != 2: 
		flash('Error: Not a valid email')
		return redirect(url_for('home'))
	if len(email) < 6:
		flash('Error: Email too short to be valid')
		return redirect(url_for('home'))
	if email[len(email)-4:len(email)] != '.edu':
		flash('Error: Please use a .edu email')
		return redirect(url_for('home'))

	# password encryption
	m = hashlib.sha384()
	m.update(password)
	password = unicode(m.hexdigest())

	try:
		cur = g.db.execute('insert into Person(type, username, password, email) values (?,?,?,?)', [type, username, password, email])
		g.db.commit()
		flash('Account created - you may login')
		return redirect(url_for('login'))
	except:
		flash('Error: Username already exists - select new username')
		return redirect(url_for('home'))
예제 #18
0
파일: authentication.py 프로젝트: d3k1/zual
def authenticate(u, p):
    if u and p:
        if u in (current_app.config['ADMIN_MAIL'],):
            p_salt = p + current_app.config["SECRET_KEY"]
            e_salt = chaabi + current_app.config["SECRET_KEY"]

            d = hashlib.sha384()
            e = hashlib.sha384()

            d.update(p_salt.encode())
            e.update(e_salt.encode())
            return d.hexdigest() == e.hexdigest()
        else:
            return False
    else:
        return False
예제 #19
0
def get_hashing_algorithm(fingerprint):
    """
    Get hashing algorithm for the given fingerprint or None if fingerprint of
    unsupported length is given.

    :param fingerprint: hexa fingerprint to get the hashing algorithm for
    :type fingerprint: hexadecimal str
    :return: one of the hashlib.* hash objects
    :rtype: hashlib.HASH object

    """

    hashes = (hashlib.md5(), hashlib.sha1(), hashlib.sha224(),
              hashlib.sha256(), hashlib.sha384(), hashlib.sha512())

    if len(fingerprint) % 2 == 1:
        return None

    num_bytes = len(fingerprint) / 2

    for hash_obj in hashes:
        # pylint: disable-msg=E1103
        if hash_obj.digest_size == num_bytes:
            return hash_obj

    return None
예제 #20
0
파일: pki.py 프로젝트: tehmaze/tlsspy
    def get_hash(self):
        '''
        :return: cryptographic hash of the tbsCertificate sequence
        '''
        signature_algorithm = self.get_signature_algorithm()
        algorithm = signature_algorithm.replace('WithRSAEncryption', '')
        log.debug('Generating hashed value for {0}'.format(
            algorithm,
        ))

        data = der_encoder.encode(self.tbsCertificate)
        if algorithm == 'md2':
            return md2.MD2(data).digest()
        elif algorithm == 'md5':
            return hashlib.md5(data).digest()
        elif algorithm == 'ripemd160':
            return ripemd160.RIPEMD160(data).digest()
        elif algorithm == 'sha1':
            return hashlib.sha1(data).digest()
        elif algorithm == 'sha224':
            return hashlib.sha224(data).digest()
        elif algorithm == 'sha256':
            return hashlib.sha256(data).digest()
        elif algorithm == 'sha384':
            return hashlib.sha384(data).digest()
        elif algorithm == 'sha512':
            return hashlib.sha512(data).digest()
        else:
            log.error('Unsupported signature algorithm: {0}'.format(
                signature_algorithm,
            ))
            return None
예제 #21
0
 def _parts_dir(self):
     parts_uri = os.environ.get("SNAPCRAFT_PARTS_URI")
     return os.path.join(
         BaseDirectory.xdg_data_home,
         "snapcraft",
         hashlib.sha384(parts_uri.encode(sys.getfilesystemencoding())).hexdigest(),
     )
예제 #22
0
def hasher(fichero, metodo):
	if metodo == "md5":
		hasheador = hashlib.md5()
	elif metodo == "sha1":
		hasheador = hashlib.sha1()
	elif metodo == "sha256":
		hasheador = hashlib.sha256()
	elif metodo == "sha384":
		hasheador = hashlib.sha384()
	elif metodo == "sha224":
		hasheador = hashlib.sha224()
	elif metodo == "sha512":
		hasheador = hashlib.sha512()

	try:
		if c.getVerbose():
			print "[hasher.py] Hasheando en hasher(): " + fichero
		with open(fichero, 'r') as f:
			while True:
				data = f.read(BUF_SIZE)
				if not data:
					break
				hasheador.update(data)
		return hasheador.hexdigest()
	except:
		pass
예제 #23
0
파일: tools.py 프로젝트: pheelixx/konvert
 def generate_hash(phrases):
     phrase = str(datetime.utcnow())
     for item in phrases:
         phrase += str(item)
     key384 = hashlib.sha384(phrase).hexdigest()
     rand = str(random.randint(1, 16777216))
     return hashlib.md5(key384 + rand).hexdigest()
예제 #24
0
def hashfile(path, blocksize=65536):
    md5 = hashlib.md5()
    sha1 = hashlib.sha1()
    sha224 = hashlib.sha224()
    sha256 = hashlib.sha256()
    sha384 = hashlib.sha384()
    sha512 = hashlib.sha512()

    with open(path, 'rb') as afile:
        buf = afile.read(blocksize)

        while len(buf) > 0:
            md5.update(buf)
            sha1.update(buf)
            sha224.update(buf)
            sha256.update(buf)
            sha384.update(buf)
            sha512.update(buf)
            buf = afile.read(blocksize)

    return {
        'md5': md5.hexdigest(),
        'sha1': sha1.hexdigest(),
        'sha224': sha224.hexdigest(),
        'sha256': sha256.hexdigest(),
        'sha384': sha384.hexdigest(),
        'sha512': sha512.hexdigest(),
    }
예제 #25
0
    def reply(self, *args):
        # type: (Message, *MsgPackable) -> None
        """Replies to the sender if you're directly connected. Tries to make
        a connection otherwise

        Args:
            *args: Each argument given is a packet you wish to send. This is
                       prefixed with base.flags.whisper, so the other end will
                       receive ``[base.flags.whisper, *args]``
        """
        self.server._logger.debug(
            'Initiating a direct reply to Message ID {}'.format(self.id))
        if self.server.routing_table.get(self.sender):
            self.server.routing_table.get(self.sender).send(
                flags.whisper, flags.whisper, *args)
        else:
            self.server._logger.debug('Requesting connection for direct reply'
                                      ' to Message ID {}'.format(self.id))
            request_hash = sha384(
                self.sender + b58encode_int(getUTC()).decode()).hexdigest()
            request_id = b58encode_int(int(request_hash, 16)).decode()
            self.server.send(request_id, self.sender, type=flags.request)
            to_send = (flags.whisper,
                       flags.whisper)  # type: Tuple[MsgPackable, ...]
            self.server.requests[request_id] = to_send + args
            self.server._logger.critical(
                "You aren't connected to the original sender. This reply is "
                "not guarunteed, but we're trying to make a connection and "
                "put the message through.")
예제 #26
0
    def server_package(version, status, value, isError):
        # create XML
        root = etree.Element('request')

        version_elm = etree.Element('version')
        version_elm.text = str(version)
        root.append(version_elm)

        status_elm = etree.Element('status')
        status_elm.text = str(status)
        root.append(status_elm)

        if isError:
            message_elm = etree.Element('error')
        else:
            message_elm = etree.Element('value')
        message_elm.text = str(value)
        root.append(message_elm)

        without_checksum = etree.tostring(root)

        # get a checksum of everything without checksum tag
        pre_checksum = etree.tostring(root)
        checksum = sha384(pre_checksum)

        checksum_elm = etree.Element('checksum')
        # convert binary to hex
        checksum_elm.text = checksum.hexdigest()
        root.append(checksum_elm)

        s = etree.tostring(root)

        return s
예제 #27
0
def token_generate(email=None, expires_in=TOKEN_EXPIRE_TIME):
    user = UserModel.query\
        .filter(UserModel.email == email) \
        .first()

    created_at = datetime.datetime.now()
    expired_at = created_at + datetime.timedelta(seconds=expires_in)

    data = {
        'user_id': user.id,
        'created_at': created_at.isoformat(),
        'expired_at': expired_at.isoformat(),
        'scheme': TOKEN_SCHEME
    }

    token = Serializer(APP_SECRET_KEY, expires_in=expires_in).dumps(data)
    data['token'] = hashlib.sha384(token).hexdigest()

    user_token = UserTokenModel(
        user_id=user.id,
        token=token,
        hashed=data['token'],
        expired_at=expired_at
    )

    db.session.add(user_token)
    db.session.commit()

    return data
예제 #28
0
def tokenIssue(userIdx) :
	t = time.time()
	hashObj = hashlib.sha384(str(userIdx) + str(int(t)) + str(random.randrange(1, 1000)))
	hashData = hashObj.hexdigest()
	hashObj = hashlib.md5(hashData)
	token = hashObj.hexdigest()
	return token
예제 #29
0
파일: repo.py 프로젝트: attente/snapcraft
    def _setup_apt_cache(self, rootdir):
        if self._use_geoip or self._sources_list:
            release = platform.linux_distribution()[2]
            sources_list = _format_sources_list(
                self._sources_list, deb_arch=self._deb_arch,
                use_geoip=self._use_geoip, release=release)
        else:
            sources_list = _get_local_sources_list()

        sources_list_digest = hashlib.sha384(
            sources_list.encode(sys.getfilesystemencoding())).hexdigest()

        cache_dir = os.path.join(self._cache_dir, sources_list_digest)
        apt_cache_dir = os.path.join(cache_dir, 'apt')
        package_cache_dir = os.path.join(cache_dir, 'packages')

        sources_list_file = os.path.join(
            apt_cache_dir, 'etc', 'apt', 'sources.list')

        os.makedirs(os.path.dirname(sources_list_file), exist_ok=True)
        with open(sources_list_file, 'w') as f:
            f.write(sources_list)

        apt_cache = apt.Cache(rootdir=apt_cache_dir, memonly=True)
        apt_cache.update(fetch_progress=self.progress,
                         sources_list=sources_list_file)

        copy_tree(apt_cache_dir, rootdir, update=True)

        return package_cache_dir
예제 #30
0
def toHash():
    while True:
        password = input("Password: "******"Encryption type: ")
        
        if hashtype == "ntlm":
            phash = hashlib.new('md4', password.encode('utf-16le')).digest()
            
        elif hashtype == "md4":
            phash = hashlib.new('md4', password.encode('ascii')).digest()

        elif hashtype == "md5":
            phash = hashlib.new('md5', password.encode("ascii")).digest()

        elif hashtype == "whirlpool":
            phash = hashlib.new('whirlpool', password.encode('ascii')).digest()
            
        elif hashtype == "sha1":
            phash = hashlib.sha1(password.encode('ascii')).digest()

        elif hashtype == "sha224":
            phash = hashlib.sha224(password.encode('ascii')).digest()

        elif hashtype == "sha256":
            phash = hashlib.sha256(password.encode('ascii')).digest()

        elif hashtype == "sha384":
            phash = hashlib.sha384(password.encode('ascii')).digest()

        elif hashtype == "sha512":
            phash = hashlib.sha512(password.encode('ascii')).digest()

        print("\n"+str(binascii.hexlify(phash))[2:-1]+"\n")
예제 #31
0
파일: webEngine.py 프로젝트: jwstes/BlueLeg
def SHA384(data):
    return hashlib.sha384(data.encode()).hexdigest()[0:6]
예제 #32
0
def hash_string_sha384(string=None):
    hash_str = sha384(string.encode('utf-8')).hexdigest()
    return hash_str
예제 #33
0
def hash_file_sha384(file_path=None):
    data = read_file(file_path)
    hash_code = sha384(data).hexdigest()
    return hash_code
예제 #34
0
    print('  ', str(i+1) + ":", options[i])

inp = int(input("Select:  "))
try:
    if inp in range(1, 10):
        # if inp == options[inp-1]:
        if inp == 1:
            print('Result of string encoded to MD5:', hashlisb.md5(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 2:
            print('Result of string encoded to SHA1:', hashlib.sha1(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 3:
            print('Result of string encoded to SHA224:', hashlib.sha224(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 4:
            print('Result of string encoded to SHA256:', hashlib.sha256(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 5:
            print('Result of string encoded to SHA384:', hashlib.sha384(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 6:
            print('Result of string encoded to SHA512:', hashlib.sha512(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 7:
            print('Encoded to MD5:', hashlib.md5(plain_str.encode('UTF-8')).hexdigest())
            print('Encoded to SHA1:', hashlib.sha1(plain_str.encode('UTF-8')).hexdigest())
            print('Encoded to SHA224:', hashlib.sha224(plain_str.encode('UTF-8')).hexdigest())
            print('Encoded to SHA256:', hashlib.sha256(plain_str.encode('UTF-8')).hexdigest())
            print('Encoded to SHA384:', hashlib.sha384(plain_str.encode('UTF-8')).hexdigest())
            print('Encoded to SHA512:', hashlib.sha512(plain_str.encode('UTF-8')).hexdigest())
        elif inp == 8:
            print('Goodbye!')
    else:
        print('Invalid input.')
except IndexError:
    print('That is not an option.')
예제 #35
0
import sys
import hashlib
# Set block size to 65MB, to deal with large files
BLOCKSIZE = 65536
# Set variable my_file from file name inputted by user
my_file = raw_input("Enter the name of the file you wish to check: ")
# declare variables for each hash algorithm
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
sha512 = hashlib.sha512()
sha384 = hashlib.sha384()
sha3_512 = hashlib.sha3_512()

with open(my_file, 'rb') as file_to_check:
    # read the contents of the file and store it in variable called "contents"
    # rb specifies to read the file in binary mode
    contents = file_to_check.read(BLOCKSIZE)
    # update each variable state with variable "contents"
    sha1.update(contents)
    sha256.update(contents)
    sha512.update(contents)
    sha384.update(contents)
    sha3_512.update(contents)

print("                                ")
print("  Mobile Forensics - Lab 2 (modified)     ")
print("                               ")
print("   Name:             Alan Pike ")
print("   Student Number:   D16124621 ")
print("                               ")
print("File name: " + my_file)
예제 #36
0
파일: md5.py 프로젝트: shijiehu/hsjtest
import hashlib
print('-----------------------------------------------------------')
m = hashlib.md5()  #创建hash对象,md5:(message-Digest Algorithm 5)消息摘要算法,得出一个128位的密文
print(m)  #<md5 HASH object @ 000000000254ADF0>
m.update('BeginMan'.encode('utf8'))  #更新哈希对象以字符串参数
print(m.digest().decode)  #返回摘要,作为二进制数据字符串值
print(m.hexdigest())  #返回十六进制数字字符串    0b28251e684dfbd9102f8b6f0281c0c5
print(m.digest_size)  #16
print(m.block_size)  #64
a = 'BeginMan国家'
b = a.encode('utf8')
c = b.decode()
print(a.encode('utf8'))
print(b)
print('1111111111' + c)
a = "a test string".encode('utf8')
print('md5     ' + hashlib.md5(a).hexdigest())
#print( hashlib.sha1(a)   )
print('sha1     ' + hashlib.sha1(a).hexdigest())
print('sha224     ' + hashlib.sha224(a).hexdigest())
print('sha256     ' + hashlib.sha256(a).hexdigest())
print('sha384     ' + hashlib.sha384(a).hexdigest())
print('sha512     ' + hashlib.sha512(a).hexdigest())
예제 #37
0
 def sources_digest(self):
     return hashlib.sha384(self._collected_sources_list().encode(
         sys.getfilesystemencoding())).hexdigest()
예제 #38
0
def 加密_SHA(内容, 方式=0):
    '方式: 0.SHA1 1.SHA224 2.SHA256 3.SHA384 4.SHA512'
    字典 = {0: hashlib.sha1(), 1: hashlib.sha224(), 2: hashlib.sha256(), 3: hashlib.sha384(), 4: hashlib.sha512()}
    字典[方式].update(str(内容).encode('utf-8'))
    return 字典[方式].hexdigest()
예제 #39
0
def main():
    argp = ArgumentParser(
        description="Crypt - Decrypt Tool",
        usage=
        "./crypt-decrypt.py [options] [-w word/hash] \nSamples: ./crypt-decrypt.py",
        version="Crypt - Decrypt Tool v" + VERSION)

    argp.add_argument('-e',
                      '--encrypt',
                      dest='encrypt',
                      action='store_true',
                      help='Encrypt word/s (offline mode)')

    argp.add_argument('-d',
                      '--decrypt',
                      dest='decrypt',
                      action='store_true',
                      help='Decrypt a hash')

    argp.add_argument('-i',
                      '--identify',
                      dest='identify',
                      action='store_true',
                      help='Identify type of hash')

    argp.add_argument('-t',
                      '--hash-type',
                      dest='type',
                      help='Hash type to encrypt/decrypt word/hash')

    argp.add_argument('-w',
                      '--word',
                      dest='word',
                      help='Word or hash to encrypt/decrypt/identify')

    argp.add_argument('-o',
                      '--online',
                      dest='online',
                      action='store_true',
                      help='Decrypt online mode')

    argp.add_argument('-f',
                      '--offline',
                      dest='offline',
                      action='store_true',
                      help='Decrypt offline mode')

    argp.add_argument('-l',
                      '--wordlist',
                      dest='wordlist',
                      help='Dictionary to decrypt hash (offline mode only)')

    argp.add_argument('-a',
                      '--all',
                      dest='all',
                      action='store_true',
                      help='Encrypt word/s with all hash types')

    argp.add_argument('-F',
                      '--file',
                      dest='file',
                      help='File with hashes to decrypt/identify')

    args = argp.parse_args()

    if args.encrypt and not args.all and not args.decrypt and not args.identify:  # ENCRYPTER
        alg = args.type.lower()
        word = args.word
        print("\n [+]" + colors.INFO + " Word: " + colors.ENDC + word)
        print(" [+]" + colors.INFO + " Type: " + colors.ENDC + alg)
        if alg == "md5":
            encrypted = hashlib.md5(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "sha1":
            encrypted = hashlib.sha1(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "sha224":
            encrypted = hashlib.sha224(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "sha256":
            encrypted = hashlib.sha256(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "sha384":
            encrypted = hashlib.sha384(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "sha512":
            encrypted = hashlib.sha512(word).hexdigest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        elif alg == "ntlm":
            encrypted = hashlib.new("md4", word.encode("utf-16le")).digest()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + binascii.hexlify(encrypted).upper() +
                  colors.ENDC + "\n")
        elif alg == "lm":
            encrypted = lmhash.encrypt(word).upper()
            print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
                  colors.GREEN + encrypted + colors.ENDC + "\n")
        else:
            print(colors.FAIL + colors.BOLD + "\n[!] Incorrect algorithm!!\n" +
                  colors.ENDC)

    elif args.encrypt and args.all and not args.decrypt and not args.identify:  # ALL TYPES
        word = args.word
        print("\n [+]" + colors.INFO + " Word: " + colors.ENDC + word)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "md5")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.md5(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "sha1")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.sha1(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "sha224")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.sha224(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "sha256")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.sha256(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "sha384")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.sha384(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "sha512")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + hashlib.sha512(word).hexdigest() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "lm")
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + lmhash.encrypt(word).upper() + colors.ENDC)
        print("\n [+]" + colors.INFO + " Type: " + colors.ENDC + "ntlm")
        encrypted = hashlib.new("md4", word.encode("utf-16le")).digest()
        print(colors.GREEN + "   [i]" + colors.INFO + " Hash: " +
              colors.GREEN + binascii.hexlify(encrypted).upper() + colors.ENDC)

    elif args.decrypt and not args.encrypt and not args.identify and not args.file:  # DECRYPTER
        alg = args.type.lower()
        hashs = args.word
        if args.online and not args.offline:  # Online
            print("\n [+]" + colors.INFO + " Hash: " + colors.ENDC + hashs)
            print(" [+]" + colors.INFO + " Type: " + colors.ENDC + alg)
            if alg == "md5":
                md5OnDecrypt(hashs)
                md5OnDecrypt3(hashs)
                md5OnDecrypt4(hashs)
                MultiOnDecrypt2(hashs)
                MultiOnDecrypt3(hashs)
            elif alg == "sha1":
                MultiOnDecrypt2(hashs)
                MultiOnDecrypt3(hashs)
            elif alg == "sha224":
                MultiOnDecrypt3(hashs)
            elif alg == "sha256":
                web = "Sha256/"
                MultiOnDecrypt(hashs, web)
                MultiOnDecrypt2(hashs)
                MultiOnDecrypt3(hashs)
            elif alg == "sha384":
                web = "Sha384/"
                MultiOnDecrypt(hashs, web)
                MultiOnDecrypt2(hashs)
                MultiOnDecrypt3(hashs)
            elif alg == "sha512":
                web = "Sha512/"
                MultiOnDecrypt(hashs, web)
                MultiOnDecrypt2(hashs)
                MultiOnDecrypt3(hashs)
            elif alg == "ntlm":
                web = "Ntlm/"
                MultiOnDecrypt(hashs, web)
            elif alg == "lm":
                print(colors.FAIL + colors.BOLD +
                      "\n[!] Hash type not supported in this mode" +
                      colors.ENDC + "\n")
            else:
                print(colors.FAIL + colors.BOLD +
                      "\n[!] Incorrect algorithm!!" + colors.ENDC)

        elif args.offline and not args.online:  # Offline
            print("\n [+]" + colors.INFO + " Hash: " + colors.ENDC + hashs)
            print(" [+]" + colors.INFO + " Type: " + colors.ENDC + alg)
            if alg == "md5":
                MultiOffDecrypt(hashs, args.wordlist, "md5")
            elif alg == "sha1":
                MultiOffDecrypt(hashs, args.wordlist, "sha1")
            elif alg == "sha224":
                MultiOffDecrypt(hashs, args.wordlist, "sha224")
            elif alg == "sha256":
                MultiOffDecrypt(hashs, args.wordlist, "sha256")
            elif alg == "sha384":
                MultiOffDecrypt(hashs, args.wordlist, "sha384")
            elif alg == "sha512":
                MultiOffDecrypt(hashs, args.wordlist, "sha512")
            elif alg == "ntlm":
                print(colors.FAIL + colors.BOLD +
                      "\n[!] Hash type not supported in this mode" +
                      colors.ENDC + "\n")
            elif alg == "lm":
                lmOffDecryptFile(hashs, args.wordlist)
            else:
                print(colors.FAIL + colors.BOLD +
                      "\n[!] Incorrect algorithm!!" + colors.ENDC)

    elif args.identify and not args.encrypt and not args.decrypt:  # IDENTIFIER
        if args.file:
            with open(args.file, 'r') as f:
                for h in f.readlines():
                    print("\n [+]" + colors.INFO + " Hash: " + colors.GREEN +
                          h.strip("\n") + colors.ENDC)
                    r = commands.getoutput('./hash-identifier.py %s' %
                                           h.strip('\n'))
                    for x in r.split("\n"):
                        if not "Least Possible" in x:
                            print(x + "\n"),
                        else:
                            break
        else:
            r = commands.getoutput('./hash-identifier.py %s' % args.word)
            print(r)

    elif args.file and args.decrypt and not args.encrypt and not args.identify:  # FILE
        alg = args.type
        with open(args.file, 'r') as myfile:
            if args.online:  # Online
                for line in myfile.readlines():
                    if alg == "md5":
                        md5OnDecrypt(line)
                        md5OnDecrypt3(line)
                        md5OnDecrypt4(line)
                        MultiOnDecrypt2(line)
                        MultiOnDecrypt3(line)
                    elif alg == "sha1":
                        MultiOnDecrypt2(line)
                        MultiOnDecrypt3(line)
                    elif alg == "sha224":
                        MultiOnDecrypt3(line)
                    elif alg == "sha256":
                        web = "Sha256/"
                        MultiOnDecrypt(line, web)
                        MultiOnDecrypt2(line)
                        MultiOnDecrypt3(line)
                    elif alg == "sha384":
                        web = "Sha384/"
                        MultiOnDecrypt(line, web)
                        MultiOnDecrypt2(line)
                        MultiOnDecrypt3(line)
                    elif alg == "sha512":
                        web = "Sha512/"
                        MultiOnDecrypt(line, web)
                        MultiOnDecrypt2(line)
                        MultiOnDecrypt3(line)
                    elif alg == "ntlm":
                        web = "Ntlm/"
                        MultiOnDecrypt(line, web)
                    elif alg == "lm":
                        print(colors.FAIL + colors.BOLD +
                              "\n[!] Hash type not supported in this mode" +
                              colors.ENDC + "\n")
                    else:
                        print(colors.FAIL + colors.BOLD +
                              "\n[!] Incorrect algorithm!!" + colors.ENDC)

            elif args.offline:  # Offline
                for line in myfile.readlines():
                    line = line.strip("\n")
                    print("\n [+]" + colors.INFO + " Hash: " + colors.ENDC +
                          line)
                    print(" [+]" + colors.INFO + " Type: " + colors.ENDC +
                          args.type)
                    if alg == "md5":
                        MultiOffDecrypt(line, args.wordlist, "md5")
                    elif alg == "sha1":
                        MultiOffDecrypt(line, args.wordlist, "sha1")
                    elif alg == "sha224":
                        MultiOffDecrypt(line, args.wordlist, "sha224")
                    elif alg == "sha256":
                        MultiOffDecrypt(line, args.wordlist, "sha256")
                    elif alg == "sha384":
                        MultiOffDecrypt(line, args.wordlist, "sha384")
                    elif alg == "sha512":
                        MultiOffDecrypt(line, args.wordlist, "sha512")
                    elif alg == "ntlm":
                        print(colors.FAIL + colors.BOLD +
                              "\n[!] Hash type not supported in this mode" +
                              colors.ENDC + "\n")
                    elif alg == "lm":
                        lmOffDecryptFile(line, args.wordlist)
                    else:
                        print(colors.FAIL + colors.BOLD +
                              "\n[!] Incorrect algorithm!!" + colors.ENDC)

    else:
        print(SAMPLES)
예제 #40
0
|  [  sha1  ]    [ sha224 ]  |
|  [ sha384 ]    [ sha256 ]  |
|  [ sha512 ]    [   md5  ]  |
|--------<<<<<[]>>>>>--------|
>\> select hash: '''))
    if hash == 'sha1':
        sha1_encrypt = (raw_input("sha1 encrypt = "))  #input string
        print ">|>", "[", hashlib.sha1(
            sha1_encrypt).hexdigest(), "]"  #output md5 encrypt
    elif hash == 'sha224':
        sha224_encrypt = (raw_input("sha224 encrypt = "))  #input string
        print ">|>", "[", hashlib.sha224(
            sha224_encrypt).hexdigest(), "]"  #output sha224 encrypt
    elif hash == 'sha384':
        sha384_encrypt = (raw_input("sha384_encrypt = "))
        print ">|>", "[", hashlib.sha384(sha384_encrypt).hexdigest(), "]"
    elif hash == 'sha256':
        sha256_encrypt = (raw_input("sha256 encrypt = "))
        print ">|>", "[", hashlib.sha256(sha256_encrypt).hexdigest(), "]"
    elif hash == 'sha512':
        sha512_encrypt = (raw_input("sha512 encrypt = "))
        print ">|>", "[", hashlib.sha512(sha512_encrypt).hexdigest(), "]"
    elif hash == 'md5':
        md5_encrypt = (raw_input("md5 encrypt = "))
        print ">|>", "[", hashlib.md5(md5_encrypt).hexdigest(), "]"
    else:
        print("Yang Benar dong Sayangg")
    exit = raw_input('''|--------<<<<<[]>>>>>--------|
[ 1.restart ]
[ 2.exit ]
>\> ''')
예제 #41
0
def sha384_hash():
    string = args[2]
    string_bytes = string.encode('utf-8')

    sha384_data = hashlib.sha384(string_bytes).hexdigest()
    print('\n[+] Hash: ' + str(sha384_data + '\n'))
예제 #42
0
# ######## sha1 ########

hash1 = hashlib.sha1()
hash1.update(b"admin")
print(hash1.hexdigest())

# ######## sha256 ########

hash2 = hashlib.sha256()
hash2.update(b"admin")
print(hash2.hexdigest())

# ######## sha384 ########

hash3 = hashlib.sha384()
hash3.update(b"admin")
print(hash3.hexdigest())

# ######## sha512 ########

hash4 = hashlib.sha512()
hash4.update(b"admin")
print(hash4.hexdigest())

#python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
import hmac
h = hmac.new('wueiqi'.encode('utf-8'))
h.update('hellowo'.encode('utf-8'))
print(h.hexdigest())
예제 #43
0
import hashlib
print(hashlib.sha384(input().encode()).hexdigest())
예제 #44
0
                          '968e7bdaeac9f29a97730ce5add8a5627c14c3532c7880d88c8f56099f8ed65275a4c9e2cb93b70c3d7c904677' \
                          '639fac7962c537f5bfaf2f12859d0dacb7c403ee59da0922715bba0a6f5202d7c653833e39715f04664c2396c4' \
                          '7bdf3f09f5486d8f6aea767ba011f1a5a10c8b57f079aea58abfd5e50ef20aa5e09b1082f6af98e806c9aeeb89' \
                          '4148a7d82cd6e1443c6115eb567fba0eacf5b7178518b8ba312da6ace22238d1ed19f3e703652576a6152ba60d' \
                          '4d4c6bc75b3ee7c8efeadee0c5ed7c14bf2930a6c4f13137becf38912f49c5'
HEXSTR_PRIVATE_PRIME_P = 'dee90ee63c12729a3fe7d38c581abf7e1c784ec0bd4bfdd1282286ea9996673942a24c7c98b31c6cd12db8ba96d' \
                         'a785c4392569d7bfc2be9d9907c3b7fbf40d31891642952a0e5a23dfbe721a746588df9a246ea4936a1958f66fd' \
                         '3a32c08008a0f6ed9b516fa869fb08a57ef31c0ec217f173e489a2f8f111e25c25c961c2b7'
HEXSTR_PRIVATE_PRIME_Q = 'c53b9c8dfb3dda04d16c7f779a02b3b8c7b44bf876dc88ad562778eafaded9ade882ccfb887761515a251c22476' \
                         '1bef7207fa489e398041787cfbd155f1034a207d517f06bc76a044262484f82f0c6a887f776b1dce837408999d8' \
                         '8dd33a96c7f80e23719e77a11075d337bf9cc47d7dbf98e341b81c23f165dd15ccfd2973ab'

TEST_MD5 = hashlib.md5(b'test').hexdigest()
TEST_SHA1 = hashlib.sha1(b'test').hexdigest()
TEST_SHA256 = hashlib.sha256(b'test').hexdigest()
TEST_SHA384 = hashlib.sha384(b'test').hexdigest()
TEST_SHA512 = hashlib.sha512(b'test').hexdigest()

class CryptoModelTest(s_t_utils.SynTest):

    async def test_model_crypto_currency(self):

        async with self.getTestCore() as core:

            nodes = await core.nodes('[ crypto:currency:client=(1.2.3.4, (btc, 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2)) ]')
            self.len(1, nodes)

            nodes = await core.nodes('inet:client=1.2.3.4 -> crypto:currency:client -> crypto:currency:address')
            self.eq(nodes[0].get('coin'), 'btc')
            self.eq(nodes[0].get('iden'), '1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2')
예제 #45
0
def register_form(request):
    if request.POST:

        email = request.POST.get('email', None)
        #
        #
        #

        if email is not None:
            reg_form = RegisterForm(request.POST)

            chk_email = check_registered_email(email)

            if chk_email == 2:
                return HttpResponse("Email is already registered")

            elif chk_email == 3:
                return HttpResponse("Email cannot be blank")
            else:

                if reg_form.is_valid():
                    reg = reg_form.save(commit=False)
                    reg.is_staff = False
                    reg.is_superuser = False

                    reg.save()

                    path = os.path.join(settings.MEDIA_ROOT, str(reg.id))
                    os.mkdir(path, 0o777)

                    profile = Profile(user=reg)

                    profile.save()

                    #
                    # Send confirmation email
                    #

                    user = CustomUser.objects.get(email=email)
                    profile = Profile.objects.get(user_id=user.pk)
                    uid = profile.uid

                    hashstr = uid + "<_secret_>" + settings.SECRET_KEY
                    hashstr = hashlib.sha384(hashstr.encode())
                    hashstr = hashstr.hexdigest()

                    conf_email = ConfirmEmail(user=user, key=hashstr)

                    conf_email.save()

                    send_email_from_app(email,
                                        uid,
                                        hashstr,
                                        template='app/users/welcome.html')

                    return HttpResponse(json.dumps({'code': '1', 'error': ''}))

                else:
                    return HttpResponse(
                        json.dumps({
                            'code':
                            '0',
                            'error':
                            safestring.mark_safe(reg_form.errors)
                        }))

        else:
            return HttpResponse("Email cannot be blank")
예제 #46
0
if argumento == '-s':
    if not len(sys.argv[4:]):
        usage()
    lista = sys.argv[4]
    with open(lista, 'r') as arquivo:
        for palavra in arquivo:
            sEnter = palavra.strip()
            texto = sEnter.encode()
            if opcao_hash == 'sha-1':
                hash = hashlib.sha1(texto)
            if opcao_hash == 'sha-224':
                hash = hashlib.sha224(texto)
            if opcao_hash == 'sha-256':
                hash = hashlib.sha256(texto)
            if opcao_hash == 'sha-384':
                hash = hashlib.sha384(texto)
            if opcao_hash == 'sha-512':
                hash = hashlib.sha512(texto)
            if opcao_hash == 'sha-3-224':
                hash = hashlib.sha3_224(texto)
            if opcao_hash == 'sha-3-256':
                hash = hashlib.sha3_256(texto)
            if opcao_hash == 'sha-3-384':
                hash = hashlib.sha3_384(texto)
            if opcao_hash == 'sha-3-512':
                hash = hashlib.sha3_512(texto)
            if opcao_hash == 'blake-2b':
                hash = hashlib.blake2b(texto)
            if opcao_hash == 'blake-2S':
                hash = hashlib.blake2s(texto)
            if opcao_hash == 'md5':
예제 #47
0
names = [
    'Harry', 'Oliver', 'Jack', 'Charlie', 'Thomas', 'Jacob', 'Alfie', 'Riley',
    'William', 'James', 'Amelia', 'Olivia', 'Jessica', 'Emily', 'Lily', 'Ava',
    'Heather', 'Sophie', 'Mia', 'Isabella'
]

index = random.randint(10, 10000)

if alg == 'sha-1':
    pre_hash = hashlib.sha1(str(index).encode()).hexdigest()
elif alg == 'sha-224':
    pre_hash = hashlib.sha224(str(index).encode()).hexdigest()
elif alg == 'sha-256':
    pre_hash = hashlib.sha256(str(index).encode()).hexdigest()
elif alg == 'sha-384':
    pre_hash = hashlib.sha384(str(index).encode()).hexdigest()
elif alg == 'sha-512':
    pre_hash = hashlib.sha512(str(index).encode()).hexdigest()
elif alg == 'MD5':
    pre_hash = hashlib.md5(str(index).encode()).hexdigest()
pre_hash = '0000' + pre_hash[4:]
creator = random.choice(names)
data = []
for i in range(index % 10 + 1):
    tx = {
        'from': random.choice(names),
        'to': random.choice(names),
        'value': random.randint(100, 5000)
    }
    data.append(tx)
예제 #48
0
def calc(ch):
    return hashlib.sha384(str(ch).encode('ascii')).hexdigest()
예제 #49
0
    elif (a == '2'):
        print(colored("\n[*]~$ SHA1 Hash is Selected", 'cyan'))
        a2 = input("\n[*] Enter the word : ")
        b2 = hashlib.sha1(a2.encode("UTF-8")).hexdigest()
        print(colored("\nHash : " + b2, 'green'))
    elif (a == '3'):
        print(colored("\n[*]~$ SHA224 Hash is Selected", 'cyan'))
        a3 = input("\n[*] Enter the word : ")
        b3 = hashlib.sha224(a3.encode()).hexdigest()
        print(colored("\nHash : " + b3, 'green'))
    elif (a == '4'):
        print(colored("\n[*]~$ SHA256 Hash is Selected", 'cyan'))
        a4 = input("\n[*] Enter the word : ")
        b4 = hashlib.sha256(a4.encode()).hexdigest()
        print(colored("\nHash : " + b4, 'green'))
    elif (a == '5'):
        print(colored("\n[*]~$ SHA384 Hash is Selected", 'cyan'))
        a5 = input("\n[*] Enter the word : ")
        b5 = hashlib.sha384(a5.encode()).hexdigest()
        print(colored("\nHash : " + b5, 'green'))
    elif (a == '6'):
        print(colored("\n[*]~$ SHA512 Hash is Selected", 'cyan'))
        a6 = input("\n[*] Enter the word : ")
        b6 = hashlib.sha512(a6.encode()).hexdigest()
        print(colored("\nHash : " + b6, 'green'))
    elif (a == '0'):
        print("\n\33[32mHad a good work with you, Good-bye ('-')\33[0m")
        break
    else:
        print(colored("\n ------- Invalid Option,Try again ------- \n", 'red'))
예제 #50
0
import hashlib

print hashlib.sha384(raw_input()).hexdigest()
예제 #51
0
"""
import hashlib

from ..__common__ import add, b, PY3

add("sha1",
    lambda s, error="strict": (hashlib.sha1(b(s)).hexdigest(), len(s)),
    guess=None)
add("sha224",
    lambda s, error="strict": (hashlib.sha224(b(s)).hexdigest(), len(s)),
    guess=None)
add("sha256",
    lambda s, error="strict": (hashlib.sha256(b(s)).hexdigest(), len(s)),
    guess=None)
add("sha384",
    lambda s, error="strict": (hashlib.sha384(b(s)).hexdigest(), len(s)),
    guess=None)
add("sha512",
    lambda s, error="strict": (hashlib.sha512(b(s)).hexdigest(), len(s)),
    guess=None)

if PY3:
    add("sha3_224",
        lambda s, error="strict": (hashlib.sha3_224(b(s)).hexdigest(), len(s)),
        pattern=r"^sha3[-_]224$",
        guess=None)
    add("sha3_256",
        lambda s, error="strict": (hashlib.sha3_256(b(s)).hexdigest(), len(s)),
        pattern=r"^sha3[-_]256$",
        guess=None)
    add("sha3_384",
 def verify(self):
     if not ca_list:
         self.error = "Trusted certificate authorities list not found"
         return False
     paymntreq = pb2.PaymentRequest()
     paymntreq.ParseFromString(self.raw)
     if not paymntreq.signature:
         self.error = "No signature"
         return
     cert = pb2.X509Certificates()
     cert.ParseFromString(paymntreq.pki_data)
     cert_num = len(cert.certificate)
     x509_chain = []
     for i in range(cert_num):
         x = x509.X509()
         x.parseBinary(bytearray(cert.certificate[i]))
         x509_chain.append(x)
         if i == 0:
             try:
                 x.check_date()
             except Exception as e:
                 self.error = str(e)
                 return
             self.requestor = x.get_common_name()
             if self.requestor.startswith('*.'):
                 self.requestor = self.requestor[2:]
         else:
             if not x.check_ca():
                 self.error = "ERROR: Supplied CA Certificate Error"
                 return
     if not cert_num > 1:
         self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
         return False
     # if the root CA is not supplied, add it to the chain
     ca = x509_chain[cert_num - 1]
     if ca.getFingerprint() not in ca_list:
         keyID = ca.get_issuer_keyID()
         f = ca_keyID.get(keyID)
         if f:
             root = ca_list[f]
             x509_chain.append(root)
         else:
             self.error = "Supplied CA Not Found in Trusted CA Store."
             return False
     # verify the chain of signatures
     cert_num = len(x509_chain)
     for i in range(1, cert_num):
         x = x509_chain[i]
         prev_x = x509_chain[i - 1]
         algo, sig, data = prev_x.get_signature()
         sig = bytearray(sig)
         pubkey = x.publicKey
         if algo == x509.ALGO_RSA_SHA1:
             verify = pubkey.hashAndVerify(sig, data)
         elif algo == x509.ALGO_RSA_SHA256:
             hashBytes = bytearray(hashlib.sha256(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA256 + hashBytes)
         elif algo == x509.ALGO_RSA_SHA384:
             hashBytes = bytearray(hashlib.sha384(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA384 + hashBytes)
         elif algo == x509.ALGO_RSA_SHA512:
             hashBytes = bytearray(hashlib.sha512(data).digest())
             verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA512 + hashBytes)
         else:
             self.error = "Algorithm not supported"
             util.print_error(self.error,
                              algo.getComponentByName('algorithm'))
             return False
         if not verify:
             self.error = "Certificate not Signed by Provided CA Certificate Chain"
             return False
     # verify the BIP70 signature
     pubkey0 = x509_chain[0].publicKey
     sig = paymntreq.signature
     paymntreq.signature = ''
     s = paymntreq.SerializeToString()
     sigBytes = bytearray(sig)
     msgBytes = bytearray(s)
     if paymntreq.pki_type == "x509+sha256":
         hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
         verify = pubkey0.verify(sigBytes,
                                 x509.PREFIX_RSA_SHA256 + hashBytes)
     elif paymntreq.pki_type == "x509+sha1":
         verify = pubkey0.hashAndVerify(sigBytes, msgBytes)
     else:
         self.error = "ERROR: Unsupported PKI Type for Message Signature"
         return False
     if not verify:
         self.error = "ERROR: Invalid Signature for Payment Request Data"
         return False
     ### SIG Verified
     self.error = 'Signed by Trusted CA: ' + ca.get_common_name()
     return True
예제 #53
0
 def get_new_connection(self, conn_params):
     conn = Database.connect(**conn_params)
     if PY38:
         create_deterministic_function = functools.partial(
             conn.create_function,
             deterministic=True,
         )
     else:
         create_deterministic_function = conn.create_function
     create_deterministic_function('django_date_extract', 2, _sqlite_datetime_extract)
     create_deterministic_function('django_date_trunc', 2, _sqlite_date_trunc)
     create_deterministic_function('django_datetime_cast_date', 3, _sqlite_datetime_cast_date)
     create_deterministic_function('django_datetime_cast_time', 3, _sqlite_datetime_cast_time)
     create_deterministic_function('django_datetime_extract', 4, _sqlite_datetime_extract)
     create_deterministic_function('django_datetime_trunc', 4, _sqlite_datetime_trunc)
     create_deterministic_function('django_time_extract', 2, _sqlite_time_extract)
     create_deterministic_function('django_time_trunc', 2, _sqlite_time_trunc)
     create_deterministic_function('django_time_diff', 2, _sqlite_time_diff)
     create_deterministic_function('django_timestamp_diff', 2, _sqlite_timestamp_diff)
     create_deterministic_function('django_format_dtdelta', 3, _sqlite_format_dtdelta)
     create_deterministic_function('regexp', 2, _sqlite_regexp)
     create_deterministic_function('ACOS', 1, none_guard(math.acos))
     create_deterministic_function('ASIN', 1, none_guard(math.asin))
     create_deterministic_function('ATAN', 1, none_guard(math.atan))
     create_deterministic_function('ATAN2', 2, none_guard(math.atan2))
     create_deterministic_function('BITXOR', 2, none_guard(operator.xor))
     create_deterministic_function('CEILING', 1, none_guard(math.ceil))
     create_deterministic_function('COS', 1, none_guard(math.cos))
     create_deterministic_function('COT', 1, none_guard(lambda x: 1 / math.tan(x)))
     create_deterministic_function('DEGREES', 1, none_guard(math.degrees))
     create_deterministic_function('EXP', 1, none_guard(math.exp))
     create_deterministic_function('FLOOR', 1, none_guard(math.floor))
     create_deterministic_function('LN', 1, none_guard(math.log))
     create_deterministic_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))
     create_deterministic_function('LPAD', 3, _sqlite_lpad)
     create_deterministic_function('MD5', 1, none_guard(lambda x: hashlib.md5(x.encode()).hexdigest()))
     create_deterministic_function('MOD', 2, none_guard(math.fmod))
     create_deterministic_function('PI', 0, lambda: math.pi)
     create_deterministic_function('POWER', 2, none_guard(operator.pow))
     create_deterministic_function('RADIANS', 1, none_guard(math.radians))
     create_deterministic_function('REPEAT', 2, none_guard(operator.mul))
     create_deterministic_function('REVERSE', 1, none_guard(lambda x: x[::-1]))
     create_deterministic_function('RPAD', 3, _sqlite_rpad)
     create_deterministic_function('SHA1', 1, none_guard(lambda x: hashlib.sha1(x.encode()).hexdigest()))
     create_deterministic_function('SHA224', 1, none_guard(lambda x: hashlib.sha224(x.encode()).hexdigest()))
     create_deterministic_function('SHA256', 1, none_guard(lambda x: hashlib.sha256(x.encode()).hexdigest()))
     create_deterministic_function('SHA384', 1, none_guard(lambda x: hashlib.sha384(x.encode()).hexdigest()))
     create_deterministic_function('SHA512', 1, none_guard(lambda x: hashlib.sha512(x.encode()).hexdigest()))
     create_deterministic_function('SIGN', 1, none_guard(lambda x: (x > 0) - (x < 0)))
     create_deterministic_function('SIN', 1, none_guard(math.sin))
     create_deterministic_function('SQRT', 1, none_guard(math.sqrt))
     create_deterministic_function('TAN', 1, none_guard(math.tan))
     # Don't use the built-in RANDOM() function because it returns a value
     # in the range [2^63, 2^63 - 1] instead of [0, 1).
     conn.create_function('RAND', 0, random.random)
     conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev))
     conn.create_aggregate('STDDEV_SAMP', 1, list_aggregate(statistics.stdev))
     conn.create_aggregate('VAR_POP', 1, list_aggregate(statistics.pvariance))
     conn.create_aggregate('VAR_SAMP', 1, list_aggregate(statistics.variance))
     conn.execute('PRAGMA foreign_keys = ON')
     return conn
예제 #54
0
def process(i):
    hash = hashlib.sha384(str(i).encode('ascii')).digest()
    return base64.b64encode(hash).decode('ascii')
예제 #55
0
def _hash(key):
    return sha384(key).hexdigest()[:16]
예제 #56
0
        if REMOTE:
            conn.close()
        continue

    K = list(factor(magic))
    if K[-1][0] > (2**120):
        if REMOTE:
            conn.close()
        continue

    print(K)

    while True:
        dat = os.urandom(48)
        data_num = bytes_to_long(dat)
        data2 = hashlib.sha384(dat).digest()
        data2_num = bytes_to_long(data2)

        if data2_num >= N:
            continue

        cnt += 1
        print("trial: ", cnt)
        print(dat, data2)

        e = None
        try:
            e = GF(N)(data2_num).log(GF(N)(data_num))
        except:
            pass
        if e != None and pow(data_num, e, N) == data2_num:
예제 #57
0
 def setup(self, arg):
     self.h = hashlib.sha384()
예제 #58
0
            if arguments[num0] == "-H"or arguments[num0] == "--hash":
                data = data.encode()
                hashed = sha224(data).hexdigest()

                print(f"\n{bcolors.GREEN +'[*] Hashing function used'+ bcolors.ENDC} ==> {bcolors.YELLOW +arguments[num + 1]+ bcolors.ENDC}")
                print(f"{bcolors.GREEN +'[*] Data to be Hashed'+ bcolors.ENDC} ==> {bcolors.YELLOW +arguments[num0 + 1]+ bcolors.ENDC}")

                print(f"\n{bcolors.BLUE +'[HASH] -->'+ bcolors.ENDC}\n\n{hashed}\n")

            else:
                help()

        elif arguments[num + 1] == "sha384":
            if arguments[num0] == "-H"or arguments[num0] == "--hash":
                data = data.encode()
                hashed = sha384(data).hexdigest()

                print(f"\n{bcolors.GREEN +'[*] Hashing function used'+ bcolors.ENDC} ==> {bcolors.YELLOW +arguments[num + 1]+ bcolors.ENDC}")
                print(f"{bcolors.GREEN +'[*] Data to be Hashed'+ bcolors.ENDC} ==> {bcolors.YELLOW +arguments[num0 + 1]+ bcolors.ENDC}")

                print(f"\n{bcolors.BLUE +'[HASH] -->'+ bcolors.ENDC}\n\n{hashed}\n")

            else:
                help()

        elif arguments[num + 1] == "md5":
            if arguments[num0] == "-H"or arguments[num0] == "--hash":
                data = data.encode()
                hashed = md5(data).hexdigest()

                print(f"\n{bcolors.GREEN +'[*] Hashing function used'+ bcolors.ENDC} ==> {bcolors.YELLOW +arguments[num + 1]+ bcolors.ENDC}")
예제 #59
0
def get_lbry_hash_obj():
    return hashlib.sha384()
예제 #60
0
 def sha384(self):
     cret = hashlib.sha384()
     cret.update(self.data.encode("utf-8"))
     auth_run.desc(self,self.type,cret)