本文整理汇总了Python中sha3.sha3_256函数的典型用法代码示例。如果您正苦于以下问题:Python sha3_256函数的具体用法?Python sha3_256怎么用?Python sha3_256使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sha3_256函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: setup_cipher
def setup_cipher(self):
# https://github.com/ethereum/cpp-ethereum/blob/develop/libp2p/RLPxFrameIO.cpp#L34
assert self.responder_nonce
assert self.initiator_nonce
assert self.auth_init
assert self.auth_ack
assert self.remote_ephemeral_pubkey
if not self.ecc.is_valid_key(self.remote_ephemeral_pubkey):
raise InvalidKeyError('invalid remote ephemeral pubkey')
# derive base secrets from ephemeral key agreement
# ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)
ecdhe_shared_secret = self.ephemeral_ecc.get_ecdh_key(self.remote_ephemeral_pubkey)
# shared-secret = sha3(ecdhe-shared-secret || sha3(nonce || initiator-nonce))
shared_secret = sha3(
ecdhe_shared_secret + sha3(self.responder_nonce + self.initiator_nonce))
self.ecdhe_shared_secret = ecdhe_shared_secret # FIXME DEBUG
self.shared_secret = shared_secret # FIXME DEBUG
# token = sha3(shared-secret)
self.token = sha3(shared_secret)
self.token_by_pubkey[self.remote_pubkey] = self.token
# aes-secret = sha3(ecdhe-shared-secret || shared-secret)
self.aes_secret = sha3(ecdhe_shared_secret + shared_secret)
# mac-secret = sha3(ecdhe-shared-secret || aes-secret)
self.mac_secret = sha3(ecdhe_shared_secret + self.aes_secret)
# setup sha3 instances for the MACs
# egress-mac = sha3.update(mac-secret ^ recipient-nonce || auth-sent-init)
mac1 = sha3_256(sxor(self.mac_secret, self.responder_nonce) + self.auth_init)
# ingress-mac = sha3.update(mac-secret ^ initiator-nonce || auth-recvd-ack)
mac2 = sha3_256(sxor(self.mac_secret, self.initiator_nonce) + self.auth_ack)
if self.is_initiator:
self.egress_mac, self.ingress_mac = mac1, mac2
else:
self.egress_mac, self.ingress_mac = mac2, mac1
ciphername = 'aes-256-ctr'
iv = "\x00" * 16
assert len(iv) == 16
self.aes_enc = pyelliptic.Cipher(self.aes_secret, iv, 1, ciphername=ciphername)
self.aes_dec = pyelliptic.Cipher(self.aes_secret, iv, 0, ciphername=ciphername)
self.mac_enc = AES.AESCipher(self.mac_secret, AES.MODE_ECB).encrypt
self.is_ready = True
开发者ID:gvsurenderreddy,项目名称:pydevp2p,代码行数:50,代码来源:rlpxcipher.py
示例2: test_submitting_initial_answer
def test_submitting_initial_answer(deploy_client, deploy_broker_contract,
deployed_contracts, get_log_data,
deploy_coinbase, contracts, denoms,
StatusEnum):
factory = deployed_contracts.BuildByteArrayFactory
broker = deploy_broker_contract(factory._meta.address)
expected = "\x01\x02\x03\x04\x05\x06\x07"
request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)
request_event_data = get_log_data(broker.Created, request_txn_hash)
_id = request_event_data['id']
assert broker.getRequest(_id)[5] == StatusEnum.Pending
deposit_amount = broker.getRequiredDeposit("abcdefg")
assert deposit_amount > 0
answer_txn_hash = broker.answerRequest(_id, expected, value=deposit_amount)
answer_txn_receipt = deploy_client.wait_for_transaction(answer_txn_hash)
assert broker.getRequest(_id)[5] == StatusEnum.WaitingForResolution
answer_data = broker.getInitialAnswer(_id)
assert answer_data[0] == sha3.sha3_256(expected).digest()
assert answer_data[1] == deploy_coinbase
assert answer_data[2] == int(answer_txn_receipt['blockNumber'], 16)
assert answer_data[3] is False
开发者ID:gitter-badger,项目名称:ethereum-computation-market,代码行数:33,代码来源:test_submitting_answer.py
示例3: get_prefixes
def get_prefixes(fullname, funcs):
names_to_sigs = {}
for func in funcs:
sig_start = func['name'].find('(')
names_to_sigs[func['name'][:sig_start]] = func['name'][sig_start:]
check_next_line = False
prefixes = []
for line in open(fullname):
if line.startswith('def set'):
name_start = line.find(' ') + 1
name_end = line.find('(')
name = line[name_start:name_end]
sig = names_to_sigs[name]
elif line.startswith('#whitelisted'):
check_next_line = True
continue
elif check_next_line and line.startswith('def'):
name_start = line.find(' ') + 1
name_end = line.find('(')
name = line[name_start:name_end]
sig = names_to_sigs[name]
else:
continue
prefix = sha3.sha3_256((name + sig).encode('ascii')).hexdigest()[:8]
prefixes.append('0x' + prefix)
prefixes.sort()
prefix_init_code = []
prefix_init_code.append('prefixes = array({})'.format(len(prefixes)))
for i, prefix in enumerate(prefixes):
item = 'prefixes[{i}] = {prefix}'.format(i=i, prefix=prefix)
prefix_init_code.append(item)
return '\n'.join(prefix_init_code)
开发者ID:rtmilbourne,项目名称:augur-core,代码行数:34,代码来源:load_contracts.py
示例4: _sign_simple_signature_fulfillment
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
"""Signs a Ed25519Fulfillment.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with.
"""
# NOTE: To eliminate the dangers of accidentally signing a condition by
# reference, we remove the reference of input_ here
# intentionally. If the user of this class knows how to use it,
# this should never happen, but then again, never say never.
input_ = deepcopy(input_)
public_key = input_.owners_before[0]
message = sha3_256(message.encode())
if input_.fulfills:
message.update('{}{}'.format(
input_.fulfills.txid, input_.fulfills.output).encode())
try:
# cryptoconditions makes no assumptions of the encoding of the
# message to sign or verify. It only accepts bytestrings
input_.fulfillment.sign(
message.digest(), base58.b58decode(key_pairs[public_key].encode()))
except KeyError:
raise KeypairMismatchException('Public key {} is not a pair to '
'any of the private keys'
.format(public_key))
return input_
开发者ID:cgwyx,项目名称:bigchaindb,代码行数:30,代码来源:transaction.py
示例5: get_prefixes
def get_prefixes(fullname, funcs):
names_to_sigs = {}
for func in funcs:
sig_start = func["name"].find("(")
names_to_sigs[func["name"][:sig_start]] = func["name"][sig_start:]
check_next_line = False
prefixes = []
for line in open(fullname):
if line.startswith("def set"):
name_start = line.find(" ") + 1
name_end = line.find("(")
name = line[name_start:name_end]
sig = names_to_sigs[name]
elif line.startswith("#whitelisted"):
check_next_line = True
continue
elif check_next_line and line.startswith("def"):
name_start = line.find(" ") + 1
name_end = line.find("(")
name = line[name_start:name_end]
sig = names_to_sigs[name]
else:
continue
prefix = sha3.sha3_256((name + sig).encode("ascii")).hexdigest()[:8]
prefixes.append("0x" + prefix)
prefixes.sort()
prefix_init_code = []
prefix_init_code.append("prefixes = array({})".format(len(prefixes)))
for i, prefix in enumerate(prefixes):
item = "prefixes[{i}] = {prefix}".format(i=i, prefix=prefix)
prefix_init_code.append(item)
return "\n".join(prefix_init_code)
开发者ID:prashantpawar,项目名称:augur-core,代码行数:34,代码来源:load_contracts.py
示例6: hash_string
def hash_string():
string = input("Please Enter Your String: \n")
# SHA-1 Hash
hash_objectsha1 = hashlib.sha1(string.encode())
String_SHA1 = hash_objectsha1.hexdigest()
# SHA-256 Hash
hash_objectsha2 = hashlib.sha256(string.encode())
String_SHA256 = hash_objectsha2.hexdigest()
# SHA-512 Hash
hash_objectsha5 = hashlib.sha512(string.encode())
String_SHA512 = hash_objectsha5.hexdigest()
# SHA-3 256 Hash
hash_objectsha3256 = sha3.sha3_256(string.encode())
String_SHA3256 = hash_objectsha3256.hexdigest()
# SHA-3 512 Hash
hash_objectsha3512 = sha3.sha3_512(string.encode())
String_SHA3512 = hash_objectsha3512.hexdigest()
print("Your SHA-1 Hash is ", String_SHA1)
print("\n")
print("Your SHA-256 Hash is ", String_SHA256)
print("\n")
print("Your SHA-512 Hash is ", String_SHA512)
print("\n")
print("Your SHA-3 256 Hash is ", String_SHA3256)
print("\n")
print("Your SHA-3 512 Hash is ", String_SHA3512)
print("\n")
return
开发者ID:YazooSecurity,项目名称:PythonHashGenerator,代码行数:35,代码来源:HashGenerator.py
示例7: web3_sha3
def web3_sha3(value, encoding='hex'):
logger.info('web3_sha3')
if encoding == 'hex':
value = decode_hex(value)
else:
value = force_bytes(value)
return encode_32bytes(sha3_256(value).digest())
开发者ID:4gn3s,项目名称:eth-testrpc,代码行数:7,代码来源:testrpc.py
示例8: test_challenging_answer
def test_challenging_answer(deploy_client, deploy_broker_contract,
deployed_contracts, get_log_data,
deploy_coinbase, contracts, StatusEnum, denoms):
factory = deployed_contracts.BuildByteArrayFactory
broker = deploy_broker_contract(factory._meta.address)
expected = "\x01\x02\x03\x04\x05\x06\x07"
request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)
request_event_data = get_log_data(broker.Created, request_txn_hash)
_id = request_event_data['id']
assert broker.getRequest(_id)[5] == StatusEnum.Pending
deposit_amount = broker.getRequiredDeposit("abcdefg")
assert deposit_amount > 0
i_answer_txn_hash = broker.answerRequest(_id, "wrong", value=deposit_amount)
i_answer_txn_receipt = deploy_client.wait_for_transaction(i_answer_txn_hash)
assert broker.getRequest(_id)[5] == StatusEnum.WaitingForResolution
i_answer_data = set(broker.getInitialAnswer(_id))
assert deploy_coinbase in i_answer_data
assert sha3.sha3_256("wrong").digest() in i_answer_data
assert int(i_answer_txn_receipt['blockNumber'], 16) in i_answer_data
assert broker.getInitialAnswerResult(_id) == "wrong"
with pytest.raises(TransactionFailed):
broker.challengeAnswer(_id, expected, value=deposit_amount - 1)
开发者ID:pipermerriam,项目名称:ethereum-computation-market,代码行数:35,代码来源:test_challenging_answer_requires_deposit.py
示例9: calc_max
def calc_max(self):
if self.max is None:
r = []
r.append(struct.pack("<i", self.nVersion))
r.append(ser_uint256(self.hashPrevBlock))
r.append(ser_uint256(self.hashMerkleRoot))
r.append(struct.pack("<I", self.nTime))
r.append(struct.pack("<I", self.nBits))
r.append(struct.pack("<I", self.nNonce))
self.max = uint256_from_str(sha3_256(''.join(r)).digest())
return self.max
开发者ID:AKIo0O,项目名称:stratum-mining-keccak,代码行数:11,代码来源:halfnode.py
示例10: findLowestHash
def findLowestHash(blockHash):
start = random.randrange(0,999999999999999999999999999999999999999999999999999999999999999999999999999999999) #big random range making it so multi-threading is easy.
lowest = (-1,999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999L) #just a big number
try:
while True:
hashInt = int(sha3.sha3_256(blockHash + str(start)).hexdigest(), 16)
if hashInt < lowest[1]:
lowest = (start, hashInt)
except:
print "anceled Search. Search results are: "
return (str(lowest[0]), str(lowest[1]))
开发者ID:ddworken,项目名称:sha3Game,代码行数:11,代码来源:bruteforcer.py
示例11: update_contract_events_api
def update_contract_events_api(contract_name, fullsig):
api = {}
for evt in fullsig:
if evt["type"] == "event":
split_name = evt["name"].split("(")
api[split_name[0]] = {
"inputs": evt["inputs"],
"name": evt["name"],
"signature": "0x" + sha3.sha3_256(evt["name"].encode("ascii")).hexdigest(),
"contract": contract_name
}
return api
开发者ID:wintermooch,项目名称:augur-core,代码行数:12,代码来源:make_api.py
示例12: sha3
def sha3(value, encoding=None):
from .formatting import (
remove_0x_prefix,
)
from .string import (
force_bytes,
)
if encoding:
value = codecs.decode(remove_0x_prefix(value), encoding)
return sha3_256(force_bytes(value)).hexdigest()
开发者ID:XertroV,项目名称:web3.py,代码行数:12,代码来源:crypto.py
示例13: SHA3_256_hash_file
def SHA3_256_hash_file(filename):
# make a hash object
h = sha3.sha3_256()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest
return h.hexdigest()
开发者ID:davidkennefick,项目名称:pythonhashgen,代码行数:13,代码来源:hashgen1.1.py
示例14: get_cache
def get_cache(block_number):
while len(cache_seeds) <= block_number // EPOCH_LENGTH:
cache_seeds.append(sha3.sha3_256(cache_seeds[-1]).digest())
seed = cache_seeds[block_number // EPOCH_LENGTH]
if seed in cache_by_seed:
c = cache_by_seed.pop(seed) # pop and append at end
cache_by_seed[seed] = c
return c
c = mkcache(block_number)
cache_by_seed[seed] = c
if len(cache_by_seed) > cache_by_seed.max_items:
cache_by_seed.pop(cache_by_seed.keys()[0]) # remove last recently accessed
return c
开发者ID:Feretrius,项目名称:pyethereum,代码行数:13,代码来源:ethpow.py
示例15: calculate_contract_address
def calculate_contract_address(self, tx=None, from_nonce_tuple=None):
if tx:
from_address = tx["from"]
nonce = tx["nonce"]
elif from_nonce_tuple:
from_address = from_nonce_tuple[0]
nonce = from_nonce_tuple[1]
return "0x" + sha3.sha3_256(
rlp.encode([
binascii.unhexlify(from_address[2:]),
nonce
])
).hexdigest()[-40:]
开发者ID:modernblockchains,项目名称:newkidsontheblock,代码行数:14,代码来源:util.py
示例16: process_fullsig
def process_fullsig(fullsig):
'''Transforms a signature to help with type checking
The full signature of a contract looks something like:
[{"type":"function",
"name":"foo(int256)",
... ,
}]
The Contract class uses the type information in the signature,
so that my_contract.foo(1) will work, but my_contract.foo('bar')
will not. After the transformation, the signature looks like this:
{"foo":[("4c970b2f", # prefix
((int, long),), # types
"foo(int256)")]} # full name
A contract might have multiple functions with the same name, but
different input types, so the result dictionary maps a name to a list
of info for each function with that name.
'''
names_to_info = {}
for item in filter(lambda i: i['type']=='function', fullsig):
sig_start = item['name'].find('(')
if sig_start == -1:
raise ValueError('Bad function name in fullsig: {}'.format(item['name']))
name = item['name'][:sig_start]
if name not in names_to_info:
names_to_info[name] = []
prefix = sha3.sha3_256(item['name'].encode('ascii')).hexdigest()[:8]
if item['name'][sig_start + 1] == ')': #empty sig
names_to_info[name].append((prefix, (), item['name']))
else:
sig = item['name'][sig_start + 1:-1].split(',')
pysig = []
for t in sig:
if '[]' in t:
pysig.append(list)
elif t.startswith('bytes') or t.startswith('string') or t=='address':
pysig.append(str)
elif 'int' in t:
pysig.append(INT)
else:
raise TypeError('unsupported type in fullsig: {}'.format(t))
names_to_info[name].append((prefix, tuple(pysig), item['name']))
return names_to_info
开发者ID:ChrisCalderon,项目名称:augur-core,代码行数:48,代码来源:test_contract.py
示例17: _sign_threshold_signature_fulfillment
def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):
"""Signs a ThresholdSha256.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The Input to be signed.
message (str): The message to be signed
key_pairs (dict): The keys to sign the Transaction with.
"""
input_ = deepcopy(input_)
message = sha3_256(message.encode())
if input_.fulfills:
message.update('{}{}'.format(
input_.fulfills.txid, input_.fulfills.output).encode())
for owner_before in set(input_.owners_before):
# TODO: CC should throw a KeypairMismatchException, instead of
# our manual mapping here
# TODO FOR CC: Naming wise this is not so smart,
# `get_subcondition` in fact doesn't return a
# condition but a fulfillment
# TODO FOR CC: `get_subcondition` is singular. One would not
# expect to get a list back.
ccffill = input_.fulfillment
subffills = ccffill.get_subcondition_from_vk(
base58.b58decode(owner_before))
if not subffills:
raise KeypairMismatchException('Public key {} cannot be found '
'in the fulfillment'
.format(owner_before))
try:
private_key = key_pairs[owner_before]
except KeyError:
raise KeypairMismatchException('Public key {} is not a pair '
'to any of the private keys'
.format(owner_before))
# cryptoconditions makes no assumptions of the encoding of the
# message to sign or verify. It only accepts bytestrings
for subffill in subffills:
subffill.sign(
message.digest(), base58.b58decode(private_key.encode()))
return input_
开发者ID:cgwyx,项目名称:bigchaindb,代码行数:45,代码来源:transaction.py
示例18: address_to_pubkeyhash
def address_to_pubkeyhash(addr):
try:
addr = b58decode(addr, 25)
except:
return None
if addr is None:
return None
ver = addr[0]
cksumA = addr[-4:]
#TODO: We should clean this up so that it works with not Keccek implementations too.
cksumB = sha3.sha3_256(addr[:-4]).digest()[:4]
if cksumA != cksumB:
return None
return (ver, addr[1:-4])
开发者ID:toxicwind,项目名称:stratum-mining-maxcoin,代码行数:18,代码来源:util.py
示例19: _input_valid
def _input_valid(input_, operation, message, output_condition_uri=None):
"""Validates a single Input against a single Output.
Note:
In case of a `CREATE` or `GENESIS` Transaction, this method
does not validate against `output_condition_uri`.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The Input to be signed.
operation (str): The type of Transaction.
message (str): The fulfillment message.
output_condition_uri (str, optional): An Output to check the
Input against.
Returns:
bool: If the Input is valid.
"""
ccffill = input_.fulfillment
try:
parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri())
except (TypeError, ValueError,
ParsingError, ASN1DecodeError, ASN1EncodeError):
return False
if operation in (Transaction.CREATE, Transaction.GENESIS):
# NOTE: In the case of a `CREATE` or `GENESIS` transaction, the
# output is always valid.
output_valid = True
else:
output_valid = output_condition_uri == ccffill.condition_uri
message = sha3_256(message.encode())
if input_.fulfills:
message.update('{}{}'.format(
input_.fulfills.txid, input_.fulfills.output).encode())
# NOTE: We pass a timestamp to `.validate`, as in case of a timeout
# condition we'll have to validate against it
# cryptoconditions makes no assumptions of the encoding of the
# message to sign or verify. It only accepts bytestrings
ffill_valid = parsed_ffill.validate(message=message.digest())
return output_valid and ffill_valid
开发者ID:cgwyx,项目名称:bigchaindb,代码行数:44,代码来源:transaction.py
示例20: test_compile_imports
def test_compile_imports():
make_tree(test_code)
node = start_test_node()
rpc = RPC_Client((test_node.HOST, test_node.PORT), 0)
coinbase = rpc.eth_coinbase()['result']
gas_price = int(rpc.eth_gasPrice()['result'], 16)
balance = 0
while balance/gas_price < int(MAXGAS, 16):
balance = int(rpc.eth_getBalance(coinbase)['result'], 16)
time.sleep(1)
subprocess.check_call(['python',
'load_contracts.py',
'-p', '9696',
'-b', '2',
'-d', 'test_load_contracts.json',
'-s', 'foobar'])
db = json.load(open("test_load_contracts.json"))
func1 = db['foo']['fullsig'][0]['name']
prefix = sha3.sha3_256(func1.encode('ascii')).hexdigest()[:8]
arg = hex(1 << 65)[2:].strip('L').rjust(64, '0')
r1 = rpc.eth_call(sender=coinbase,
to=db['foo']['address'],
data=('0x' + prefix + arg),
gas=hex(3*10**6))['result']
r1 = int(r1, 16)
if r1 > 2**255:
r1 -= 2**256
r2 = bar(1 << 65)
if r1 == r2:
print 'TEST PASSED'
else:
print 'TEST FAILED: <r1 {}> <r2 {}>'.format(r1, r2)
rm_tree(test_code)
node.send_signal(signal.SIGINT)
node.wait()
开发者ID:rtmilbourne,项目名称:augur-core,代码行数:40,代码来源:test_load_contracts.py
注:本文中的sha3.sha3_256函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论