本文整理汇总了Python中nacl.signing.SigningKey类的典型用法代码示例。如果您正苦于以下问题:Python SigningKey类的具体用法?Python SigningKey怎么用?Python SigningKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SigningKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decrypt_message
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
示例2: test_message_signing
def test_message_signing(self, seed, message, signature, expected):
signing_key = SigningKey(seed, encoder=HexEncoder)
signed = signing_key.sign(binascii.unhexlify(message), encoder=HexEncoder)
assert signed == expected
assert signed.message == message
assert signed.signature == signature
示例3: 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
示例4: test_key_conversion
def test_key_conversion(self):
keypair_seed = (b"421151a459faeade3d247115f94aedae"
b"42318124095afabe4d1451a559faedee")
signing_key = SigningKey(binascii.unhexlify(keypair_seed))
verify_key = signing_key.verify_key
private_key = bytes(signing_key.to_curve25519_private_key())
public_key = bytes(verify_key.to_curve25519_public_key())
assert tohex(private_key) == ("8052030376d47112be7f73ed7a019293"
"dd12ad910b654455798b4667d73de166")
assert tohex(public_key) == ("f1814f0e8ff1043d8a44d25babff3ced"
"cae6c22c3edaa48f857ae70de2baae50")
示例5: sign
def sign(self, message, private_key):
"""
Sign the message.
This method will take the currently configured values for the message
prefix and suffix and create a signature using the provided Ed25519 private key.
Args:
message (bytes): message to be signed
private_key (bytes) Ed25519 private key
"""
sk = SigningKey(private_key)
self.public_key = sk.verify_key.encode()
self.signature = sk.sign(message).signature
return self.signature
示例6: __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
示例7: test_verify_with_prefix
def test_verify_with_prefix(self):
sk = SigningKey.generate()
vk = sk.verify_key
m = "body"
prefix = "prefix:"
sk2 = SigningKey.generate()
sm1 = sk.sign(prefix+m)
sm2 = sk.sign("not the prefix"+m)
sm3 = sk2.sign(prefix+m)
self.failUnlessEqual(util.verify_with_prefix(vk, sm1, prefix), m)
self.failUnlessRaises(errors.BadSignatureError,
util.verify_with_prefix, vk, sm2, prefix)
self.failUnlessRaises(CryptoError,
util.verify_with_prefix, vk, sm3, prefix)
示例8: test_wrong_types
def test_wrong_types():
sk = SigningKey.generate()
check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, 12)
check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, sk)
check_type_error("SigningKey must be created from a 32 byte seed", SigningKey, sk.verify_key)
check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, 13)
check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, sk)
check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, sk.verify_key)
示例9: encrypt_message
def encrypt_message(message, identifier):
"""Encrypts a message so that it can be read by all the devices of the
given identifier.
:param message: the message itself, in clear text.
:param identifier: the identifier of the message recipient.
"""
# Cipher the message with a brand new random key.
message_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
message_box = nacl.secret.SecretBox(message_key)
message_nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
encrypted_message = message_box.encrypt(message, message_nonce,
Base64Encoder)
returned = []
# Encrypt the message key with each recipient's public key.
for recipient_device_pub_key in get_public_keys(identifier):
# Generate a new keypair & cipher the key with it.
temp_private_key, temp_public_key = generate_keypair()
box = PublicBox(temp_private_key, recipient_device_pub_key)
nonce = nacl.utils.random(PublicBox.NONCE_SIZE)
encrypted_key = box.encrypt(message_key, nonce, Base64Encoder)
# Sign the message.
mac_key = sha256(box._shared_key, RawEncoder)
signing_key = SigningKey(mac_key)
message_sig = signing_key.sign(message, Base64Encoder)
# Return the public key used to cipher the message key.
returned.append({
'encrypted_key': encrypted_key,
'temp_public_key': temp_public_key.encode(Base64Encoder),
'message_signature': message_sig
})
return {
'encrypted_message': encrypted_message,
'recipients': returned
}
示例10: test_invalid_signed_message
def test_invalid_signed_message(self):
skey = SigningKey.generate()
smessage = skey.sign(b"A Test Message!")
signature, message = smessage.signature, b"A Forged Test Message!"
# Small sanity check
assert skey.verify_key.verify(smessage)
with pytest.raises(BadSignatureError):
skey.verify_key.verify(message, signature)
with pytest.raises(BadSignatureError):
forged = SignedMessage(signature + message)
skey.verify_key.verify(forged)
示例11: test_base64_smessage_with_detached_sig_matches_with_attached_sig
def test_base64_smessage_with_detached_sig_matches_with_attached_sig(self):
sk = SigningKey.generate()
vk = sk.verify_key
smsg = sk.sign(b"Hello World in base64", encoder=Base64Encoder)
msg = smsg.message
b64sig = smsg.signature
sig = Base64Encoder.decode(b64sig)
assert vk.verify(msg, sig, encoder=Base64Encoder) == \
vk.verify(smsg, encoder=Base64Encoder)
assert Base64Encoder.decode(msg) == b"Hello World in base64"
示例12: test_hex_smessage_with_detached_sig_matches_with_attached_sig
def test_hex_smessage_with_detached_sig_matches_with_attached_sig(self):
sk = SigningKey.generate()
vk = sk.verify_key
smsg = sk.sign(b"Hello World in hex", encoder=HexEncoder)
msg = smsg.message
hexsig = smsg.signature
sig = HexEncoder.decode(hexsig)
assert vk.verify(msg, sig, encoder=HexEncoder) == \
vk.verify(smsg, encoder=HexEncoder)
assert HexEncoder.decode(msg) == b"Hello World in hex"
示例13: startInvitation
def startInvitation(self, petname, code, transports):
#print "invite", petname, code.encode("hex")
stretched = stretch(code)
inviteKey = SigningKey(stretched)
inviteID = inviteKey.verify_key.encode(Hex)
mySigningKey = SigningKey.generate()
myCIDkey = os.urandom(32)
myTempPrivkey = PrivateKey.generate()
# create my channel record
tids = ",".join([str(tid) for tid in sorted(transports.keys())])
channel_key = PrivateKey.generate()
pub_crec = { "channel_pubkey": channel_key.public_key.encode(Hex),
"CID_key": myCIDkey.encode("hex"),
"transports": transports.values(),
}
priv_data = { "my_signkey": mySigningKey.encode(Hex),
"my_CID_key": myCIDkey.encode("hex"),
"my_old_channel_privkey": channel_key.encode(Hex),
"my_new_channel_privkey": channel_key.encode(Hex),
"transport_ids": tids,
}
db = self.db
c = db.execute("SELECT inviteID FROM invitations")
if inviteID in [str(row[0]) for row in c.fetchall()]:
raise CommandError("invitation code already in use")
iid = db.insert("INSERT INTO `invitations`"
" (code, petname, inviteKey,"
" inviteID,"
" myTempPrivkey, mySigningKey,"
" my_channel_record, my_private_channel_data,"
" myMessages, theirMessages, nextExpectedMessage)"
" VALUES (?,?,?, ?, ?,?, ?,?, ?,?,?)",
(code.encode("hex"), petname, stretched.encode("hex"),
inviteID,
myTempPrivkey.encode(Hex), mySigningKey.encode(Hex),
json.dumps(pub_crec), json.dumps(priv_data),
"", "", 1),
"invitations")
self.subscribe(inviteID)
i = Invitation(iid, self.db, self)
i.sendFirstMessage()
self.db.commit()
示例14: __init__
def __init__(self, iid, db, manager):
self.iid = iid
self.db = db
self.manager = manager
c = self.db.execute("SELECT petname, inviteID, inviteKey," # 0,1,2
" theirTempPubkey," # 3
" nextExpectedMessage," # 4
" myMessages," # 5
" theirMessages" # 6
" FROM invitations WHERE id = ?", (iid,))
res = c.fetchone()
if not res:
raise KeyError("no pending Invitation for '%d'" % iid)
self.petname = res[0]
self.inviteID = res[1]
self.inviteKey = SigningKey(res[2].decode("hex"))
self.theirTempPubkey = None
if res[3]:
self.theirTempPubkey = PublicKey(res[3].decode("hex"))
self.nextExpectedMessage = int(res[4])
self.myMessages = splitMessages(res[5])
self.theirMessages = splitMessages(res[6])
示例15: tick
class Invitation:
# This has a brief lifetime: one is created in response to the rendezvous
# client discovering new messages for us, used for one reactor tick, then
# dereferenced. It holds onto a few values during that tick (which may
# process multiple messages for a single invitation, e.g. A's second poll
# will receive both B-m1 and B-m2 together). But all persistent state
# beyond that one tick is stored in the database.
def __init__(self, iid, db, manager):
self.iid = iid
self.db = db
self.manager = manager
c = self.db.execute("SELECT petname, inviteID, inviteKey," # 0,1,2
" theirTempPubkey," # 3
" nextExpectedMessage," # 4
" myMessages," # 5
" theirMessages" # 6
" FROM invitations WHERE id = ?", (iid,))
res = c.fetchone()
if not res:
raise KeyError("no pending Invitation for '%d'" % iid)
self.petname = res[0]
self.inviteID = res[1]
self.inviteKey = SigningKey(res[2].decode("hex"))
self.theirTempPubkey = None
if res[3]:
self.theirTempPubkey = PublicKey(res[3].decode("hex"))
self.nextExpectedMessage = int(res[4])
self.myMessages = splitMessages(res[5])
self.theirMessages = splitMessages(res[6])
def getAddressbookID(self):
c = self.db.execute("SELECT addressbook_id FROM invitations"
" WHERE id = ?", (self.iid,))
return c.fetchone()[0]
def getMyTempPrivkey(self):
c = self.db.execute("SELECT myTempPrivkey FROM invitations"
" WHERE id = ?", (self.iid,))
return PrivateKey(c.fetchone()[0].decode("hex"))
def getMySigningKey(self):
c = self.db.execute("SELECT mySigningKey FROM invitations"
" WHERE id = ?", (self.iid,))
return SigningKey(c.fetchone()[0].decode("hex"))
def getMyPublicChannelRecord(self):
c = self.db.execute("SELECT my_channel_record FROM invitations"
" WHERE id = ?", (self.iid,))
return c.fetchone()[0]
def getMyPrivateChannelData(self):
c = self.db.execute("SELECT my_private_channel_data FROM invitations"
" WHERE id = ?", (self.iid,))
return json.loads(c.fetchone()[0])
def sendFirstMessage(self):
pub = self.getMyTempPrivkey().public_key.encode()
self.send("i0:m1:"+pub)
self.db.update("UPDATE invitations SET myMessages=? WHERE id=?",
(",".join(self.myMessages), self.iid),
"invitations", self.iid)
# that will be commited by our caller
def processMessages(self, messages):
# These messages are neither version-checked nor signature-checked.
# Also, we may have already processed some of them.
#print "processMessages", messages
#print " my", self.myMessages
#print " theirs", self.theirMessages
assert isinstance(messages, set), type(messages)
assert None not in messages, messages
assert None not in self.myMessages, self.myMessages
assert None not in self.theirMessages, self.theirMessages
# Send anything that didn't make it to the server. This covers the
# case where we commit our outbound message in send() but crash
# before finishing delivery.
for m in self.myMessages - messages:
#print "resending", m
self.manager.sendToAll(self.inviteID, m)
newMessages = messages - self.myMessages - self.theirMessages
#print " %d new messages" % len(newMessages)
if not newMessages:
print " huh, no new messages, stupid rendezvous client"
# check signatures, extract bodies. invalid messages kill the channel
# and the invitation. MAYBE TODO: lose the one channel, keep using
# the others.
bodies = set()
for m in newMessages:
#print " new inbound message", m
try:
if not m.startswith("r0:"):
print "unrecognized rendezvous message prefix"
if not VALID_MESSAGE.search(m):
raise CorruptChannelError()
m = m[len("r0:"):].decode("hex")
bodies.add(self.inviteKey.verify_key.verify(m))
except (BadSignatureError, CorruptChannelError) as e:
#.........这里部分代码省略.........