本文整理汇总了Python中nacl.public.PrivateKey.generate方法的典型用法代码示例。如果您正苦于以下问题:Python PrivateKey.generate方法的具体用法?Python PrivateKey.generate怎么用?Python PrivateKey.generate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nacl.public.PrivateKey
的用法示例。
在下文中一共展示了PrivateKey.generate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_new_channel
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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_list_request
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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)
示例4: __new__
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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)
示例5: key_gen
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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
示例6: purchase
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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)
示例7: respond_to_rekey
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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
示例8: authenticate
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [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
示例9: storeAccount
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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
示例10: get_node
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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"]
order_id = digest(json.dumps(contract_dict, indent=4)).encode("hex")
self.send_message(Node(unhexlify(guid)),
nacl.signing.VerifyKey(
contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"],
encoder=nacl.encoding.HexEncoder).to_curve25519_public_key().encode(),
objects.PlaintextMessage.Type.Value("ORDER_CONFIRMATION"),
json.dumps(contract.contract["vendor_order_confirmation"]),
order_id,
store_only=True)
return True
else:
return False
if node_to_ask:
public_key = nacl.signing.VerifyKey(
contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["guid"],
encoder=nacl.encoding.HexEncoder).to_curve25519_public_key()
skephem = PrivateKey.generate()
pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
box = Box(skephem, public_key)
nonce = nacl.utils.random(Box.NONCE_SIZE)
ciphertext = box.encrypt(json.dumps(contract.contract, indent=4), nonce)
d = self.protocol.callOrderConfirmation(node_to_ask, pkephem, ciphertext)
return d.addCallback(parse_response)
else:
return parse_response([False])
示例11: send_message
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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)
示例12: get_node
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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])
示例13: send_rekey
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
def send_rekey(self):
self.pkey = PrivateKey.generate()
msg = six.int2byte(Message.rekey) + encode_varint(self.my_seq) + self.pkey.public_key._public_key
mac = self.get_mac(msg)
self.my_seq += 1
self._send(msg + mac)
self.state = ClientState.rekey
示例14: test_wrong_types
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
def test_wrong_types():
priv = PrivateKey.generate()
check_type_error(("PrivateKey must be created from a 32 bytes long "
"raw secret key"),
PrivateKey, 12)
check_type_error(("PrivateKey must be created from a 32 bytes long "
"raw secret key"),
PrivateKey, priv)
check_type_error(("PrivateKey must be created from a 32 bytes long "
"raw secret key"),
PrivateKey, priv.public_key)
check_type_error("PublicKey must be created from 32 bytes",
PublicKey, 13)
check_type_error("PublicKey must be created from 32 bytes",
PublicKey, priv)
check_type_error("PublicKey must be created from 32 bytes",
PublicKey, priv.public_key)
check_type_error("Box must be created from a PrivateKey and a PublicKey",
Box, priv, "not a public key")
check_type_error("Box must be created from a PrivateKey and a PublicKey",
Box, priv.encode(), priv.public_key.encode())
check_type_error("Box must be created from a PrivateKey and a PublicKey",
Box, priv, priv.public_key.encode())
check_type_error("Box must be created from a PrivateKey and a PublicKey",
Box, priv.encode(), priv.public_key)
check_type_error("seed must be a 32 bytes long",
PrivateKey.from_seed, b"1")
示例15: purchase
# 需要导入模块: from nacl.public import PrivateKey [as 别名]
# 或者: from nacl.public.PrivateKey import generate [as 别名]
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"]
chaincode = contract.contract["buyer_order"]["order"]["payment"]["chaincode"]
masterkey_b = contract.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
buyer_key = derive_childkey(masterkey_b, chaincode)
amount = contract.contract["buyer_order"]["order"]["payment"]["amount"]
listing_hash = contract.contract["buyer_order"]["order"]["ref_hash"]
verify_key = nacl.signing.VerifyKey(node_to_ask.signed_pubkey[64:])
verify_key.verify(
str(address) + str(amount) + str(listing_hash) + str(buyer_key), 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)
self.log.info("purchasing contract %s from %s" % (contract.get_contract_id().encode("hex"), node_to_ask))
return d.addCallback(parse_response)