def H(m):
return hashlib.sha512(m).digest()
python类sha512()的实例源码
def seed(self, a=None, version=2):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
"""
if version == 1 and isinstance(a, (str, bytes)):
x = ord(a[0]) << 7 if a else 0
for c in a:
x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF
x ^= len(a)
a = -2 if x == -1 else x
if version == 2 and isinstance(a, (str, bytes, bytearray)):
if isinstance(a, str):
a = a.encode()
a += _sha512(a).digest()
a = int.from_bytes(a, 'big')
super().seed(a)
self.gauss_next = None
def selfModify(*args, **kwargs):
'''
Usage: selfModify(cur_user = token_from_auth, newValue = form)
Modify informantion for oneself
'''
form = kwargs['newValue']
name = form.get('name', None)
value = form.get('value', None)
if (name == None or value == None):
result = {'success': 'false'}
return result
user = User.query.filter_by(username = kwargs['cur_user'].username).first()
if (name == 'nickname'):
user.nickname = value
elif (name == 'description'):
user.description = value
elif (name == 'department'):
user.department = value
elif (name == 'e_mail'):
user.e_mail = value
elif (name == 'tel'):
user.tel = value
elif (name == 'password'):
old_password = hashlib.sha512(form.get('old_value', '').encode('utf-8')).hexdigest()
if (user.password != old_password):
result = {'success': 'false'}
return result
user.password = hashlib.sha512(value.encode('utf-8')).hexdigest()
else:
result = {'success': 'false'}
return result
db.session.commit()
result = {'success': 'true'}
return result
def chpassword(*args, **kwargs):
'''
Usage: chpassword(cur_user = token_from_auth, password = 'your_password')
'''
cur_user = kwargs['cur_user']
cur_user.password = hashlib.sha512(kwargs['password'].encode('utf-8')).hexdigest()
def register(self, *args, **kwargs):
'''
Usage: register(user = modified_from_newuser())
'''
if (kwargs['user'].username == None or kwargs['user'].username == ''):
return {"success":'false', "reason": "Empty username"}
user_check = User.query.filter_by(username = kwargs['user'].username).first()
if (user_check != None and user_check.status != "init"):
#for the activating form
return {"success":'false', "reason": "Unauthorized action"}
newuser = kwargs['user']
if (user_check != None and (user_check.status == "init")):
db.session.delete(user_check)
db.session.commit()
else:
newuser.password = hashlib.sha512(newuser.password.encode('utf-8')).hexdigest()
db.session.add(newuser)
db.session.commit()
# if newuser status is normal, init some data for this user
# now initialize for all kind of users
#if newuser.status == 'normal':
path = env.getenv('DOCKLET_LIB')
subprocess.call([path+"/userinit.sh", newuser.username])
res = self.groupQuery(name=newuser.user_group)
if res['success']:
self.set_nfs_quota(newuser.username,res['data']['data'])
return {"success":'true'}
def H(m):
return hashlib.sha512(m).digest()
def api_query(self, command, req={}):
if (command == "returnTicker" or command == "return24Volume"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif (command == "returnOrderBook"):
ret = urllib2.urlopen(urllib2.Request(
'https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif (command == "returnMarketTradeHistory"):
ret = urllib2.urlopen(urllib2.Request(
'https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(
req['currencyPair'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time() * 1000)
post_data = urllib.urlencode(req)
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def H(x):
# random oracle
h = int(hashlib.sha512(str(x)).hexdigest(), 16)
out = vector([0]*k, Zmod(q))
for i in range(0, k) :
out[i] = h%b
h /= b
i += 1
return out
def hash_to_baseb(matrix, message, b, k):
'''
i/p:
matrix : numpy array to be hashed
message : string that the sender sends
o/p:
list with k elements each b/w 0 to b-1
'''
hexval = hl.sha512(np.array_str(matrix) + message).hexdigest() # returns a string with 128 hex digits
return np.array(map(int, list(b2b(hexval, 16, b)[:k]))) # returns first k digits from hexval in a list
# this list of symbols allows conversion of numbers represented until base 36
def create (seed, hash=hashlib.sha512):
"""Create a new TOTP for the given secret seed and hash,
using the default 30 second time step period."""
return totp(stringToHex(seed), format='dec8', hash=hash)
def api_query(self, method, options=None):
"""
Queries Bittrex with given method and options
:param method: Query method for getting info
:type method: str
:param options: Extra options for query
:type options: dict
:return: JSON response from Bittrex
:rtype : dict
"""
if not options:
options = {}
nonce = str(int(time.time() * 1000))
method_set = 'public'
if method in MARKET_SET:
method_set = 'market'
elif method in ACCOUNT_SET:
method_set = 'account'
request_url = (BASE_URL % method_set) + method + '?'
if method_set != 'public':
request_url += 'apikey=' + self.api_key + "&nonce=" + nonce + '&'
request_url += urlencode(options)
return requests.get(
request_url,
headers={"apisign": hmac.new(self.api_secret.encode(), request_url.encode(), hashlib.sha512).hexdigest()}
).json()
def api_query(self, command, req={}):
if(command == "returnTicker" or command == "return24Volume"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif(command == "returnOrderBook"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif(command == "returnMarketTradeHistory"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif (command == "returnChartData"):
ret = urllib2.urlopen(urllib2.Request(
'https://poloniex.com/public?command=' + "returnChartData" + '¤cyPair=' + str(
req['currencyPair']) + '&start=' + str(
req['start']) + '&end=' + str(
req['end']) + '&period=' + str(req['period'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(req)
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def make_secure_token(*args, **options):
'''
This will create a secure token that you can use as an authentication
token for your users. It uses heavy-duty HMAC encryption to prevent people
from guessing the information. (To make it even more effective, if you
will never need to regenerate the token, you can pass some random data
as one of the arguments.)
:param \*args: The data to include in the token.
:type args: args
:param \*\*options: To manually specify a secret key, pass ``key=THE_KEY``.
Otherwise, the ``current_app`` secret key will be used.
:type \*\*options: kwargs
'''
key = options.get('key')
key = _secret_key(key)
l = [s if isinstance(s, bytes) else s.encode('utf-8') for s in args]
payload = b'\0'.join(l)
token_value = hmac.new(key, payload, sha512).hexdigest()
if hasattr(token_value, 'decode'): # pragma: no cover
token_value = token_value.decode('utf-8') # ensure bytes
return token_value
def _cookie_digest(payload, key=None):
key = _secret_key(key)
return hmac.new(key, payload.encode('utf-8'), sha512).hexdigest()
def _create_identifier():
user_agent = request.headers.get('User-Agent')
if user_agent is not None:
user_agent = user_agent.encode('utf-8')
base = '{0}|{1}'.format(_get_remote_addr(), user_agent)
if str is bytes:
base = unicode(base, 'utf-8', errors='replace') # pragma: no cover
h = sha512()
h.update(base.encode('utf8'))
return h.hexdigest()
def save(obj):
"""return inner state of sha512 `obj` as raw string"""
#assert isinstance(obj, sha512)
datap = ctypes.cast(ctypes.cast(id(obj),
ctypes.POINTER(ctypes.c_voidp))[POFFSET],
ctypes.POINTER(ctypes.c_char))
assert datap
return datap[:STATESIZE]
def restore(data):
"""create new sha512 object with inner state from `data`, str/bytes or iterable"""
new = sha512()
datap = ctypes.cast(ctypes.cast(id(new),
ctypes.POINTER(ctypes.c_voidp))[POFFSET],
ctypes.POINTER(ctypes.c_char))
assert datap
assert datap[:8] == '\x08\xc9\xbc\xf3g\xe6\tj' # first sha512 word
for i, byte in enumerate(data):
assert i < STATESIZE
datap[i] = byte
assert i + 1 == STATESIZE
return new
def encode_sha512(self, *, message : str):
'''Generate SHA-512 hash'''
await self.bot.embed_reply(hashlib.sha512(message.encode("utf-8")).hexdigest())
def H(m):
return hashlib.sha512(m).digest()
def H(m):
return hashlib.sha512(m).digest()