本文整理匯總了Python中secp256k1.PublicKey方法的典型用法代碼示例。如果您正苦於以下問題:Python secp256k1.PublicKey方法的具體用法?Python secp256k1.PublicKey怎麽用?Python secp256k1.PublicKey使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類secp256k1
的用法示例。
在下文中一共展示了secp256k1.PublicKey方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_schnorr
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_schnorr():
if not secp256k1.HAS_SCHNORR:
pytest.skip('secp256k1_schnorr not enabled, skipping')
return
inst = secp256k1.PrivateKey()
raw_sig = inst.schnorr_sign(b'hello')
test1 = secp256k1.PublicKey(inst.pubkey.public_key,
flags=secp256k1.NO_FLAGS)
with pytest.raises(Exception):
test1.schnorr_verify(b'hello', raw_sig)
blank = secp256k1.PublicKey(flags=secp256k1.NO_FLAGS)
with pytest.raises(Exception):
blank.schnorr_recover(b'hello', raw_sig)
blank = secp256k1.PublicKey(flags=secp256k1.FLAG_SIGN)
with pytest.raises(Exception):
blank.schnorr_recover(b'hello', raw_sig)
示例2: test_schnorr_partial
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_schnorr_partial():
if not secp256k1.HAS_SCHNORR:
pytest.skip('secp256k1_schnorr not enabled, skipping')
return
signer1 = secp256k1.PrivateKey()
pubnonce1, privnonce1 = signer1.schnorr_generate_nonce_pair(b'hello')
signer2 = secp256k1.PrivateKey()
pubnonce2, privnonce2 = signer2.schnorr_generate_nonce_pair(b'hello')
partial1 = signer1.schnorr_partial_sign(b'hello', privnonce1, pubnonce2)
blank = secp256k1.PublicKey(flags=secp256k1.NO_FLAGS)
with pytest.raises(TypeError):
blank.schnorr_partial_combine([partial1, secp256k1.ffi.NULL])
with pytest.raises(Exception):
blank.schnorr_partial_combine([partial1, b''])
示例3: test_ecdh
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_ecdh():
if not secp256k1.HAS_ECDH:
pytest.skip('secp256k1_ecdh not enabled, skipping')
return
pubkey = secp256k1.PrivateKey().pubkey
p = secp256k1.PublicKey(pubkey.public_key)
with pytest.raises(Exception):
# Bad scalar length.
p.ecdh(b'')
with pytest.raises(Exception):
# Bad scalar type.
p.ecdh([])
res = p.ecdh(b'0' * 32)
assert type(res) == bytes
示例4: test_pubkey_combine
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_pubkey_combine():
k1 = secp256k1.PrivateKey()
k2 = secp256k1.PrivateKey()
pub1 = k1.pubkey.public_key
pub2 = k2.pubkey.public_key
new = secp256k1.PublicKey()
assert new.public_key is None
res = new.combine([pub1, pub2])
assert new.public_key == res
new = secp256k1.PublicKey()
assert new.public_key is None
res = new.combine([pub1])
assert new.public_key == res
assert new.serialize() == k1.pubkey.serialize()
示例5: test_pubkey_tweak
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_pubkey_tweak():
inst = secp256k1.PrivateKey()
pub = inst.pubkey
scalar = [b'\x01' * 32]
with pytest.raises(TypeError):
pub.tweak_add(scalar)
with pytest.raises(TypeError):
pub.tweak_mul(scalar)
scalar = b'\x01' * 31
with pytest.raises(TypeError):
pub.tweak_add(scalar)
with pytest.raises(TypeError):
pub.tweak_mul(scalar)
scalar = scalar + b'\x01'
res = pub.tweak_add(scalar)
assert isinstance(res, secp256k1.PublicKey)
assert res.serialize() != pub.serialize()
示例6: __init__
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def __init__(self, privkey=None, raw=True, flags=None, ctx=None):
if USE_SECP:
if flags == None:
flags = secp256k1.ALL_FLAGS
self.obj = secp256k1.PrivateKey(privkey, raw, flags, ctx)
self.pubkey = self.obj.pubkey
else:
if not raw:
raise Exception("Non raw init unsupported")
if privkey == None:
privkey = ecpy.ecrand.rnd(CURVE_SECP256K1.order)
else:
privkey = int.from_bytes(privkey,'big')
self.obj = ECPrivateKey(privkey, CURVE_SECP256K1)
pubkey = self.obj.get_public_key().W
out = b"\x04"
out += pubkey.x.to_bytes(32, 'big')
out += pubkey.y.to_bytes(32, 'big')
self.pubkey = PublicKey(out, raw=True)
示例7: create_address
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def create_address(self, public_key: PublicKey) -> str:
serialized_pub = public_key.serialize(compressed=False)
hashed_pub = hashlib.sha3_256(serialized_pub[1:]).hexdigest()
return f"hx{hashed_pub[-40:]}"
示例8: verify_signature
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def verify_signature(self, origin_data: bytes, signature: bytes, is_hash: bool):
try:
origin_signature, recover_code = signature[:-1], signature[-1]
recoverable_sig = self._pri.ecdsa_recoverable_deserialize(origin_signature, recover_code)
pub = self._pri.ecdsa_recover(origin_data,
recover_sig=recoverable_sig,
raw=is_hash,
digest=hashlib.sha3_256)
extract_pub = PublicKey(pub, ctx=self._base.ctx).serialize(compressed=False)
return self.verify_address(extract_pub)
except Exception as e:
raise RuntimeError(f"signature verification fail : {origin_data} {signature}\n"
f"{e}")
示例9: verify
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def verify(self, signature, message):
"""
Verify signature, raise exception if it is not valid
:param message: sequance of bytes, raw format or hexadecimal notation
:param signature: a signature in base58 encoding
"""
signature = scrub_input(signature)
message = scrub_input(message)
if not self._public_key:
raise ValueError("Cannot verify without a public key")
if signature[:3] != b'sig': # not generic
if self.curve != signature[:2]: # "sp", "p2" "ed"
raise ValueError("Signature and public key curves mismatch.")
signature = base58_decode(signature)
# Ed25519
if self.curve == b"ed":
digest = pysodium.crypto_generichash(message)
try:
pysodium.crypto_sign_verify_detached(signature, digest, self._public_key)
except ValueError:
raise ValueError('Signature is invalid.')
# Secp256k1
elif self.curve == b"sp":
pk = secp256k1.PublicKey(self._public_key, raw=True)
sig = pk.ecdsa_deserialize_compact(signature)
if not pk.ecdsa_verify(message, sig, digest=blake2b_32):
raise ValueError('Signature is invalid.')
# P256
elif self.curve == b"p2":
pk = SEC1Encoder.decode_public_key(self._public_key, curve=P256)
r, s = bytes_to_int(signature[:32]), bytes_to_int(signature[32:])
if not verify(sig=(r, s), msg=message, Q=pk, hashfunc=blake2b_32):
raise ValueError('Signature is invalid.')
else:
assert False
示例10: test_ecdsa_recover
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_ecdsa_recover():
if not secp256k1.HAS_RECOVERABLE:
pytest.skip('secp256k1_recovery not enabled, skipping')
return
class MyECDSA(secp256k1.Base, secp256k1.ECDSA):
def __init__(self):
secp256k1.Base.__init__(self, ctx=None, flags=secp256k1.ALL_FLAGS)
privkey = secp256k1.PrivateKey()
unrelated = MyECDSA()
# Create a signature that allows recovering the public key.
recsig = privkey.ecdsa_sign_recoverable(b'hello')
# Recover the public key.
pubkey = unrelated.ecdsa_recover(b'hello', recsig)
# Check that the recovered public key matches the one used
# in privkey.pubkey.
pubser = secp256k1.PublicKey(pubkey).serialize()
assert privkey.pubkey.serialize() == pubser
# Check that after serializing and deserializing recsig
# we still recover the same public key.
recsig_ser = unrelated.ecdsa_recoverable_serialize(recsig)
recsig2 = unrelated.ecdsa_recoverable_deserialize(*recsig_ser)
pubkey2 = unrelated.ecdsa_recover(b'hello', recsig2)
pubser2 = secp256k1.PublicKey(pubkey2).serialize()
assert pubser == pubser2
raw_sig = unrelated.ecdsa_recoverable_convert(recsig2)
unrelated.ecdsa_deserialize(unrelated.ecdsa_serialize(raw_sig))
示例11: test_publickey
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_publickey():
with pytest.raises(Exception):
# Must be bytes.
# In Python 2 this will not raise a TypeError
# since bytes is an alias to str, instead it will fail
# during deserialization.
secp256k1.PublicKey('abc', raw=True)
with pytest.raises(Exception):
secp256k1.PublicKey([], raw=True)
with pytest.raises(Exception):
# Invalid size.
secp256k1.PublicKey(b'abc', raw=True)
with pytest.raises(Exception):
# Invalid public key.
secp256k1.PublicKey(b'a' * 33, raw=True)
# Invalid usage: passing a raw public key but not specifying raw=True.
with pytest.raises(TypeError):
secp256k1.PublicKey(b'a' * 33)
# No public key.
assert secp256k1.PublicKey()
pub1 = secp256k1.PrivateKey().pubkey.public_key
new = secp256k1.PublicKey()
with pytest.raises(AssertionError):
# Trying to combine with something that is not a public key.
new.combine([pub1, secp256k1.ffi.NULL])
new = secp256k1.PublicKey()
with pytest.raises(AssertionError):
# Nothing to combine.
new.combine([])
示例12: test_schnorr_partial
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_schnorr_partial():
if not secp256k1.HAS_SCHNORR:
pytest.skip('secp256k1_schnorr not enabled, skipping')
return
signer1 = secp256k1.PrivateKey()
pubnonce1, privnonce1 = signer1.schnorr_generate_nonce_pair(b'hello')
signer2 = secp256k1.PrivateKey()
pubnonce2, privnonce2 = signer2.schnorr_generate_nonce_pair(b'hello')
# First test partial signatures with only two signers.
partial1 = signer1.schnorr_partial_sign(b'hello', privnonce1, pubnonce2)
partial2 = signer2.schnorr_partial_sign(b'hello', privnonce2, pubnonce1)
blank = secp256k1.PublicKey(flags=secp256k1.NO_FLAGS)
sig = blank.schnorr_partial_combine([partial1, partial2])
# Recover the public key from the combined signature.
pubkey = secp256k1.PublicKey().schnorr_recover(b'hello', sig)
assert blank.public_key is None
# Check that the combined public keys from signer1 and signer2
# match the recovered public key.
blank.combine(
[signer1.pubkey.public_key, signer2.pubkey.public_key])
assert blank.public_key
assert secp256k1.PublicKey(pubkey).serialize() == blank.serialize()
示例13: test_pubkey
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def test_pubkey():
privkey = secp256k1.PrivateKey()
sig = privkey.ecdsa_sign(b'hello')
pubkeyser = privkey.pubkey.serialize()
pubkey = secp256k1.PublicKey(pubkeyser, raw=True, flags=secp256k1.NO_FLAGS)
with pytest.raises(Exception):
# FLAG_SIGN was not specified.
pubkey.ecdsa_verify(b'hello', sig)
pubkey = secp256k1.PublicKey(pubkeyser, raw=True)
assert pubkey.ecdsa_verify(b'hello', sig)
示例14: recoverPubkeyParameter
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def recoverPubkeyParameter(message, digest, signature, pubkey):
""" Use to derive a number that allows to easily recover the
public key from the signature
"""
if not isinstance(message, bytes):
message = bytes(message, "utf-8") # pragma: no cover
for i in range(0, 4):
if SECP256K1_MODULE == "secp256k1": # pragma: no cover
sig = pubkey.ecdsa_recoverable_deserialize(signature, i)
p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig))
if p.serialize() == pubkey.serialize():
return i
elif SECP256K1_MODULE == "cryptography" and not isinstance(pubkey, PublicKey):
p = recover_public_key(digest, signature, i, message)
p_comp = hexlify(compressedPubkey(p))
pubkey_comp = hexlify(compressedPubkey(pubkey))
if p_comp == pubkey_comp:
return i
else: # pragma: no cover
p = recover_public_key(digest, signature, i)
p_comp = hexlify(compressedPubkey(p))
p_string = hexlify(p.to_string())
if isinstance(pubkey, PublicKey): # pragma: no cover
pubkey_string = bytes(repr(pubkey), "ascii")
else: # pragma: no cover
pubkey_string = hexlify(pubkey.to_string())
if p_string == pubkey_string or p_comp == pubkey_string: # pragma: no cover
return i
示例15: verify_message
# 需要導入模塊: import secp256k1 [as 別名]
# 或者: from secp256k1 import PublicKey [as 別名]
def verify_message(message, signature, hashfn=hashlib.sha256):
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
if not isinstance(signature, bytes): # pragma: no cover
signature = bytes(signature, "utf-8")
if not isinstance(message, bytes):
raise AssertionError()
if not isinstance(signature, bytes):
raise AssertionError()
digest = hashfn(message).digest()
sig = signature[1:]
# TODO: 4 means we use compressed keys.
# Grapehen uses compressed keys by default even though it would still allow
# uncompressed keys to be used. This library so far expects compressed keys
# due to this line:
recoverParameter = bytearray(signature)[0] - 4 - 27 # recover parameter only
if SECP256K1_MODULE == "secp256k1":
ALL_FLAGS = (
secp256k1.lib.SECP256K1_CONTEXT_VERIFY
| secp256k1.lib.SECP256K1_CONTEXT_SIGN
)
# Placeholder
pub = secp256k1.PublicKey(flags=ALL_FLAGS)
# Recover raw signature
sig = pub.ecdsa_recoverable_deserialize(sig, recoverParameter)
# Recover PublicKey
verifyPub = secp256k1.PublicKey(pub.ecdsa_recover(message, sig))
# Convert recoverable sig to normal sig
normalSig = verifyPub.ecdsa_recoverable_convert(sig)
# Verify
verifyPub.ecdsa_verify(message, normalSig)
phex = verifyPub.serialize(compressed=True)
elif SECP256K1_MODULE == "cryptography":
p = recover_public_key(digest, sig, recoverParameter, message)
order = ecdsa.SECP256k1.order
r, s = ecdsa.util.sigdecode_string(sig, order)
sigder = encode_dss_signature(r, s)
p.verify(sigder, message, ec.ECDSA(hashes.SHA256()))
phex = compressedPubkey(p)
else: # pragma: no branch # pragma: no cover
p = recover_public_key(digest, sig, recoverParameter)
# Will throw an exception of not valid
p.verify_digest(sig, digest, sigdecode=ecdsa.util.sigdecode_string)
phex = compressedPubkey(p)
return phex
# def pointToPubkey(x, y, order=None): # pragma: no cover
# """ This code is untested und thus not commented in. Waiting for unit tests of
# the original author.
# """
# order = order or ecdsa.SECP256k1.order
# x_str = ecdsa.util.number_to_string(x, order)
# return _bytes(chr(2 + (y & 1))) + x_str # pragma: no cover
#