def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." if (hasattr(self.body, 'read')): BLOCKSIZE = 65536 hasher = sha() buf = self.body.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = self.body.read(BLOCKSIZE) self.body.seek(0) self['oauth_body_hash'] = base64.b64encode(hasher.digest()) else: self['oauth_body_hash'] = base64.b64encode(sha(to_utf8_if_string(self.body)).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token)
def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = str( base64.b64encode(sha(self.body.encode()).digest()).decode()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name oauth_signature = signature_method.sign(self, consumer, token) #print("type of 'oauth_signature': "+str(type(oauth_signature))) if str(type(oauth_signature)) == "<class 'bytes'>": oauth_signature = oauth_signature.decode() #print("'oauth_signature: "+oauth_signature) else: oauth_signature = oauth_signature #print("'oauth_signature: "+oauth_signature) # oauth_signature = oauth_signature # print("'oauth_signature2:"+oauth_signature) self['oauth_signature'] = oauth_signature
def hashSha512(password, salt='', n=12): from hashlib import sha512 salt = salt or sha(urandom(40)).hexdigest() hashed = sha512(salt + password).hexdigest() for i in xrange(n): hashed = sha512(hashed + salt).hexdigest() return '$sha512$%i$%s$%s' % (n, salt, hashed)
def hash_sha512(password, salt='', n=12): from hashlib import sha512 salt = salt or sha(urandom(40)).hexdigest() hashed = sha512(salt + password).hexdigest() for i in xrange(n): hashed = sha512(hashed + salt).hexdigest() return '$sha512$%i$%s$%s' % (n, salt, hashed)
def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = str(base64.b64encode(sha(self.body.encode()).digest()).decode()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name oauth_signature = signature_method.sign(self, consumer, token) #print("type of 'oauth_signature': "+str(type(oauth_signature))) if str(type(oauth_signature)) == "<class 'bytes'>": oauth_signature = oauth_signature.decode() #print("'oauth_signature: "+oauth_signature) else: oauth_signature = oauth_signature #print("'oauth_signature: "+oauth_signature) # oauth_signature = oauth_signature # print("'oauth_signature2:"+oauth_signature) self['oauth_signature'] = oauth_signature
def sign(self, request, consumer, token): """Builds the base signature string.""" if RSA is None: raise NotImplementedError, self.name key, raw = self.signing_base(request, consumer, token) digest = sha(raw).digest() sig = key.sign(self._pkcs1imify(key, digest), '')[0] sig_bytes = long_to_bytes(sig) # Calculate the digest base 64. return binascii.b2a_base64(sig_bytes)[:-1]
def new(arg=None): """Return a new sha crypto object. If arg is present, the method call update(arg) is made. """ crypto = sha() if arg: crypto.update(arg) return crypto
def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" if RSA is None: raise NotImplementedError, self.name key, raw = self.signing_base(request, consumer, token) digest = sha(raw).digest() sig = bytes_to_long(binascii.a2b_base64(signature)) data = self._pkcs1imify(key, digest) pubkey = key.publickey() return pubkey.verify(data, (sig,))
def getHash(self): """Returns the torrent hash. Adapted from btshowmetainfo.py. """ metainfo_file = open(self.torrentFile, 'rb') metainfo = bdecode(metainfo_file.read()) metainfo_file.close() announce = metainfo['announce'] info = metainfo['info'] #print info info_hash = sha(bencode(info)) return info_hash.hexdigest()
def fillin_torrent_fields(self): ## borrowed this from BitTornado try: # metainfo_file = open(self.get_file_path_filename(), 'rb') metainfo_file = open(self.file_path.path, 'rb') metainfo = bdecode(metainfo_file.read()) # note, this will only work for single file torrents which have the length key in the info dictionary info = metainfo['info'] if info.has_key('length'): self.info_hash = sha(bencode(info)).hexdigest() self.piece_length = info['piece length'] self.announce = metainfo['announce'] self.size = info['length'] self.name = info['name'] except: raise
def sign_request(self, request): """Signs the request using `self.signature`, `self.consumer` and `self.token` for OAuth authentication handling. This basically means generating and adding `oauth_signature_method` and `oauth_signature` to `request.params`. """ if not request.method == "POST": # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." if request._enc_data is None: request._enc_data = '' request.params['oauth_body_hash'] = base64.b64encode(sha(request._enc_data).digest()) request.params['oauth_signature_method'] = self.signature.name request.params['oauth_signature'] = self.signature.sign(request, self.consumer, self.token)
def read(self, file0): file1 = open(file0, 'rb') if file1.read(11) != 'd8:announce': print('%s: Not a BitTorrent metainfo file' % file0) return file1.seek(0) metainfo = bdecode(file1.read()) file1.close() logging.debug("metainfo: {0}".format(metainfo)) self.file0 = file0; self.info = metainfo['info'] self.announce = metainfo['announce'] self.info_hash = sha(bencode(self.info)) self.piece_length = self.info['piece length'] return
def _make_token(user, timestamp): ts_b36 = web.to36(timestamp) # By hashing on the internal state of the user and using state # that is sure to change (the password hash and the last_login) # we produce a hash that will be invalid as soon as it --or the old # password-- is used. # By hashing also a secret key the system cannot be subverted # even if the database is compromised. items = [ web.config.session_parameters.secret_key, unicode(user.id), u'@', user.password, unicode(user.last_login_at), unicode(timestamp), ] hash = sha(''.join(items)).hexdigest() return "%s$%s" % (ts_b36, hash)
def maketorrent(self, filename, request, msg): self._logger.debug('Going to make torrent: %s', filename) def dc(v): #print v pass def prog(amount): #print '%.1f%% complete\r' % (amount * 100), #self._logger.debug('%.1f%% complete', amount * 100) pass config = self.maketorent_config trackers = msg['args']['trackers'] if trackers: tracker = trackers[0] else: tracker = config['tracker_name'] msg['trackers'] = [tracker] try: meta = make_meta_files(bytes(tracker), [filename], progressfunc=prog, filefunc=dc, piece_len_pow2=config['piece_size_pow2'], comment=config['comment'], target=config['target'], filesystem_encoding=config['filesystem_encoding'], use_tracker=config['use_tracker'], data_dir=config['data_dir']) metainfo_file = open(filename + '.torrent', 'rb') metainfo = bdecode(metainfo_file.read()) metainfo_file.close() info = metainfo['info'] info_hash = sha(bencode(info)) msg['args']['sha1'] = info_hash.hexdigest() msg['result'] = 'success' except BTFailure, e: msg['result'] = 'failed' msg['traceback'] = "Excepition BTFailure: %s" % str(e)
def torrent_info(request, filename): metaname = settings.MEDIA_ROOT + filename metafile = open(metaname, "rb") metainfo = bdecode(metafile.read()) metafile.close() info = metainfo['info'] info_hash = sha(bencode(info)).hexdigest() title = metainfo.get('title', '') #filename piece_length = info['piece length'] if info.has_key('length'): # single file mode path_name = '' files = [ { 'fname':info['name'], 'length':info['length'], 'content_type':info.get('content_type','') }, ] file_length = info['length'] else: # multiple files mode path_name = info['name'] files = [] file_length = 0 for file in info['files']: path = "/".join( file["path"] ) files.append( { 'fname':path, 'length':file['length'], 'content_type':file.get('content_type',''), } ) file_length += file['length'] piece_number, last_piece_length = divmod(file_length, piece_length) announce = metainfo.get('announce','') announce_list = metainfo.get('announce-list','') nodes = map(lambda n:{'ip':n[0], 'port':n[1]}, metainfo['nodes']) comment = metainfo.get('comment','') url_list = metainfo.get('url-list', '') create_date = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(metainfo.get('creation date', 0))) return render_to_response('bitinfo/torrent_info.html', locals(), RequestContext(request) )
def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token)
def ChecksumBuilder(target, source, env): # Read source contents content = open(str(source[0])).read() sum = None # Retrieve extension. file, ext = os.path.splitext(str(target[0])) # Process checksum request. if ext == ".md5": sum = md5(content).hexdigest() elif ext == ".sha1": sum = sha(content).hexdigest() # Write to output file. out = open(str(target[0]), "w") out.write(sum + " " + str(source[0]) + "\n") out.close()
def sign_request(self, request): """Signs the request using `self.signature`, `self.consumer` and `self.token` for OAuth authentication handling. This basically means generating and adding `oauth_signature_method` and `oauth_signature` to `request.params`. """ if not request.method == "POST": # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." if request._enc_data is None: request._enc_data = '' request.params['oauth_body_hash'] = base64.b64encode( sha(request._enc_data).digest()) request.params['oauth_signature_method'] = self.signature.name request.params['oauth_signature'] = self.signature.sign( request, self.consumer, self.token)
def checksum(filename, md5_hashes, sha_hashes, verbose=False): s = sha() m = md5() m.update(file(filename, "r").read()) fname = os.path.basename(filename) rc = 1 if (fname in md5_hashes) and md5_hashes[fname] == m.hexdigest(): s.update(file(filename, "r").read()) if (fname in sha_hashes) and sha_hashes[fname] == s.hexdigest(): rc = 0 if verbose: print("File: %s" % fname) print(" MD5 : %s" % m.hexdigest()) print(" SHA1: %s" % s.hexdigest()) print("Recipies:") print(" MD5 : %s" % (fname in md5_hashes and md5_hashes[fname] or "Not Found")) print(" SHA1: %s" % (fname in sha_hashes and sha_hashes[fname] or "Not Found")) if rc == 0: print("FOR THE WIN!") else: print("FAIL") return rc
def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." hsh = sha() #pylint: disable-msg=E1103 if self.body and hasattr(self.body, 'tell'): # remenber current pos curpos = self.body.tell() while(True): # read chunks (128Kb) chunk = self.body.read(READ_BUFFER_CHUNK_SIZE) if chunk == '': break # update hash hsh.update(chunk) # reset seek self.body.seek(curpos) else: # default implementation hsh.update(self.body) self['oauth_body_hash'] = base64.b64encode(hsh.digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token)
def create_checksum(filename, directory, md5file, shafile, verbose=False): md5_hashes = load_hashes(md5file) sha_hashes = load_hashes(shafile) if directory: abspath = os.path.abspath(directory) files = [ (f, os.path.join(abspath, f)) for f in os.listdir(abspath) if not f.startswith(".") and os.path.isfile(os.path.join(abspath, f)) ] else: abspath = os.path.abspath(filename) files = [(os.path.basename(baspath), abspath)] for f, fpath in files: if os.path.isfile(fpath) and not f.startswith("."): # Create the MD5 Hash m = md5() m.update(open(fpath, "rb").read()) md5_hashes[f] = m.hexdigest() # Create the SHA Hash s = sha() s.update(open(fpath, "rb").read()) sha_hashes[f] = s.hexdigest() if verbose: print("File: %s" % f) print(" MD5 : %s" % md5_hashes[f]) print(" SHA1: %s" % sha_hashes[f]) continue # Save pickle files mfile = gzip.open(md5file, "wb") sfile = gzip.open(shafile, "wb") pickle.dump(md5_hashes, mfile, pickle.HIGHEST_PROTOCOL) pickle.dump(sha_hashes, sfile, pickle.HIGHEST_PROTOCOL) mfile.close() sfile.close() return 0
def sha_key(self, key, secret_word): crypted_string = self.shuffle_word(key + str(time.time()) + secret_word) return sha(crypted_string).hexdigest()
# write out to a local file of = open( filestr, "wb" ) of.write( f.read() ) of.close() metainfo_name = filestr # owners have to match if not isFileOwnerCurrentUser( metainfo_name ): print 'You do not own torrent \'%s\'' % metainfo_name continue metainfo_file = open(metainfo_name, 'rb') metainfo = bdecode(metainfo_file.read()) metainfo_file.close() info = metainfo['info'] info_hash = sha( bencode( info ) ).hexdigest() # allowed tracker? if not isTrackerAllowed( metainfo['announce'] ): print 'Tracker for \'%s\' is not allowed.' % info['name'] continue ## make sure we havent downloaded this already if checkDownloadStatus( info ) and not forceDownload: print "A torrent with the hash %s has already been downloaded." % info_hash else: if info.has_key('length'): fileSize = info['length'] else: fileSize = 0; for file in info['files']:
def random_password(): """ Generate a random secure password. """ return sha(urandom(40)).hexdigest()
def hash_sha1(password, salt='', n=12): salt = salt or sha(urandom(32)).hexdigest() hashed = sha(salt + password).hexdigest() for i in xrange(n): hashed = sha(hashed + salt).hexdigest() return '$sha1$%i$%s$%s' % (n, salt, hashed)
print '%s %s - decode BitTorrent metainfo files' % (NAME, VERSION) print if len(argv) == 1: print '%s file1.torrent file2.torrent file3.torrent ...' % argv[0] print exit(2) # common exit code for syntax error for metainfo_name in argv[1:]: metainfo_file = open(metainfo_name, 'rb') metainfo = bdecode(metainfo_file.read()) metainfo_file.close() announce = metainfo['announce'] info = metainfo['info'] info_hash = sha(bencode(info)) print 'metainfo file.: %s' % basename(metainfo_name) print 'info hash.....: %s' % info_hash.hexdigest() piece_length = info['piece length'] if info.has_key('length'): # let's assume we just have a file print 'file name.....: %s' % info['name'] file_length = info['length'] name ='file size.....:' else: # let's assume we have a directory structure print 'directory name: %s' % info['name'] print 'files.........: ' file_length = 0; for file in info['files']:
def hashSha1(password, salt='', n=12): salt = salt or sha(urandom(32)).hexdigest() hashed = sha(salt + password).hexdigest() for i in xrange(n): hashed = sha(hashed + salt).hexdigest() return '$sha1$%i$%s$%s' % (n, salt, hashed)
} maxlength = max([len(v[:v.find(':')]) for v in labels.values()]) # run through l10n-ed labels and make them all the same length for k, v in labels.items(): if ':' in v: index = v.index(':') newlabel = v.replace(':', '.' * (maxlength - index) + ':') labels[k] = newlabel for metainfo_name in argv[1:]: metainfo_file = open(metainfo_name, 'rb') metainfo = bdecode(metainfo_file.read()) metainfo_file.close() info = metainfo['info'] info_hash = sha(bencode(info)) if metainfo.has_key('title'): print labels['title'] % metainfo['title'] print labels['metafile'] % basename(metainfo_name) print labels['infohash'] % info_hash.hexdigest() piece_length = info['piece length'] if info.has_key('length'): # let's assume we just have a file print labels['filename'] % info['name'] file_length = info['length'] name = labels['filesize'] if info.has_key('content_type'): print labels['content_type'] % info['content_type'] else: # let's assume we have a directory structure
def randomPassword(): """ Generate a random secure password. """ return sha(urandom(40)).hexdigest()
def verify_body(self): """Compare the body hash to the one from actual body.""" try: return self['oauth_body_hash'] == base64.b64encode(sha(self.body).digest()) except KeyError: raise Error('oauth_body_hash expected, none found in request')