本文整理汇总了Python中nacl.public.Box.decrypt方法的典型用法代码示例。如果您正苦于以下问题:Python Box.decrypt方法的具体用法?Python Box.decrypt怎么用?Python Box.decrypt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nacl.public.Box
的用法示例。
在下文中一共展示了Box.decrypt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _checkInitiate
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def _checkInitiate(self, clientID, data, host_port):
cookieNonce, encryptedCookie, nonce = _initiateStruct.unpack_from(data)
try:
decryptedCookie = self._secretBox.decrypt(encryptedCookie, 'c' * 8 + cookieNonce)
except CryptoError:
return
clientShortPubkey = PublicKey(decryptedCookie[:32])
serverShortKey = PrivateKey(decryptedCookie[32:])
serverShortClientShort = Box(serverShortKey, clientShortPubkey)
try:
decrypted = serverShortClientShort.decrypt(data[176:], 'CurveCP-client-I' + nonce)
except CryptoError:
return
clientPubkeyString, vouchNonce, encryptedVouch, serverDomain = _initiateInnerStruct.unpack_from(decrypted)
clientPubkey = PublicKey(clientPubkeyString)
serverLongClientLong = Box(self.serverKey.key, clientPubkey)
try:
vouchKey = serverLongClientLong.decrypt(encryptedVouch, 'CurveCPV' + vouchNonce)
except CryptoError:
return
if vouchKey != str(clientShortPubkey):
return
transport = CurveCPServerTransport(
self.reactor, self.serverKey, self.factory, clientID,
clientPubkey, host_port, serverShortClientShort, dnsToName(serverDomain))
return transport, decrypted[352:]
示例2: decrypt
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def decrypt(self, data, public_key, base64=True):
box = Box(self._private_key, public_key)
# decrypted = box.decrypt(data)
if base64:
decrypted = box.decrypt(data, encoder=nacl.encoding.Base64Encoder)
else:
decrypted = box.decrypt(data)
return decrypted
示例3: test_box_failed_decryption
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def test_box_failed_decryption(skalice, pkalice, skbob, pkbob, nonce, plaintext, ciphertext):
pkbob = PublicKey(pkbob, encoder=HexEncoder)
skbob = PrivateKey(skbob, encoder=HexEncoder)
# this cannot decrypt the ciphertext!
# the ciphertext must be decrypted by (pkbob, skalice) or (pkalice, skbob)
box = Box(pkbob, skbob)
with pytest.raises(CryptoError):
box.decrypt(ciphertext, binascii.unhexlify(nonce), encoder=HexEncoder)
示例4: __init__
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
class CryptoBox:
# Init
def __init__(self, sk=None, pk=None):
# Set local Variables
self._box = None
self.sk = None
self.pk = None
# Generate key pair if nessessary
if not sk or not pk:
self.sk = PrivateKey.generate()
self.pk = self.sk.public_key
else:
self.sk = sk
self.pk = pk
# Generate shared key / box
self._box = Box(self.sk, self.pk)
# Encryption
def encrypt(self, plaintext, nonce=None):
if not nonce:
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = self._box.encrypt(plaintext, nonce)
return ciphertext[24:]
# Decryption
def decrypt(self, ciphertext, nonce=None):
if nonce:
plaintext = self._box.decrypt(ciphertext, nonce)
else:
plaintext = self._box.decrypt(ciphertext)
return plaintext
示例5: rpc_order
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def rpc_order(self, sender, pubkey, encrypted):
try:
box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey))
order = box.decrypt(encrypted)
c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict),
testnet=self.multiplexer.testnet)
if c.verify(sender.signed_pubkey[64:]):
self.router.addContact(sender)
self.log.info("received an order from %s, waiting for payment..." % sender)
payment_address = c.contract["buyer_order"]["order"]["payment"]["address"]
chaincode = c.contract["buyer_order"]["order"]["payment"]["chaincode"]
masterkey_b = c.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
buyer_key = derive_childkey(masterkey_b, chaincode)
amount = c.contract["buyer_order"]["order"]["payment"]["amount"]
listing_hash = c.contract["buyer_order"]["order"]["ref_hash"]
signature = self.signing_key.sign(
str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64]
c.await_funding(self.get_notification_listener(), self.multiplexer.blockchain, signature, False)
return [signature]
else:
self.log.warning("received invalid order from %s" % sender)
return ["False"]
except Exception:
self.log.error("unable to decrypt order from %s" % sender)
return ["False"]
示例6: authenticate
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def authenticate(self, permissions=[]): #TODO check is needs to = None
keys = PrivateKey.generate()
nonce = nacl.utils.random(Box.NONCE_SIZE)
payload = {
'app': {
'name': self.name,
'version': self.version,
'vendor': self.vendor,
'id': self.id
},
'publicKey': base64.b64encode(keys.public_key.__bytes__()),
'nonce': base64.b64encode(nonce),
'permissions': permissions
}
headers = {
'Content-Type': 'application/json'
}
r = self._post('auth', headers, payload)
if r.status_code == 200:
responseJson = r.json()
cipherText = base64.b64decode(responseJson['encryptedKey'])
self.token = responseJson['token']
self.permissions = responseJson['permissions']
self.publicKey = base64.b64decode(responseJson['publicKey'])
box = Box(keys, PublicKey(self.publicKey))
data = box.decrypt(cipherText, nonce=nonce)
self.symmetricKey = data[0:PrivateKey.SIZE]
self.symmetricNonce = data[PrivateKey.SIZE:]
return True
else:
return False
示例7: decrypt_message
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def decrypt_message(encrypted_message, keying_material, private_key):
encrypted_key = keying_material['encrypted_key']
message_signature = keying_material['message_signature']
temp_public_key = PublicKey(
keying_material['temp_public_key'],
Base64Encoder)
box = PublicBox(private_key, temp_public_key)
message_key = box.decrypt(
encrypted_key,
encoder=Base64Encoder)
# We got the key, so let's get the message.
message_box = nacl.secret.SecretBox(message_key)
message = message_box.decrypt(
encrypted_message,
encoder=Base64Encoder)
# Check the signature.
mac_key = sha256(box._shared_key, RawEncoder)
signing_key = SigningKey(mac_key)
if signing_key.sign(message, Base64Encoder) != message_signature:
raise SignatureError("The signature is not valid")
return message
示例8: unwrap
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def unwrap(self):
# don't process the bundle if it's not meant for us
# check the key fingerprint against our own
# if it doesn't match
# return false
#TODO: Write this code
#if self.destination is not config.get('global', 'nodename'):
#return False;
#else:
# grab my private key
with open( config.get('global', 'keypath') + '/' + self.destination + '.private', 'r' ) as destinationPrivateKey:
destinationKey = self.deserialize(destinationPrivateKey)
# grab the origin's public key
with open( config.get('global', 'keypath') + '/' + self.origin + '.public', 'r' ) as originPublicKey:
originKey = self.deserialize(originPublicKey)
# grab the origin's verification keyhg
with open( config.get('global', 'keypath') + '/' + self.origin + '.sighex', 'r' ) as originSigHex:
originSigKey = self.deserialize(originSigHex)
originVerify = nacl.signing.VerifyKey(originSigKey, encoder=nacl.encoding.HexEncoder)
# create a box to decrypt this sucker
container = Box(destinationKey, originKey)
# verify the signature
rawResult = originVerify.verify(self.payload)
# decrypt it
rawResult = container.decrypt(rawResult)
# verify the signature again
result = originVerify.verify(rawResult)
return result
示例9: decrypt_room_message_key
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def decrypt_room_message_key(message_key_array, captain_transport_pubkey, my_room_privkey):
"""
Parse the message key array, do the trial decryption, and try to retrieve
the room message key. Return it if found, otherwise raise NoKeyFound.
"""
# The array length needs to be a multiple of 72 bytes.
if len(message_key_array) % 72 != 0:
util.debug("Received message key array of length %d" % len(message_key_array))
raise NoKeyFound
# Build our decryption box.
decryption_box = Box(my_room_privkey, captain_transport_pubkey)
chunks = array_chunk_generator(message_key_array, 72)
# Start walking over the message key array and trial decrypt every
# ciphertext till we get our key. If we finish array and still haven't
# found anything, bail with NoKeyFound exception.
while True:
try:
chunk = chunks.next()
except StopIteration: # no more chunks
util.debug("Walked over the whole KEY_TRANSPORT packet!")
raise NoKeyFound
try:
room_message_key = decryption_box.decrypt(chunk)
break
except nacl.exceptions.CryptoError:
util.debug("Walking KEY_TRANSPORT: Not our key!")
# if we didn't find key in first chunk, move to next one.
continue
return room_message_key
示例10: rpc_message
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def rpc_message(self, sender, pubkey, encrypted):
try:
box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey))
plaintext = box.decrypt(encrypted)
p = PlaintextMessage()
p.ParseFromString(plaintext)
signature = p.signature
p.ClearField("signature")
verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
verify_key.verify(p.SerializeToString(), signature)
h = nacl.hash.sha512(p.signed_pubkey)
pow_hash = h[64:128]
if int(pow_hash[:6], 16) >= 50 or p.sender_guid.encode("hex") != h[:40] or p.sender_guid != sender.id:
raise Exception('Invalid guid')
self.log.info("received a message from %s" % sender)
self.router.addContact(sender)
for listener in self.listeners:
try:
verifyObject(MessageListener, listener)
listener.notify(p, signature)
except DoesNotImplement:
pass
return ["True"]
except Exception:
self.log.warning("received invalid message from %s" % sender)
return ["False"]
示例11: rpc_order
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def rpc_order(self, sender, pubkey, encrypted):
try:
box = Box(self.signing_key.to_curve25519_private_key(), PublicKey(pubkey))
order = box.decrypt(encrypted)
c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict),
testnet=self.multiplexer.testnet)
v = c.verify(sender.pubkey)
if v is True:
self.router.addContact(sender)
self.log.info("received an order from %s, waiting for payment..." % sender)
payment_address = c.contract["buyer_order"]["order"]["payment"]["address"]
chaincode = c.contract["buyer_order"]["order"]["payment"]["chaincode"]
masterkey_b = c.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
buyer_key = derive_childkey(masterkey_b, chaincode)
amount = c.contract["buyer_order"]["order"]["payment"]["amount"]
listing_hash = c.contract["vendor_offer"]["listing"]["contract_id"]
signature = self.signing_key.sign(
str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64]
c.await_funding(self.get_notification_listener(), self.multiplexer.blockchain, signature, False)
return [signature]
else:
self.log.warning("received invalid order from %s reason %s" % (sender, v))
return ["False"]
except Exception, e:
self.log.error("Exception (%s) occurred processing order from %s" % (e.message, sender))
return ["False"]
示例12: validate_workload
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def validate_workload(r):
if "powq" in r.args and "powa" in r.args:
q = base64.b64decode(r.args["powq"][0])
a = r.args["powa"][0]
box = Box(SERVER_KEY, SERVER_KEY.public_key)
q = box.decrypt(q).split(",")
if q[1] != a:
print 1
defer.returnValue(False)
return
# Work is expired
if (float(q[0]) - time.time()) > 80:
print 2
defer.returnValue(False)
return
ex = yield REDIS.get(":workload:%s" % r.getClientIP())
ex = ex or 1
# Work load is smaller than what we require
if int(q[2]) < int(ex):
defer.returnValue(False)
return
defer.returnValue(True)
return
defer.returnValue(False)
示例13: parse_messages
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def parse_messages(messages):
if messages is not None:
for message in messages:
try:
value = objects.Value()
value.ParseFromString(message)
try:
box = Box(PrivateKey(self.signing_key.encode()), PublicKey(value.valueKey))
ciphertext = value.serializedData
plaintext = box.decrypt(ciphertext)
p = objects.Plaintext_Message()
p.ParseFromString(plaintext)
signature = p.signature
p.ClearField("signature")
verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
verify_key.verify(p.SerializeToString(), signature)
h = nacl.hash.sha512(p.signed_pubkey)
pow_hash = h[64:128]
if int(pow_hash[:6], 16) >= 50 or hexlify(p.sender_guid) != h[:40]:
raise Exception('Invalid guid')
listener.notify(p.sender_guid, p.encryption_pubkey, p.subject,
objects.Plaintext_Message.Type.Name(p.type), p.message)
except Exception:
pass
signature = self.signing_key.sign(value.valueKey)[:64]
self.kserver.delete(self.kserver.node.id, value.valueKey, signature)
except Exception:
pass
示例14: parse_messages
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def parse_messages(messages):
if messages is not None:
self.log.info("retrieved %s message(s) from the dht" % len(messages))
for message in messages:
try:
value = objects.Value()
value.ParseFromString(message)
try:
box = Box(PrivateKey(self.signing_key.encode()), PublicKey(value.valueKey))
ciphertext = value.serializedData
plaintext = box.decrypt(ciphertext)
p = objects.Plaintext_Message()
p.ParseFromString(plaintext)
signature = p.signature
p.ClearField("signature")
verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
verify_key.verify(p.SerializeToString(), signature)
h = nacl.hash.sha512(p.signed_pubkey)
pow_hash = h[64:128]
if int(pow_hash[:6], 16) >= 50 or p.sender_guid.encode("hex") != h[:40]:
raise Exception('Invalid guid')
if p.type == objects.Plaintext_Message.Type.Value("ORDER_CONFIRMATION"):
c = Contract(self.db, hash_value=unhexlify(p.subject))
c.accept_order_confirmation(self.protocol.multiplexer.ws,
confirmation_json=p.message)
else:
listener.notify(p.sender_guid, p.encryption_pubkey, p.subject,
objects.Plaintext_Message.Type.Name(p.type), p.message)
except Exception:
pass
signature = self.signing_key.sign(value.valueKey)[:64]
self.kserver.delete(self.kserver.node.id, value.valueKey, signature)
except Exception:
pass
示例15: decode_report
# 需要导入模块: from nacl.public import Box [as 别名]
# 或者: from nacl.public.Box import decrypt [as 别名]
def decode_report(report, reporterkey, nonce, keyfile):
pk = decode_reporter_key(reporterkey)
sk = decode_server_secret_key(keyfile)
nonce = from_hex(nonce)
ciphertext = from_hex(report)
box = Box(sk, pk)
plaintext = box.decrypt(ciphertext, nonce)
return plaintext