本文整理汇总了Python中ecdsa.VerifyingKey类的典型用法代码示例。如果您正苦于以下问题:Python VerifyingKey类的具体用法?Python VerifyingKey怎么用?Python VerifyingKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VerifyingKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(argv):
"""
Main procedure to generate C array with keys
"""
parser = argparse.ArgumentParser(description="Generates SQLite database with"
" keys and serial number.")
parser.add_argument('config_file', help="project specific configuration file"
)
args = parser.parse_args()
config = ConfigParser.ConfigParser()
config.read(args.config_file)
con = sqlite3.connect(config.get('database', 'filename'))
while 1:
serialno = uuid.uuid4().bytes
oem_factory_token = '%s%s' %(serialno, '\xFF')
customer_factory_token = '%s%s' %(serialno, '\x00\xFF')
private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
public_key = generate_public_key(config.get('tools', 'public_key_cmd'), private_key)
sk = SigningKey.from_der(private_key)
pk = VerifyingKey.from_der(public_key)
embedded_private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
embedded_public_key = generate_public_key(config.get('tools', 'public_key_cmd'), embedded_private_key)
embedded_sk = SigningKey.from_der(embedded_private_key)
embedded_pk = VerifyingKey.from_der(embedded_public_key)
embedded_private_key_sig = embedded_sk.sign(oem_factory_token, hashfunc=sha256)
assert embedded_pk.verify(embedded_private_key_sig, oem_factory_token, hashfunc=sha256)
oem_factory_token_sig = sk.sign(oem_factory_token, hashfunc=sha256)
assert pk.verify(oem_factory_token_sig, oem_factory_token, hashfunc=sha256)
customer_factory_token_sig = sk.sign(customer_factory_token, hashfunc=sha256)
assert pk.verify(customer_factory_token_sig, customer_factory_token, hashfunc=sha256)
debug_token_sig = sk.sign(serialno, hashfunc=sha256)
assert pk.verify(debug_token_sig, serialno, hashfunc=sha256)
public_key_compressed = ecc_compress(pk.to_string())
with con:
cur = con.cursor()
cur.execute(config.get('database', 'create'))
cur.execute(config.get('database', 'insert'),
(sqlite3.Binary(private_key),
sqlite3.Binary(public_key),
sqlite3.Binary(public_key_compressed),
sqlite3.Binary(embedded_private_key),
sqlite3.Binary(embedded_public_key),
sqlite3.Binary(embedded_sk.to_string()),
sqlite3.Binary(serialno),
sqlite3.Binary(oem_factory_token_sig),
sqlite3.Binary(customer_factory_token_sig),
sqlite3.Binary(debug_token_sig)))
示例2: import_public_key_ecc
def import_public_key_ecc(s):
"""
import public ecc key from a hex string
:param s: a hex string generated by export_keys()
:return: a VerifyingKey object
"""
return VerifyingKey.from_string(bytes.fromhex(s), curve=SECP256k1)
示例3: loadpubstr
def loadpubstr(pemstring):
"""
Load a public key from PEM string
:param pemstring:
:return:
"""
return VerifyingKey.from_pem(pemstring)
示例4: create_material
def create_material(self, bits, d=None, x=None, y=None):
curve = self.curve_for_bits(bits)
if d:
return SigningKey.from_secret_exponent(d, curve)
if x and y:
point = ec.Point(curve.curve, x, y, curve.order)
return VerifyingKey.from_public_point(point, curve)
示例5: __init__
def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None):
self.verifying_key = None
self.signing_key = None
if file_obj is not None:
self._from_private_key(file_obj, password)
return
if filename is not None:
self._from_private_key_file(filename, password)
return
if (msg is None) and (data is not None):
msg = Message(data)
if vals is not None:
self.verifying_key, self.signing_key = vals
else:
if msg is None:
raise SSHException('Key object may not be empty')
if msg.get_text() != 'ecdsa-sha2-nistp256':
raise SSHException('Invalid key')
curvename = msg.get_text()
if curvename != 'nistp256':
raise SSHException("Can't handle curve of type %s" % curvename)
pointinfo = msg.get_binary()
if pointinfo[0:1] != four_byte:
raise SSHException('Point compression is being used: %s' %
binascii.hexlify(pointinfo))
self.verifying_key = VerifyingKey.from_string(pointinfo[1:],
curve=curves.NIST256p)
self.size = 256
示例6: process_invoicerequest
def process_invoicerequest(message, id):
resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)
if isinstance(message, ProtocolMessage):
invoice_request = InvoiceRequest()
invoice_request.ParseFromString(message.serialized_message)
# Validate Public Key
vk = from_sec(request.headers.get('x-identity').decode('hex')) or VerifyingKey.from_der(request.headers.get('x-identity').decode('hex'))
allowed_keys = [vk.to_der(), to_sec(vk, False), to_sec(vk, True)]
if invoice_request.sender_public_key not in allowed_keys:
log.warn("InvoiceRequest Public Key Does Not Match X-Identity Public Key")
return create_json_response(False, 'InvoiceRequest Public Key Does Not Match X-Identity Public Key', 400)
if invoice_request.pki_type == 'x509+sha256':
log.debug("InvoiceRequest Contains X509 Certificate, Validating")
if invoice_request.pki_data and not invoice_request.signature:
log.warn('Submitted InvoiceRequest Missing Signature')
return create_json_response(False, 'Requests including x509 cert must include signature', 400)
# Verify signature if cert and signature are present
if invoice_request.pki_data and invoice_request.signature:
try:
x509_certs = X509Certificates()
x509_certs.ParseFromString(invoice_request.pki_data)
cert_data = ssl.DER_cert_to_PEM_cert(x509_certs.certificate[0])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
except Exception as e:
log.warn('Unable to load given x509 certificate [ID: %s]: %s' % (id, str(e)))
return create_json_response(False, 'Invalid x509 Certificate', 400)
try:
sig_validate_ir = InvoiceRequest()
sig_validate_ir.ParseFromString(message.serialized_message)
sig_validate_ir.signature = ""
crypto.verify(cert, invoice_request.signature, sig_validate_ir.SerializeToString(), 'sha256')
log.info("InvoiceRequest Signature is Valid")
except Exception as e:
log.info('Bad Signature Encountered During Signature Validation [ID: %s]: %s' % (id, str(e)))
return create_json_response(False, 'InvoiceRequest Signature Verification Error', 401)
try:
log.info('Adding InvoiceRequest %s' % id)
ret_tx_id = resolver.add_paymentprotocol_message(message, id=id)
if not ret_tx_id:
log.error("Unexpected Add InvoiceRequest Failure [ID: %s]" % (id))
return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)
pp_tx_url = '%s/paymentprotocol/%s' % (request.host_url.rstrip('/'), ret_tx_id)
log.debug('Accepted InvoiceRequest [ID: %s]' % id)
return create_json_response(status=202, headers={'Access-Control-Expose-Headers': 'Location', 'Location':pp_tx_url})
except Exception as e:
log.error("Unexpected exception adding InvoiceRequest [ID: %s]: %s" % (id, str(e)))
return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)
示例7: validate_signature
def validate_signature(signature_block, log=logging.getLogger(__name__)):
"""
Validates signature of verification record or transaction accounting for presence of
"stripped_hash" in transaction signatures
:param signature_block: dict of signature
:param log: message logger
:return: True on valid signature, False otherwise.
"""
""" validate signature using provided stripped and full hashes """
verifying_key = VerifyingKey.from_pem(signature_block["public_key"])
log.info("Decoding the digest")
decoded_digest = signature_block["signature"].decode('base64')
log.info('Performing signature verification')
# checking stripped hash if this is a transaction signature
if "stripped_hash" in signature_block and signature_block['stripped_hash']:
merged_hash = merge_hashes(signature_block["stripped_hash"], signature_block["hash"])
verifying_key.verify(decoded_digest, str(merged_hash))
else:
verifying_key.verify(decoded_digest, str(signature_block["hash"]))
# signature hash is valid
return True
示例8: check_for_privkey
def check_for_privkey(keydir, jid, stderr):
# the "anonymous ID" case
if jid.startswith("anonid0-"):
return None
# the "old-style ID" case
# FIXME: once it is possible for addons to change from old-style IDs
# to new, cryptographic IDs on AMO and in Firefox, warn users that
# continuing to use old-style IDs is less secure, and provide them with
# instructions for changing to new IDs.
if not jid.startswith("jid0-"):
return None
keypath = os.path.join(keydir, jid)
if not os.path.isfile(keypath):
msg = """\
Your package.json says our ID is:
%(jid)s
But I don't have a corresponding private key in:
%(keypath)s
If you are the original developer of this package and have recently copied
the source code from a different machine to this one, you should copy the
private key into the file named above.
Otherwise, if you are a new developer who has made a copy of an existing
package to use as a starting point, you need to remove the 'id' property
from package.json, so that we can generate a new id and keypair. This will
disassociate our new package from the old one.
If you're collaborating on the same addon with a team, make sure at least
one person on the team has the private key. In the future, you may not
be able to distribute your addon without it.
"""
print >> stderr, msg % {"jid": jid, "keypath": keypath}
return None
keylines = open(keypath, "r").readlines()
keydata = {}
for line in keylines:
line = line.strip()
if line:
k, v = line.split(":", 1)
keydata[k.strip()] = v.strip()
if "private-key" not in keydata:
raise ValueError("invalid keydata: can't find 'private-key' line")
sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data")
from ecdsa import SigningKey, VerifyingKey, NIST256p
sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p)
vk = sk.get_verifying_key()
jid_2 = vk_to_jid(vk)
if jid_2 != jid:
raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid))
vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data")
vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p)
if vk.to_string() != vk2.to_string():
raise ValueError("invalid keydata: public-key mismatch")
return sk
示例9: from_point
def from_point(cls, point, network=BitcoinMainNet, **kwargs):
"""Create a PublicKey from a point on the SECP256k1 curve.
:param point: A point on the SECP256k1 curve.
:type point: SECP256k1.point
"""
verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1)
return cls.from_verifying_key(verifying_key, network=network, **kwargs)
示例10: load_public_key
def load_public_key(self):
# Check settings validity
if self.private_key:
private_key = self.load_private_key()
return private_key.get_verifying_key()
elif self.public_key:
with open(self.public_key, 'rb') as key_file:
return VerifyingKey.from_pem(key_file.read())
示例11: verify
def verify(pubKey, message, signature):
try:
vk = VerifyingKey.from_der(pubKey)
hashed = _policy_[vk.curve.name][1](message).digest()
if vk.verify(signature, hashed):
return True
else:
return False
except Exception,e:
return False
示例12: hex2key
def hex2key(hex_key):
key_bytes = unhexlify(hex_key)
if len(hex_key) == 64:
return SigningKey.from_string(key_bytes, curve=NIST256p,
hashfunc=sha256)
elif len(hex_key) == 128:
return VerifyingKey.from_string(key_bytes, curve=NIST256p,
hashfunc=sha256)
else:
raise ValueError("Key in hex form is of the wrong length.")
示例13: __init__
def __init__(self, **kwargs):
try:
config = kwargs['config']
except KeyError:
client_key = kwargs['client_key']
server_key = kwargs['server_key']
identifier = kwargs['identifier']
try:
url = kwargs['url']
except KeyError:
url = 'https://core.bravecollective.net/api'
else:
client_key = config['CORE_AUTH_PRIVATE_KEY']
server_key = config['CORE_AUTH_PUBLIC_KEY']
identifier = config['CORE_AUTH_IDENTIFIER']
try:
url = config['CORE_AUTH_URL']
except KeyError:
url = 'https://core.bravecollective.net/api'
if isinstance(client_key, SigningKey):
priv = client_key
elif hasattr(client_key, 'read'):
priv_pem = client_key.read()
priv = SigningKey.from_pem(priv_pem)
else:
with open(client_key, 'r') as f:
priv_pem = f.read()
priv = SigningKey.from_pem(priv_pem)
if isinstance(server_key, VerifyingKey):
pub = server_key
elif hasattr(server_key, 'read'):
pub_pem = server_key.read()
pub = VerifyingKey.from_pem(pub_pem)
else:
with open(server_key, 'r') as f:
pub_pem = f.read()
pub = VerifyingKey.from_pem(pub_pem)
self.api = API(url, identifier, priv, pub,
requests_session)
示例14: verify_file
def verify_file(args):
from ecdsa import VerifyingKey
public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
signature = args.signature.read()
message = args.file.read()
if verify_signature(public_key, message, signature):
print "Verification OK"
else:
print "Verification Failure"
示例15: validate_encrypted_message
def validate_encrypted_message(msg, sig_key='sender', sig_required=False):
# Verify Keys in DER Format
try:
sender_key = from_sec(msg.sender_public_key) or VerifyingKey.from_der(msg.sender_public_key)
except Exception as e:
log.warn("sender_public_key NOT in DER Format")
raise EncryptedMessageValidationError('sender_public_key not in DER format')
try:
receiver_key = from_sec(msg.receiver_public_key) or VerifyingKey.from_der(msg.receiver_public_key)
except Exception as e:
log.warn("receiver_public_key NOT in DER Format")
raise EncryptedMessageValidationError('receiver_public_key not in DER format')
# Validate Nonce
if not msg.nonce or msg.nonce < (int(time.time() * 1000000) - config.ir_nonce_allowable * 1000000):
log.warn("InvoiceRequest Nonce Missing or Before %d Seconds Ago" % config.ir_nonce_allowable)
raise NonceValidationError('Invalid Nonce')
if not msg.signature:
if not sig_required:
return
else:
raise EncryptedMessageValidationError('Signature Required')
# Validate Signature
try:
sig_verify = msg.signature
msg.signature = ''
if sig_key == 'sender':
sender_key.verify(sig_verify, msg.SerializeToString(), hashfunc=sha256, sigdecode=sigdecode_der)
elif sig_key == 'receiver':
receiver_key.verify(sig_verify, msg.SerializeToString(), hashfunc=sha256, sigdecode=sigdecode_der)
else:
raise Exception('Invalid sig_key argument')
msg.signature = sig_verify
except Exception as e:
log.warn('Signature Validation Failed: %s' % str(e))
raise EncryptedMessageValidationError('Invalid Signature')