本文整理汇总了Python中nacl.public.PrivateKey类的典型用法代码示例。如果您正苦于以下问题:Python PrivateKey类的具体用法?Python PrivateKey怎么用?Python PrivateKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PrivateKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_new_channel
def add_new_channel(self, nA, nB):
a_signkey = SigningKey.generate()
a_chankey = PrivateKey.generate()
a_CIDkey = os.urandom(32)
a_transports = nA.agent.individualize_transports(nA.agent.get_transports())
b_signkey = SigningKey.generate()
b_chankey = PrivateKey.generate()
b_CIDkey = os.urandom(32)
b_transports = nB.agent.individualize_transports(nB.agent.get_transports())
a_rec = { "channel_pubkey": a_chankey.public_key.encode().encode("hex"),
"CID_key": a_CIDkey.encode("hex"),
"transports": a_transports.values(),
}
b_rec = { "channel_pubkey": b_chankey.public_key.encode().encode("hex"),
"CID_key": b_CIDkey.encode("hex"),
"transports": b_transports.values(),
}
q = ("INSERT INTO addressbook"
" (petname, acked, next_outbound_seqnum,"
" my_signkey,"
" their_channel_record_json,"
" my_CID_key, next_CID_token,"
" highest_inbound_seqnum,"
" my_old_channel_privkey, my_new_channel_privkey,"
" they_used_new_channel_key, their_verfkey)"
" VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")
vA=("petname-from-A", 1, 1,
a_signkey.encode().encode("hex"),
json.dumps(b_rec),
a_CIDkey.encode("hex"), None,
0,
a_chankey.encode().encode("hex"),
a_chankey.encode().encode("hex"),
0, b_signkey.verify_key.encode().encode("hex"),
)
vB=("petname-from-A", 1, 1,
b_signkey.encode().encode("hex"),
json.dumps(a_rec),
b_CIDkey.encode("hex"), None,
0,
b_chankey.encode().encode("hex"),
b_chankey.encode().encode("hex"),
0, a_signkey.verify_key.encode().encode("hex"),
)
nA.db.execute(q, vA)
nA.db.commit()
nB.db.execute(q, vB)
nA.db.commit()
entA = nA.db.execute("SELECT * FROM addressbook").fetchone()
entB = nB.db.execute("SELECT * FROM addressbook").fetchone()
return entA, entB
示例2: test_nacl_encrypt_decrypt
def test_nacl_encrypt_decrypt():
skbob = PrivateKey.generate()
pkbob = skbob.public_key
skalice = PrivateKey.generate()
pkalice = skalice.public_key
message_bytes = nacl.utils.random(SALT_SIZE)
encrypted = nacl_encrypt(message_bytes, skbob, pkalice)
decrypted = nacl_decrypt(encrypted, skalice, pkbob)
assert decrypted == message_bytes
示例3: test_box_seal
def test_box_seal(
privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext):
pubalice = PublicKey(pubalice, encoder=HexEncoder)
privalice = PrivateKey(privalice, encoder=HexEncoder)
plaintext = binascii.unhexlify(plaintext)
sealed = pubalice.seal(plaintext)
unsealed = privalice.seal_open(sealed)
assert plaintext == unsealed
sealed2 = privalice.seal(plaintext)
unsealed2 = privalice.seal_open(sealed2)
assert plaintext == unsealed2
示例4: test_list_request
def test_list_request(self):
serverkey = PrivateKey.generate()
RT = "01234567" # 8 bytes
req, tmppub = retrieval.encrypt_list_request(serverkey.public_key.encode(), RT)
got_tmppub, boxed0 = server.decrypt_list_request_1(req)
ts, got_RT = server.decrypt_list_request_2(got_tmppub, boxed0, serverkey)
self.failUnlessEqual(RT, got_RT)
示例5: __new__
def __new__(cls, microdescriptor):
relay_identity = decodeMicrodescriptorIdentifier(microdescriptor)
relay_ntor_onion_key = base64.b64decode(microdescriptor.ntor_onion_key)
secret_key = PrivateKey.generate()
public_key = secret_key.public_key
return super(NTorState, cls).__new__(
cls, relay_identity, relay_ntor_onion_key, secret_key, public_key)
示例6: key_gen
def key_gen(self):
"""Generate a private key"""
import base64, zlib
from nacl.public import PrivateKey
privObj = PrivateKey.generate()
privKey = base64.b64encode(zlib.compress(str(privObj), 9))
return privObj, privKey
示例7: purchase
def purchase(self, node_to_ask, contract):
"""
Send an order message to the vendor.
Args:
node_to_ask: a `dht.node.Node` object
contract: a complete `Contract` object containing the buyer's order
"""
def parse_response(response):
try:
address = contract.contract["buyer_order"]["order"]["payment"]["address"]
verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:])
verify_key.verify(str(address), response[1][0])
return response[1][0]
except Exception:
return False
public_key = contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"]
skephem = PrivateKey.generate()
pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
d = self.protocol.callOrder(node_to_ask, pkephem, ciphertext)
return d.addCallback(parse_response)
示例8: __enter__
def __enter__(self) -> typing.Tuple[PrivateKey, PrivateKey]:
"""
Provides a pair of private keys.
"""
# Derive the key from the passphrase.
derived = util.derive_passphrase(self.passphrase)
sign_box = SecretBox(derived)
enc_box = SecretBox(derived)
# Decrypt, using the two nonces.
s_d = sign_box.decrypt(self.key._private_signing_seed, self.key._private_signing_nonce)
e_d = enc_box.decrypt(self.key._private_key_raw, self.key._private_nonce)
# Generate a SigningKey out of the seed.
self.sign = SigningKey(s_d)
self.encrypt = PrivateKey(e_d)
# Update the key's public keys.
if self.key._public_key is None:
self.key._public_key = self.encrypt.public_key
if self.key._public_signing_key is None:
self.key._public_signing_key = self.sign.verify_key
return self.encrypt, self.sign
示例9: get_node
def get_node(node_to_ask):
def parse_response(response):
if response[0] and response[1][0] == "True":
return True
elif not response[0]:
contract_dict = json.loads(json.dumps(contract.contract, indent=4),
object_pairs_hook=OrderedDict)
del contract_dict["vendor_order_confirmation"]
del contract_dict["buyer_receipt"]
order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex")
self.send_message(Node(unhexlify(guid)),
contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"],
objects.Plaintext_Message.Type.Value("RECEIPT"),
json.dumps(contract.contract["buyer_receipt"]),
order_id,
store_only=True)
return True
else:
return False
if node_to_ask:
public_key = contract.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["encryption"]
skephem = PrivateKey.generate()
pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
d = self.protocol.callCompleteOrder(node_to_ask, pkephem, ciphertext)
return d.addCallback(parse_response)
else:
return parse_response([False])
示例10: storeAccount
def storeAccount(phrase, uid, auth, alias):
"""
Store new account information
@param phrase: new passphrase as bytes
@param uid: user id
@param auth: authentication token
@param alias: user set alias for profile
@return: Profile ID of newly created profile and safe
"""
con = getCursor()
# random phrase buffer
buffer = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
# create safe (db encryption)
safe = SecretBox(b''.join((phrase, buffer[len(phrase) - 32:])))
# create new signing_key and verify_key (message signing)
skey = nacl.signing.SigningKey.generate()
# create new private and public key (message encryption)
mkey = PrivateKey.generate()
con.execute("INSERT INTO profiles (uid, auth, signing_key, verify_key, private_key, public_key, buffer, alias) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
list(encrypt(safe, uid, auth, skey._seed, skey.verify_key.encode(encoder=nacl.encoding.HexEncoder),
mkey._private_key, mkey.public_key._public_key)) + [buffer, alias])
profileId = con.lastrowid
return profileId, safe
示例11: create_node
def create_node(so, stdout=sys.stdout, stderr=sys.stderr):
basedir = so["basedir"]
if os.path.exists(basedir):
print >>stderr, "basedir '%s' already exists, refusing to touch it" % basedir
return 1
os.mkdir(basedir)
dbfile = os.path.join(basedir, "petmail.db")
db = database.get_db(dbfile, stderr)
db.execute("INSERT INTO node (webhost, webport) VALUES (?,?)",
(so["webhost"], so["webport"]))
db.execute("INSERT INTO services (name) VALUES (?)", ("client",))
db.execute("INSERT INTO `client_profile`"
" (`name`, `icon_data`) VALUES (?,?)",
("",""))
privkey = PrivateKey.generate()
TID_tokenid, TID_privkey, TID_token0 = rrid.create()
server_desc = { "transport_privkey": privkey.encode().encode("hex"),
"TID_private_key": TID_privkey.encode("hex"),
"local_TID0": TID_token0.encode("hex"),
"local_TID_tokenid": TID_tokenid.encode("hex"),
}
db.execute("INSERT INTO mailbox_server_config"
" (private_descriptor_json, enable_retrieval)"
" VALUES (?,?)",
(json.dumps(server_desc), 0))
db.commit()
print >>stdout, "node created in %s" % basedir
return 0
示例12: authenticate
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
示例13: send_message
def send_message(self, receiving_node, public_key, message_type, message, subject=None):
"""
Sends a message to another node. If the node isn't online it
will be placed in the dht for the node to pick up later.
"""
pro = Profile().get()
if len(message) > 1500:
return
p = objects.Plaintext_Message()
p.sender_guid = self.kserver.node.id
p.signed_pubkey = self.kserver.node.signed_pubkey
p.encryption_pubkey = PrivateKey(self.signing_key.encode()).public_key.encode()
p.type = message_type
p.message = message
if subject is not None:
p.subject = subject
if pro.handle:
p.handle = pro.handle
if pro.avatar_hash:
p.avatar_hash = pro.avatar_hash
p.timestamp = int(time.time())
signature = self.signing_key.sign(p.SerializeToString())[:64]
p.signature = signature
skephem = PrivateKey.generate()
pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = box.encrypt(p.SerializeToString(), nonce)
def get_response(response):
if not response[0]:
self.kserver.set(digest(receiving_node.id), pkephem, ciphertext)
self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
示例14: respond_to_rekey
def respond_to_rekey(self, message):
# Verify length
if not len(message) == 34 + self._mac_length:
_logger.info('Invalid length of rekey')
# TODO: Multi-byte asequence numbers should also be allowed
return
# Verify MAC
msg, sig = message[:-self._mac_length], message[-self._mac_length:]
if not self.verify_mac(message):
_logger.info('Invalid MAC on rekey')
return
# Verify sequence number
if not self.validate_and_update_others_seqnum(msg):
_logger.info('Invalid sequence number on rekey')
return
client_pubkey = msg[2:]
self.pkey = PrivateKey.generate()
self.new_master_key = self.derive_shared_key(client_pubkey)
msg = six.int2byte(Message.rekey_response) + encode_varint(self.my_seq) + self.pkey.public_key._public_key
self.state = ServerState.rekey
full_msg = msg + self.get_mac(msg)
self._send(full_msg)
self.my_seq += 1
示例15: get_node
def get_node(node_to_ask, recipient_guid, public_key):
def parse_response(response):
if not response[0]:
self.send_message(
Node(unhexlify(recipient_guid)),
nacl.signing.VerifyKey(public_key, encoder=nacl.encoding.HexEncoder)
.to_curve25519_public_key()
.encode(),
objects.PlaintextMessage.Type.Value("DISPUTE_OPEN"),
json.dumps(contract),
order_id,
store_only=True,
)
if node_to_ask:
enc_key = nacl.signing.VerifyKey(
public_key, encoder=nacl.encoding.HexEncoder
).to_curve25519_public_key()
skephem = PrivateKey.generate()
pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
box = Box(skephem, enc_key)
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = box.encrypt(json.dumps(contract, indent=4), nonce)
d = self.protocol.callDisputeOpen(node_to_ask, pkephem, ciphertext)
return d.addCallback(parse_response)
else:
return parse_response([False])