def run(self):
try:
if self.data_type == 'hash':
query_url = 'scan/'
query_data = self.getParam('data', None, 'Hash is missing')
elif self.data_type == 'file':
query_url = 'scan/'
hashes = self.getParam('attachment.hashes', None)
if hashes is None:
filepath = self.getParam('file', None, 'File is missing')
query_data = hashlib.sha256(open(filepath, 'r').read()).hexdigest()
else:
# find SHA256 hash
query_data = next(h for h in hashes if len(h) == 64)
elif self.data_type == 'filename':
query_url = 'search?query=filename:'
query_data = self.getParam('data', None, 'Filename is missing')
else:
self.notSupported()
url = str(self.basic_url) + str(query_url) + str(query_data)
error = True
while error:
r = requests.get(url, headers=self.headers, auth=HTTPBasicAuth(self.api_key, self.secret), verify=False)
if "error" in r.json().get('response') == "Exceeded maximum API requests per minute(5). Please try again later.":
time.sleep(60)
else:
error = False
self.report({'results': r.json()})
except ValueError as e:
self.unexpectedError(e)
python类sha256()的实例源码
def solve(x):
base58char = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
for i in range(len(x)):
for char in base58char:
cry = x[:i]+char+x[i+1:]
print cry
clear = base58.b58decode(str(cry))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
if chk == rechk[:4]: return cry
for i in range(len(x)):
for j in range(len(x)):
if i == j: continue
for charI in base58char:
for charJ in base58char:
cry = x[:i]+charI+x[i+1:]
cry = cry[:j]+charJ+cry[j+1:]
print cry
clear = base58.b58decode(str(cry))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
if chk == rechk[:4]: return cry
'''
clear = base58.b58decode(str(cry))
#li = list()
#for i in clear:
# li.append(ord(i))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
checksum = rechk[:4]
final = ori+checksum
return base58.b58encode(final)
'''
#print solve(cry)
#print solve('15GJF8Do1NDSMy4eV8H82dfFtTvKaqYyhg')
def hash_password(password, salt):
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
# Check a hashed password
def check_hash(password, hashed_pw):
hashed_pw, salt = hashed_pw.split(':')
return hashed_pw == hashlib.sha256(salt.encode() + password.encode()).hexdigest()
# Prompts the user for text input
def sha256(self):
"""
Simply return the sha256 hash value associated with the content file.
If the file can't be accessed, then None is returned.
"""
sha256 = hashlib.sha256()
if self.open(mode=NNTPFileMode.BINARY_RO):
for chunk in \
iter(lambda: self.stream.read(128*sha256.block_size), b''):
sha256.update(chunk)
return sha256.hexdigest()
return None
def write_record(self, bdist_dir, distinfo_dir):
from wheel.util import urlsafe_b64encode
record_path = os.path.join(distinfo_dir, 'RECORD')
record_relpath = os.path.relpath(record_path, bdist_dir)
def walk():
for dir, dirs, files in os.walk(bdist_dir):
dirs.sort()
for f in sorted(files):
yield os.path.join(dir, f)
def skip(path):
"""Wheel hashes every possible file."""
return (path == record_relpath)
with open_for_csv(record_path, 'w+') as record_file:
writer = csv.writer(record_file)
for path in walk():
relpath = os.path.relpath(path, bdist_dir)
if skip(relpath):
hash = ''
size = ''
else:
with open(path, 'rb') as f:
data = f.read()
digest = hashlib.sha256(data).digest()
hash = 'sha256=' + native(urlsafe_b64encode(digest))
size = len(data)
record_path = os.path.relpath(
path, bdist_dir).replace(os.path.sep, '/')
writer.writerow((record_path, hash, size))
def test_verifying_zipfile():
if not hasattr(zipfile.ZipExtFile, '_update_crc'):
pytest.skip('No ZIP verification. Missing ZipExtFile._update_crc.')
sio = StringIO()
zf = zipfile.ZipFile(sio, 'w')
zf.writestr("one", b"first file")
zf.writestr("two", b"second file")
zf.writestr("three", b"third file")
zf.close()
# In default mode, VerifyingZipFile checks the hash of any read file
# mentioned with set_expected_hash(). Files not mentioned with
# set_expected_hash() are not checked.
vzf = wheel.install.VerifyingZipFile(sio, 'r')
vzf.set_expected_hash("one", hashlib.sha256(b"first file").digest())
vzf.set_expected_hash("three", "blurble")
vzf.open("one").read()
vzf.open("two").read()
try:
vzf.open("three").read()
except wheel.install.BadWheelFile:
pass
else:
raise Exception("expected exception 'BadWheelFile()'")
# In strict mode, VerifyingZipFile requires every read file to be
# mentioned with set_expected_hash().
vzf.strict = True
try:
vzf.open("two").read()
except wheel.install.BadWheelFile:
pass
else:
raise Exception("expected exception 'BadWheelFile()'")
vzf.set_expected_hash("two", None)
vzf.open("two").read()
def sign(wheelfile, replace=False, get_keyring=get_keyring):
"""Sign a wheel"""
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wf = WheelFile(wheelfile, append=True)
wk = WheelKeys().load()
name = wf.parsed_filename.group('name')
sign_with = wk.signers(name)[0]
sys.stdout.write("Signing {0} with {1}\n".format(name, sign_with[1]))
vk = sign_with[1]
kr = keyring.get_keyring()
sk = kr.get_password('wheel', vk)
keypair = ed25519ll.Keypair(urlsafe_b64decode(binary(vk)),
urlsafe_b64decode(binary(sk)))
record_name = wf.distinfo_name + '/RECORD'
sig_name = wf.distinfo_name + '/RECORD.jws'
if sig_name in wf.zipfile.namelist():
raise WheelError("Wheel is already signed.")
record_data = wf.zipfile.read(record_name)
payload = {"hash":"sha256=" + native(urlsafe_b64encode(hashlib.sha256(record_data).digest()))}
sig = signatures.sign(payload, keypair)
wf.zipfile.writestr(sig_name, json.dumps(sig, sort_keys=True))
wf.zipfile.close()
def hmacsha256(data, key):
return hmac.new(key, data, digestmod=hashlib.sha256).digest()
def write_record(self, bdist_dir, distinfo_dir):
from .util import urlsafe_b64encode
record_path = os.path.join(distinfo_dir, 'RECORD')
record_relpath = os.path.relpath(record_path, bdist_dir)
def walk():
for dir, dirs, files in os.walk(bdist_dir):
dirs.sort()
for f in sorted(files):
yield os.path.join(dir, f)
def skip(path):
"""Wheel hashes every possible file."""
return (path == record_relpath)
with open_for_csv(record_path, 'w+') as record_file:
writer = csv.writer(record_file)
for path in walk():
relpath = os.path.relpath(path, bdist_dir)
if skip(relpath):
hash = ''
size = ''
else:
with open(path, 'rb') as f:
data = f.read()
digest = hashlib.sha256(data).digest()
hash = 'sha256=' + native(urlsafe_b64encode(digest))
size = len(data)
record_path = os.path.relpath(
path, bdist_dir).replace(os.path.sep, '/')
writer.writerow((record_path, hash, size))
def sign(wheelfile, replace=False, get_keyring=get_keyring):
"""Sign a wheel"""
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wf = WheelFile(wheelfile, append=True)
wk = WheelKeys().load()
name = wf.parsed_filename.group('name')
sign_with = wk.signers(name)[0]
sys.stdout.write("Signing {0} with {1}\n".format(name, sign_with[1]))
vk = sign_with[1]
kr = keyring.get_keyring()
sk = kr.get_password('wheel', vk)
keypair = ed25519ll.Keypair(urlsafe_b64decode(binary(vk)),
urlsafe_b64decode(binary(sk)))
record_name = wf.distinfo_name + '/RECORD'
sig_name = wf.distinfo_name + '/RECORD.jws'
if sig_name in wf.zipfile.namelist():
raise WheelError("Wheel is already signed.")
record_data = wf.zipfile.read(record_name)
payload = {"hash": "sha256=" + native(urlsafe_b64encode(hashlib.sha256(record_data).digest()))}
sig = signatures.sign(payload, keypair)
wf.zipfile.writestr(sig_name, json.dumps(sig, sort_keys=True))
wf.zipfile.close()
def get_rings_checksum():
"""Returns sha256 checksum for rings in /etc/swift."""
sha = hashlib.sha256()
for ring in SWIFT_RINGS.keys():
path = os.path.join(SWIFT_CONF_DIR, '{}.{}'
.format(ring, SWIFT_RING_EXT))
if not os.path.isfile(path):
continue
with open(path, 'rb') as fd:
sha.update(fd.read())
return sha.hexdigest()
def get_builders_checksum():
"""Returns sha256 checksum for builders in /etc/swift."""
sha = hashlib.sha256()
for builder in SWIFT_RINGS.values():
if not os.path.exists(builder):
continue
with open(builder, 'rb') as fd:
sha.update(fd.read())
return sha.hexdigest()
def _generate_id(self):
new_id = hashlib.sha256(self._secret + str(uuid.uuid4()) + str(time.time()))
return new_id.hexdigest()
def _generate_hmac(self, session_id):
return hmac.new(session_id, self._secret, hashlib.sha256).hexdigest()
def get_password_hash(pw, current_salt):
"""Gets the password hash for the two-step verification.
current_salt should be the byte array provided by invoking GetPasswordRequest()"""
# Passwords are encoded as UTF-8
# At https://github.com/DrKLO/Telegram/blob/e31388
# src/main/java/org/telegram/ui/LoginActivity.java#L2003
data = pw.encode('utf-8')
pw_hash = current_salt + data + current_salt
return sha256(pw_hash).digest()
# endregion
def get_file_hash(file_name):
"""Get a sha256 hash of a file."""
with open(file_name, 'rb') as f:
sha = hashlib.sha256(f.read())
return sha.hexdigest()
def change_password(login, password):
salt = uuid4().hex
hashed = sha256(password.encode() + salt.encode()).hexdigest()
g.db = connect_db()
cur = g.db.execute('UPDATE users SET password=?, salt=? WHERE login=?', (hashed, salt, login))
g.db.commit()
g.db.close()
##
# Change admin status
# status: 1 = admin, 0 = user
def create_user(login, password, isAdmin=0):
salt = uuid4().hex
hashed = sha256(password.encode() + salt.encode()).hexdigest()
g.db = connect_db()
cur = g.db.execute('INSERT INTO users(login, password, salt, isAdmin) VALUES (?,?,?,?)', (login, hashed, salt, isAdmin))
g.db.commit()
g.db.close()
##
# Is the user an admin?
def l1l11(self, l11l11, l1l1l):
l1ll1 = self.l1l111.encode(self.l1111(u'??????'))
l1l1ll = str(l11l11) + self.l1111(u'??') + str(l1l1l)
l1l1ll = l1l1ll.encode(self.l1111(u'??????'))
l1lllll = l11ll1.new(l1ll1, l1l1ll, digestmod=l1ll.sha256)
return l1lllll.hexdigest()