本文整理汇总了Python中ecdsa.VerifyingKey.from_pem方法的典型用法代码示例。如果您正苦于以下问题:Python VerifyingKey.from_pem方法的具体用法?Python VerifyingKey.from_pem怎么用?Python VerifyingKey.from_pem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ecdsa.VerifyingKey
的用法示例。
在下文中一共展示了VerifyingKey.from_pem方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_signature
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
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
示例2: loadpubstr
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def loadpubstr(pemstring):
"""
Load a public key from PEM string
:param pemstring:
:return:
"""
return VerifyingKey.from_pem(pemstring)
示例3: load_public_key
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
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())
示例4: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
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)
示例5: verify_file
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
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"
示例6: receive_message
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def receive_message(args):
'''
'''
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from ecdsa import VerifyingKey
backend = default_backend()
key_size = 2048
key_enc = args.message.read(key_size/8)
iv = args.message.read(16)
encrypted = args.message.read()
private_key = serialization.load_pem_private_key(
args.privateKey.read(),
password=None,
backend=backend
)
key = private_key.decrypt(
key_enc,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
plain = decrypt(key, iv, encrypted)
signature = plain[len(plain)-64:]
plain = plain[:len(plain)-64]
name, extension = os.path.splitext(args.message.name)
name = os.path.basename(name)
with open(name, 'wb') as plain_file:
plain_file.write(plain)
with open('%s.sig' % name, 'wb') as sig_file:
sig_file.write(signature)
public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
if verify_signature(public_key, plain, signature):
print "Verification OK"
else:
print "Verification Failure"
示例7: recover
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def recover():
txt1 = "Students reported that students post to discussion forums more frequently and are irrevocable provided the stated conditions are met."
sig1 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccdcd7a46d769ee43467a01453214868094ca228cb5eebc953a39fb9bbaf865f4dbe1dad9b5f9f1bed75671e0db5433f0ed'''.strip().decode('hex')
txt2 = "But is this enough? And what new threats could be using it as a friend or fan.[2]"
sig2 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccd54d4f8306fe11bd4a28a491ddf596c64cd98c93d7fa9a05acead17e42e96ed1a190a2fddd7c695b8d9bce43f221b4e1b'''.strip().decode('hex')
public_key_ec = VerifyingKey.from_pem(public_key_ec_pem)
print "Verify1: " + str(public_key_ec.verify(sig1, txt1))
print "Verify2: " + str(public_key_ec.verify(sig2, txt2))
print "curve order:", public_key_ec.curve.order
key = recover_key(txt1, sig1, txt2, sig2, public_key_ec)
print key
示例8: put
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def put(self, ndef_message):
print "client has put an NDEF message"
#print ndef_message.pretty()
keyRecord = ndef_message.pop()
sigRecord = ndef_message.pop()
actionRecord = ndef_message.pop()
vk = VerifyingKey.from_pem(keyRecord.data.decode("utf-8"))
print vk.to_pem() == keyRecord.data.decode("utf-8")
print "Key created. Yay!"
try:
tmp = vk.verify(sigRecord.data, "test", hashfunc=hashlib.sha256())
print tmp
except Exception, e:
print "Signature Error"
示例9: is_jose_sig_valid
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def is_jose_sig_valid(b64_jpayload, jose_sig, vk_pem):
jpayload = b64url_dec(b64_jpayload, MalformedSignatureError)
b64_jheader = dget(jose_sig, 'protected', MalformedSignatureError)
jheader = b64url_dec(b64_jheader, MalformedSignatureError)
b64_sig = dget(jose_sig, 'signature', MalformedSignatureError)
sig_der = b64url_dec(b64_sig, MalformedSignatureError)
vk = VerifyingKey.from_pem(vk_pem)
vk_order = vk.curve.order
b64_sig_string = base64url_encode(sig_der_to_string(sig_der, vk_order))
try:
jws.verify(jheader, jpayload, b64_sig_string, vk, is_json=True)
return True
except jws.SignatureError:
return False
示例10: is_jws_sig_valid
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def is_jws_sig_valid(b64_jws_sig, vk_pem):
parts = b64_jws_sig.split('.')
if len(parts) != 3:
raise MalformedSignatureError
# Extract parts to verify signature
jheader_b64, jbody_b64, sig_der_b64 = parts
jheader = b64url_dec(jheader_b64)
jbody = b64url_dec(jbody_b64)
sig_der = b64url_dec(sig_der_b64)
vk = VerifyingKey.from_pem(vk_pem)
vk_order = vk.curve.order
sig_string_b64 = base64url_encode(sig_der_to_string(sig_der, vk_order))
try:
jws.verify(jheader, jbody, sig_string_b64, vk, is_json=True)
return True
except jws.SignatureError:
return False
示例11: RequestHandler
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
import datetime
from binascii import unhexlify
from ecdsa import VerifyingKey
import hashlib
import signal
PORT = 6002
PUBLIC_KEY = """
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEgTxPtDMGS8oOT3h6fLvYyUGq/BWeKiCB
sQPyD0+2vybIT/Xdl6hOqQd74zr4U2dkj+2q6+vwQ4DCB1X7HsFZ5JczfkO7HCdY
I7sGDvd9eUias/xPdSIL3gMbs26b0Ww0
-----END PUBLIC KEY-----
"""
vk = VerifyingKey.from_pem(PUBLIC_KEY.strip())
print(vk.to_string())
help_string = b"""
COMMANDS:
* read [file]
- prints contents of file
* time
- prints the current time
* help
- prints this message
"""
class RequestHandler(ss.StreamRequestHandler):
def run_command(self, msg):
开发者ID:grocid,项目名称:CTF,代码行数:33,代码来源:server_86326796a2f5d67d831ab67691cdb6ee495ad539e014c74b0481978315f375ee.py
示例12: string_to_number
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
from ecdsa import VerifyingKey
from ecdsa.numbertheory import inverse_mod
#sources:
#http://antonio-bc.blogspot.com/2013/12/mathconsole-ictf-2013-writeup.html
#https://neg9.org/news/2015/8/12/openctf-2015-veritable-buzz-1-crypto-300-writeup
#public key we pulled from the server
public_key_ec_pem = """
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEgTxPtDMGS8oOT3h6fLvYyUGq/BWeKiCB
sQPyD0+2vybIT/Xdl6hOqQd74zr4U2dkj+2q6+vwQ4DCB1X7HsFZ5JczfkO7HCdY
I7sGDvd9eUias/xPdSIL3gMbs26b0Ww0
-----END PUBLIC KEY-----
"""
public_key_ec = VerifyingKey.from_pem(public_key_ec_pem.strip())
curve_order = public_key_ec.curve.order
#"help" and "time" sigs we obtained from the packet capture
h = "c0e1fc4e3858ac6334cc8798fdec40790d7ad361ffc691c26f2902c41f2b7c2fd1ca916de687858953a6405423fe156cfd7287caf75247c9a32e52ab8260e7ff1e46e55594aea88731bee163035f9ee31f2c2965ac7b2cdfca6100d10ba23826"
t = "c0e1fc4e3858ac6334cc8798fdec40790d7ad361ffc691c26f2902c41f2b7c2fd1ca916de687858953a6405423fe156c0cbebcec222f83dc9dd5b0d4d8e698a08ddecb79e6c3b35fc2caaa4543d58a45603639647364983301565728b504015d"
def string_to_number(tstr):
return int(binascii.hexlify(tstr), 16)
def sha256(content):
sha256_hash = hashlib.sha256()
sha256_hash.update(content)
return sha256_hash.digest()
示例13: get_signKey
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
Get the user's verification key
Returns:
Verification key from meta-container (Keys) in meta-tenant
"""
auth = v3.Password(auth_url=AUTH_URL,username=ADMIN_USER,password=ADMIN_KEY,project_name='demo',project_domain_id="Default",user_domain_name="Default")
sess = session.Session(auth=auth)
barbican = bc.Client(session=sess)
keystone = kc.Client(session=sess)
try:
user = keystone.users.get(usrID)
dict_keys = json.loads(user.description)
ref = dict_keys.get('Verification_Key','')
ref = "%s/secrets/%s" %(BARBICAN_URL,ref)
secret_node = barbican.secrets.get(ref)
except Exception,err:
return
a = VerifyingKey.from_pem(secret_node.payload)
return a
def get_signKey(self, usrID):
"""
Get the user's sign key
Returns:
The sign key
"""
filename = '/opt/stack/swift/swift/common/middleware/sk.key'
with open(filename, 'r') as f:
sign_key = f.read()
return SigningKey.from_pem(sign_key)
示例14: verify_sth
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_pem [as 别名]
def verify_sth(sth_json,sigkey):
# Signature is calculated over this structure
# digitally-signed struct {
# Version version;
# SignatureType signature_type = tree_hash;
# uint64 timestamp;
# uint64 tree_size;
# opaque sha256_root_hash[32];
# } TreeHeadSignature;
treehash = struct.pack(">B",1)
version = struct.pack(">B",0)
# put the decimal encoded values into byte buffers
tstampbuf = struct.pack(">Q",sth_json["timestamp"])
tsizebuf = struct.pack(">Q",sth_json["tree_size"])
# convert base64 root hash to binary
srhbuf = base64.b64decode(sth_json["sha256_root_hash"])
buf = version + treehash + tstampbuf + tsizebuf + srhbuf
# Per RFC 6962, either support RSA or ECDSA with NIST256p curves
# determine this by deserializing TLS signature structure
print base64.b64encode(buf)
# Get SHA256 digest of buffer
m = SHA256.new(buf)
# convert base64 signature in message to binary
sigbuf = base64.b64decode(sth_json["tree_head_signature"])
b = io.BytesIO(sigbuf)
hashalgo ,= struct.unpack(">b",b.read(1))
sigalgo ,= struct.unpack(">b",b.read(1))
# Signature is opaque data structure per RFC 5246. Length of the signature
# is stored in first n bytes where n is number of bytes sufficient to hold max size
# of signature
# Defined as
# struct {
# SignatureAndHashAlgorithm algorithm;
# opaque signature<0..2^16-1>;
# } DigitallySigned;
# 2 bytes needed to specify 2^16 - 1
siglen ,= struct.unpack(">h",b.read(2))
buf2 = b.read()
if siglen != len(buf2):
print 'Signature invalid; signature wrong length'
return False
# Verify the signature
print sigkey
# From RFC 5246 section 7.4.1.4.1
# enum {
# none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
# sha512(6), (255)
# } HashAlgorithm;
# enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
# SignatureAlgorithm;
if hashalgo == 4 and sigalgo == 3:
vk = VerifyingKey.from_pem(sigkey)
try:
vk.verify(buf2,buf,hashfunc=hashlib.sha256,
sigdecode=ecdsa.util.sigdecode_der)
print "The signature is authentic."
except BadSignatureError:
print "The signature is not authentic."
return False
else:
print "Unsupported signature/hash algorithm"
return False
return True