本文整理汇总了Python中ecdsa.VerifyingKey.from_der方法的典型用法代码示例。如果您正苦于以下问题:Python VerifyingKey.from_der方法的具体用法?Python VerifyingKey.from_der怎么用?Python VerifyingKey.from_der使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ecdsa.VerifyingKey
的用法示例。
在下文中一共展示了VerifyingKey.from_der方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
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: process_invoicerequest
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
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)
示例3: verify
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
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
示例4: validate_encrypted_message
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
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')
示例5: main
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
def main(argv):
"""
Main procedure to sign a binary
"""
parser = argparse.ArgumentParser(description='convert der to raw')
parser.add_argument('-s','--secretkey_file', help='Secret key', required=True)
parser.add_argument('-p','--publickey_file', help='Public key', required=True)
args = parser.parse_args()
secretkey_file = args.secretkey_file
publickey_file = args.publickey_file
privkey = SigningKey.from_der(open(secretkey_file).read())
pubkey = VerifyingKey.from_der(open(publickey_file).read())
open(secretkey_file[0:-4] + ".bin", "wb").write(privkey.to_string())
open(publickey_file[0:-4] + ".bin", "wb").write(pubkey.to_string())
示例6: test_bip75_flow
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
def test_bip75_flow(self):
###################
# Load Crypto Keys
###################
self.x509_sender_cert = crypto.load_certificate(crypto.FILETYPE_PEM, SENDER_CERT)
self.x509_sender_cert_privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, SENDER_CERT_PRIVKEY)
self.x509_receiver_cert = crypto.load_certificate(crypto.FILETYPE_PEM, RECEIVER_CERT)
self.x509_receiver_cert_privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, RECEIVER_CERT_PRIVKEY)
#########################
# Create InvoiceRequest
#########################
log.info("Building InvoiceRequest")
sender_certs = X509Certificates()
sender_certs.certificate.append(ssl.PEM_cert_to_DER_cert(crypto.dump_certificate(crypto.FILETYPE_PEM, self.x509_sender_cert)))
invoice_request = InvoiceRequest()
invoice_request.sender_public_key = BIP75FunctionalTest.sender_sk.get_verifying_key().to_der()
invoice_request.amount = 75
invoice_request.pki_type = 'x509+sha256'
invoice_request.pki_data = sender_certs.SerializeToString()
invoice_request.notification_url = 'https://notify.me/longId'
invoice_request.signature = ""
# Handle x509 Signature
sig = crypto.sign(self.x509_sender_cert_privkey, invoice_request.SerializeToString(), 'sha1')
invoice_request.signature = sig
##################################
# Create Encrypted InvoiceRequest
##################################
eir = self.create_encrypted_protocol_message(
message=invoice_request,
receiver_pubkey=BIP75FunctionalTest.receiver_sk.get_verifying_key(),
sender_pubkey=BIP75FunctionalTest.sender_sk.get_verifying_key(),
private_key=BIP75FunctionalTest.sender_sk
)
BIP75FunctionalTest.identifier = eir.identifier
#############################
# Sign & Submit HTTP Request
#############################
post_url = "%s/address/testid/resolve" % self.get_server_url()
msg_sig = BIP75FunctionalTest.sender_sk.sign(post_url + eir.SerializeToString())
ir_headers = {
'X-Identity': BIP75FunctionalTest.sender_sk.get_verifying_key().to_der().encode('hex'),
'X-Signature': msg_sig.encode('hex'),
'Content-Type': 'application/bitcoin-encrypted-paymentprotocol-message',
'Content-Transfer-Encoding': 'binary'
}
log.info("Submitting InvoiceRequest using an EncryptedProtocolMessage")
response = requests.post(post_url, headers=ir_headers, data=eir.SerializeToString())
# Validate Response
self.assertEqual(202, response.status_code)
self.assertTrue(response.headers.get('Location').startswith('https://%s/paymentprotocol' % config.site_url))
self.payment_id = response.headers.get('Location').rsplit('/', 1)[1]
log.info('Payment ID: %s' % self.payment_id)
###############################################
# Get Pending InvoiceRequests from Addressimo
###############################################
sign_url = "%s/address/testid/paymentprotocol" % self.get_server_url()
msg_sig = BIP75FunctionalTest.receiver_sk.sign(sign_url)
ir_req_headers = {
'X-Identity': BIP75FunctionalTest.receiver_sk.get_verifying_key().to_der().encode('hex'),
'X-Signature': msg_sig.encode('hex')
}
log.info("Retrieving Encrypted InvoiceRequests")
response = requests.get(sign_url, headers=ir_req_headers)
log.info("Encrypted InvoiceRequest Retrieval Response [CODE: %d | TEXT: %s]" % (response.status_code, response.text))
self.assertEqual(200, response.status_code)
self.assertIsNotNone(response.text)
###############################################
# Retrieve and Decrypt Encrypted InvoiceRequest
###############################################
received_eir = None
for epm in response.json()['encrypted_protocol_messages']:
_local_msg = self.parse_protocol_message(epm.decode('hex'))
if _local_msg.message_type == ProtocolMessageType.Value('INVOICE_REQUEST') and _local_msg.identifier == BIP75FunctionalTest.identifier:
received_eir = _local_msg
if not received_eir:
self.fail('Failed to Retrieve Encrypted InvoiceRequest message')
sender_vk = VerifyingKey.from_der(received_eir.sender_public_key)
self.assertEqual(received_eir.receiver_public_key, BIP75FunctionalTest.receiver_sk.get_verifying_key().to_der())
received_invoice_request = self.get_decrypted_protocol_message(received_eir, sender_vk, BIP75FunctionalTest.receiver_sk)
#########################
#.........这里部分代码省略.........
示例7: delete_paymentprotocol_message
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
def delete_paymentprotocol_message(identifier, message_type, id=None, tx_id=None):
resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)
if id:
not_verified = verify_public_key()
if not_verified:
return not_verified
if not id and not tx_id:
log.error('Missing ID and TX_ID, Returning Error')
return create_json_response(False, 'Invalid Payment Protocol Message Retrieval Attempt', 400)
if id:
try:
id_obj = resolver.get_id_obj(id)
except Exception as e:
log.error('Exception retrieving id_obj [ID: %s | Exception: %s]' % (id, str(e)))
return create_json_response(False, 'Exception Occurred, Please Try Again Later.', 500)
if not id_obj:
log.error('Unable to retrieve id_obj [ID: %s]' % id)
return create_json_response(False, 'ID Not Recognized', 404)
messages = resolver.get_paymentprotocol_messages(id=id)
if tx_id:
messages = resolver.get_paymentprotocol_messages(tx_id=tx_id)
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)]
for transaction_id, tx in messages.iteritems():
for msg in tx.get('messages', []):
parsed_msg = parse_paymentprotocol_message(msg)
if parsed_msg.identifier != identifier.decode('hex'):
log.debug('Skipping Non-Matching Identifier [TYPE: %s | TX: %s]' % (message_type.upper(), transaction_id))
continue
if isinstance(parsed_msg, EncryptedProtocolMessage) and (parsed_msg.sender_public_key in allowed_keys or parsed_msg.receiver_public_key in allowed_keys):
if resolver.delete_paymentprotocol_message(identifier.decode('hex'), message_type, tx_id=transaction_id):
log.info('Deleted PaymentProtocol Message [TYPE: %s | TX: %s]' % (message_type.upper(), transaction_id))
return create_json_response(True, 'Payment Protocol Message Deleted', 204)
else:
log.info('PaymentProtocol Message Delete Failure [TYPE: %s | TX: %s]' % (message_type.upper(), transaction_id))
return create_json_response(False, 'Payment Protocol Message Does Not Exist', 404)
elif isinstance(parsed_msg, ProtocolMessage) and parsed_msg.message_type == ProtocolMessageType.Value('INVOICE_REQUEST'):
if parsed_msg.message_type == 'InvoiceRequest' and (parsed_msg.sender_public_key in allowed_keys or id == tx.get('receiver')):
if resolver.delete_paymentprotocol_message(identifier.decode('hex'), message_type, tx_id=transaction_id):
log.info('Deleted PaymentProtocol Message [TYPE: %s | TX: %s]' % (message_type.upper(), transaction_id))
return create_json_response(True, 'Payment Protocol Message Deleted', 204)
else:
log.info('PaymentProtocol Message Delete Failure [TYPE: %s | TX: %s]' % (message_type.upper(), transaction_id))
return create_json_response(False, 'Payment Protocol Message Delete Failed, Try Again Later', 503)
return create_json_response(False, 'Matching Payment Protocol Message Not Found', 404)
示例8: submit_paymentprotocol_message
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
def submit_paymentprotocol_message(id=None, tx_id=None, ignore_pubkey_verify=False):
resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)
if not id and not tx_id:
log.error('Missing ID and TX_ID, Returning Error')
return create_json_response(False, 'Invalid Payment Protocol Message Retrieval Attempt', 400)
if request.content_type not in PAYMENT_PROTOCOL_CONTENT_TYPES:
log.warn('Received Request with Invalid Content-Type [CONTENT-TYPE: %s]' % str(request.content_type))
return create_json_response(False, 'Invalid Content-Type for Payment Protocol Message', 400)
if request.headers.get('Content-Transfer-Encoding', '') != 'binary':
log.warn("PaymentProtocol Message Content-Transfer-Encoding IS NOT set to binary")
return create_json_response(False, 'PaymentProtocol Message Content-Transfer-Encoding MUST be binary', 400)
##########################################################
# Verify ID or TX Exists (and is correctly configured
##########################################################
if id:
if not ignore_pubkey_verify:
not_verified = verify_public_key()
if not_verified:
return not_verified
try:
id_obj = resolver.get_id_obj(id)
except Exception as e:
log.error('Exception retrieving id_obj [ID: %s | Exception: %s]' % (id, str(e)))
return create_json_response(False, 'Exception Occurred, Please Try Again Later.', 503)
if not id_obj:
log.error('Unable to retrieve id_obj [ID: %s]' % id)
return create_json_response(False, 'ID Not Recognized', 404)
if not id_obj.paymentprotocol_only:
log.warn("PaymentProtocol Endpoint POST Submitted to Non-PaymentProtocol Endpoint")
return create_json_response(False, 'Not a PaymentProtocol Endpoint', 400)
if tx_id and not resolver.get_paymentprotocol_messages(tx_id=tx_id):
log.error('No Messages Exist, Unable to Add Message to Transaction [TX ID: %s]' % str(tx_id))
return create_json_response(False, 'Transaction Does Not Exist', 404)
########################################
# Handle ProtocolMessages
########################################
message = parse_paymentprotocol_message(request.get_data())
if not message:
log.error('Unable to Parse Payment Protocol Message, Returning an Error')
return create_json_response(False, 'Unable to Parse Payment Protocol', 400)
# Verify Identifier is Set
if not message.identifier:
log.warn('Identifier is Missing from Payment Protocol Message, Rejecting')
return create_json_response(False, 'Payment Protocol Message Missing Required Field: identifier', 400)
if isinstance(message, ProtocolMessage) and message.message_type != ProtocolMessageType.Value('INVOICE_REQUEST'):
log.warn("Non-InvoiceRequest Message Send via Protocol Message")
return create_json_response(False, 'Only InvoiceRequest Messages May Be Send Using ProtocolMessages, all others require EncryptedProtocolMessages', 400)
#################################################
# Verify Encrypted Protocol Message Signatures
#################################################
if isinstance(message, EncryptedProtocolMessage):
required_identity = message.sender_public_key
text_identity = 'sender'
if message.message_type in [ProtocolMessageType.Value('PAYMENT_REQUEST'), ProtocolMessageType.Value('PAYMENT_ACK')]:
required_identity = message.receiver_public_key
text_identity = 'receiver'
# Determine Possible Values the sender_public_key could have
vk = from_sec(request.headers.get('x-identity').decode('hex')) or VerifyingKey.from_der(request.headers.get('x-identity').decode('hex'))
pk_vals = [vk.to_der().encode('hex'), to_sec(vk, False).encode('hex'), to_sec(vk, True).encode('hex')]
# Verify the Sender is the message signer
if required_identity.encode('hex') not in pk_vals:
log.warn("Message %s Public Key Does Not Match X-Identity Public Key" % text_identity)
return create_json_response(False, 'Message %s Public Key Does Not Match X-Identity Public Key' % text_identity, 400)
# Check Nonce is Increasing
if message.message_type != ProtocolMessageType.Value('INVOICE_REQUEST') and resolver.get_tx_last_nonce(message, id=id) > message.nonce:
log.warn('PaymentProtocol EncryptedProtocolMessage Submitted with Invalid Nonce')
return create_json_response(False, 'Nonce is Not Valid', 400)
# Validate Encrypted Message
try:
validate_encrypted_message(message, sig_key=text_identity, sig_required=True)
except EncryptedMessageValidationError as e:
return create_json_response(False, str(e), 400)
except NonceValidationError as e:
return create_json_response(False, str(e), 400, data={'utime': int(time.time() * 1000000)})
# Process Submission
if message.message_type == ProtocolMessageType.Value('INVOICE_REQUEST'):
return process_invoicerequest(message, id)
elif message.message_type == ProtocolMessageType.Value('PAYMENT_REQUEST'):
return process_paymentrequest(message, id)
#.........这里部分代码省略.........
示例9: verifying_key
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_der [as 别名]
def verifying_key(self):
if self._verifying_key is None:
self._verifying_key = VerifyingKey.from_der(self._der)
return self._verifying_key