本文整理汇总了Python中ecdsa.VerifyingKey.from_string方法的典型用法代码示例。如果您正苦于以下问题:Python VerifyingKey.from_string方法的具体用法?Python VerifyingKey.from_string怎么用?Python VerifyingKey.from_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ecdsa.VerifyingKey
的用法示例。
在下文中一共展示了VerifyingKey.from_string方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
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
示例2: import_public_key_ecc
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
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: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def __init__(self,jsonObject):
"""
Validate the signature of an already parsed JSON object
The current implementation is limited to RSA and EC
signatures and usage of the IETF JOSE algorithms
An invalid signature raises an exception
"""
if not isinstance(jsonObject, OrderedDict):
raise TypeError('JCS requires JSON to be parsed into a "OrderedDict"')
signatureObject = jsonObject['signature']
clonedSignatureObject = OrderedDict(signatureObject)
signatureValue = base64UrlDecode(signatureObject.pop('value'))
algorithmEntry = getAlgorithmEntry(signatureObject['algorithm'])
hashObject = algorithmEntry[1].new(serializeJson(jsonObject).encode("utf-8"))
jsonObject['signature'] = clonedSignatureObject
self.publicKey = signatureObject['publicKey']
keyType = self.publicKey['type']
if algorithmEntry[0]:
if keyType != 'RSA':
raise TypeError('"RSA" expected')
self.nativePublicKey = RSA.construct([cryptoBigNumDecode(self.publicKey['n']),
cryptoBigNumDecode(self.publicKey['e'])])
if not PKCS1_v1_5.new(self.nativePublicKey).verify(hashObject,signatureValue):
raise ValueError('Invalid Signature!')
else:
if keyType != 'EC':
raise TypeError('"EC" expected')
self.nativePublicKey = EC.from_string(base64UrlDecode(self.publicKey['x']) +
base64UrlDecode(self.publicKey['y']),
curve=getEcCurve(self.publicKey['curve']))
self.nativePublicKey.verify_digest(signatureValue,hashObject.digest())
示例4: check_for_privkey
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
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
示例5: hex2key
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
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.")
示例6: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def __init__(self, key=None, private=False):
self.secretKey = self.verifKey = None
# Recuperation
if key is not None:
if private:
self.secretKey = SigningKey.from_string(key, curve=NIST384p)
self.verifKey = self.secretKey.get_verifying_key()
else:
self.verifKey = VerifyingKey.from_string(key, curve=NIST384p)
# Auto-generation
else:
self.secretKey = SigningKey.generate(curve=NIST384p)
self.verifKey = self.secretKey.get_verifying_key()
示例7: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def __init__(self, identity, private, public):
"""Configure HTDSA signed request/response authentication.
To perform the cryptographic operations required for the HTDSA protocol you must pass in either instances of
`ecdsa` signing and verifying keys, or their hex-encoded versions which will be converted automatically.
Additionally, the identity token (opaque identifier) assigned to your client application by the provider will
need to be passed in so we can identify ourselves.
The private key is your application's private key. The public key is the provider's service key you were given
when registering your application.
"""
self.identity = identity
self.private = SigningKey.from_string(unhexlify(private), NIST256p) if isinstance(private, (str, unicode)) else private
self.public = VerifyingKey.from_string(unhexlify(public), NIST256p) if isinstance(public, (str, unicode)) else public
示例8: check_for_privkey
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def check_for_privkey(keydir, jid, stderr):
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 need to 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.
"""
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: valid_signature
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def valid_signature(self, signature, msg, public_key=None):
try:
if type(msg) == str:
msg = msg.encode("ascii")
#Parse public key.
if public_key == None:
public_key = self.public_key
else:
public_key = self.parse_public_key(public_key)
signature = auto_bytes(signature)
msg = auto_bytes(msg)
verify_key = VerifyingKey.from_string(public_key, SECP256k1)
return verify_key.verify(signature, msg)
except Exception as e:
print(e)
return 0
示例10: __init__
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def __init__(self, public_key=None, private_key=None):
self.id = 0
if public_key is not None:
public_key = "#" + public_key
if private_key is not None:
private_key = "#" + private_key
self.public_key = auto_bytes(public_key)
self.private_key = private_key
self.addr_version = None
self.use_compression = 1
if private_key == "":
private_key = None
#Generate key pairs.
if self.public_key == None and private_key == None:
self.sign_key = SigningKey.generate(curve=SECP256k1)
self.verify_key = self.sign_key.get_verifying_key()
self.private_key = self.sign_key.to_string()
self.public_key = self.verify_key.to_string()
return
#Init public key.
self.old_verify_str = None
if self.public_key != None:
self.public_key = self.parse_public_key(self.public_key)
self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1)
self.sign_key = None
self.old_verify_str = self.verify_key.to_string()
#Init private key.
if self.private_key != None:
#Construct keys from private key.
self.private_key = self.parse_private_key(private_key)
self.sign_key = SigningKey.from_string(self.private_key, SECP256k1)
self.verify_key = self.sign_key.get_verifying_key()
#Check private key corrosponds to public key.
if self.old_verify_str != None:
if self.old_verify_str != self.verify_key.to_string():
raise Exception("Private key doesn't corrospond to stored public key.")
示例11: from_sec
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def from_sec(string, curve=curves.SECP256k1, hashfunc=sha1, validate_point=True):
"""Convert a public key in SEC binary format to a verifying key."""
# based on code from https://github.com/richardkiss/pycoin
if string.startswith(b("\x04")):
# uncompressed
return VerifyingKey.from_string(string[1:], curve, hashfunc, validate_point)
elif string.startswith(b("\x02")) or string.startswith(b("\x03")):
# compressed
is_even = string.startswith(b("\x02"))
x = string_to_number(string[1:])
order = curve.order
p = curve.curve.p()
alpha = (pow(x, 3, p) + (curve.curve.a() * x) + curve.curve.b()) % p
beta = square_root_mod_prime(alpha, p)
if is_even == bool(beta & 1):
y = p - beta
else:
y = beta
if validate_point:
assert ecdsa.point_is_valid(curve.generator, x, y)
point = ellipticcurve.Point(curve.curve, x, y, order)
return VerifyingKey.from_public_point(point, curve, hashfunc)
示例12: from_string
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def from_string(cls, string):
return cls(VerifyingKey.from_string(string, curve=SECP256k1))
示例13: Verify
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def Verify(self, issuer = None):
if issuer == None:
issuer = self
sigAlgo = self.SignatureAlgorithm()
CertDer = encoder.encode(self.Asn1Obj.getComponentByName('tbsCertificate'))
if sigAlgo == 'sha1WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA1':
from Crypto.Hash import SHA
SigHash = SHA.new(CertDer)
elif sigAlgo == 'sha256WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA256':
from Crypto.Hash import SHA256
SigHash = SHA256.new(CertDer)
elif sigAlgo == 'sha384WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA384':
from Crypto.Hash import SHA384
SigHash = SHA384.new(CertDer)
elif sigAlgo == 'sha512WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA512':
from Crypto.Hash import SHA512
SigHash = SHA512.new(CertDer)
elif sigAlgo == 'sha224WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA224':
from Crypto.Hash import SHA224
SigHash = SHA224.new(CertDer)
elif sigAlgo == 'md2WithRSAEncryption':
from Crypto.Hash import MD2
SigHash = MD2.new(CertDer)
elif sigAlgo == 'md4WithRSAEncryption':
from Crypto.Hash import MD4
SigHash = MD4.new(CertDer)
elif sigAlgo == 'md5WithRSAEncryption':
from Crypto.Hash import MD5
SigHash = MD5.new(CertDer)
else:
raise NotImplementedError('Signature algorithm not supported ({0})'.format(sigAlgo))
if issuer.PublicKeyAlgorithm() == 'rsaEncryption':
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
PubKeyDer = issuer.PublicKey().Raw()
key = RSA.importKey(PubKeyDer)
verifier = PKCS1_v1_5.new(key)
try:
if verifier.verify(SigHash, self.Signature()):
return True
else:
return False
except ValueError:
return False
elif issuer.PublicKeyAlgorithm() == 'id-ecPublicKey':
from ecdsa import VerifyingKey, NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1
from ecdsa.util import sigdecode_der
curves = [NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1]
TheCurve = None
for crv in curves:
if crv.name == issuer.PublicKey().CurveMap():
TheCurve = crv
break
if TheCurve == None:
raise NotImplementedError('Public Key Curve not supported ({0})'.format(issuer.PublicKey().CurveMap()))
VerKey = VerifyingKey.from_string(issuer.PublicKey().Raw(), curve=TheCurve)
try:
if VerKey.verify_digest(self.Signature(), SigHash.digest(), sigdecode=sigdecode_der):
return True
else:
return False
except:
return False
else:
raise NotImplementedError('Public key algorithm not supported ({0})'.format(issuer.PublicKeyAlgorithm()))
示例14: pop_auth_values
# 需要导入模块: from ecdsa import VerifyingKey [as 别名]
# 或者: from ecdsa.VerifyingKey import from_string [as 别名]
def pop_auth_values(post_dict):
endpoint = post_dict.pop('coreproxy_endpoint')
identity = post_dict.pop('coreproxy_identity')
private = SigningKey.from_string(unhexlify(post_dict.pop('coreproxy_private')), curve=NIST256p, hashfunc=sha256)
public = VerifyingKey.from_string(unhexlify(post_dict.pop('coreproxy_public')), curve=NIST256p, hashfunc=sha256)
return endpoint, identity, private, public